stormcloud-video-player 0.8.62 → 0.8.63
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/StormcloudPlayer.cjs +21 -23
- package/lib/StormcloudPlayer.cjs.map +1 -1
- package/lib/index.cjs +21 -23
- package/lib/index.cjs.map +1 -1
- package/lib/index.js +21 -23
- package/lib/index.js.map +1 -1
- package/lib/player/AdConfigManager.cjs +21 -23
- package/lib/player/AdConfigManager.cjs.map +1 -1
- package/lib/player/AdConfigManager.d.cts +1 -1
- package/lib/player/StormcloudVideoPlayer.cjs +21 -23
- package/lib/player/StormcloudVideoPlayer.cjs.map +1 -1
- package/lib/players/HlsPlayer.cjs +21 -23
- package/lib/players/HlsPlayer.cjs.map +1 -1
- package/lib/players/index.cjs +21 -23
- package/lib/players/index.cjs.map +1 -1
- package/lib/ui/StormcloudVideoPlayer.cjs +21 -23
- package/lib/ui/StormcloudVideoPlayer.cjs.map +1 -1
- package/lib/utils/ctvVastSignals.cjs +1 -21
- package/lib/utils/ctvVastSignals.cjs.map +1 -1
- package/lib/utils/vastEnvironmentSignals.cjs +1 -21
- package/lib/utils/vastEnvironmentSignals.cjs.map +1 -1
- package/lib/utils/vastMacros.cjs +17 -0
- package/lib/utils/vastMacros.cjs.map +1 -1
- package/lib/utils/vastMacros.d.cts +2 -1
- package/package.json +1 -1
|
@@ -1,3 +1,3 @@
|
|
|
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 self?self:e||self).StormcloudVP={})}(this,function(e){"use strict";function t(e,t){this.v=e,this.k=t}function r(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=Array(t);r<t;r++)i[r]=e[r];return i}function i(e){if(Array.isArray(e))return e}function n(e,t,r,i,n,a,s){try{var o=e[a](s),l=o.value}catch(e){return void r(e)}o.done?t(l):Promise.resolve(l).then(i,n)}function a(e,t,r){return t=h(t),m(e,v()?Reflect.construct(t,r||[],h(e).constructor):t.apply(e,r))}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,I(i.key),i)}}function l(e,t,r){return t&&o(e.prototype,t),r&&o(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function u(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=L(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var i=0,n=function(){};return{s:n,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:n}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,s=!0,o=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return s=e.done,e},e:function(e){o=!0,a=e},f:function(){try{s||null==r.return||r.return()}finally{if(o)throw a}}}}function c(e,t,r){return(t=I(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function d(){return d="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(e,t,r){var i=T(e,t);if(i){var n=Object.getOwnPropertyDescriptor(i,t);return n.get?n.get.call(arguments.length<3?e:r):n.value}},d.apply(null,arguments)}function h(e){return h=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},h(e)}function f(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&&E(e,t)}function v(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(v=function(){return!!e})()}function g(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function p(){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 m(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 y(){
|
|
2
2
|
/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
|
|
3
|
-
var e,t,r="function"==typeof Symbol?Symbol:{},i=r.iterator||"@@iterator",n=r.toStringTag||"@@toStringTag";function a(r,i,n,a){var l=i&&i.prototype instanceof o?i:o,u=Object.create(l.prototype);return k(u,"_invoke",function(r,i,n){var a,o,l,u=0,c=n||[],d=!1,h={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,r){return a=t,o=0,l=e,h.n=r,s}};function f(r,i){for(o=r,l=i,t=0;!d&&u&&!n&&t<c.length;t++){var n,a=c[t],f=h.p,v=a[2];r>3?(n=v===i)&&(l=a[(o=a[4])?5:(o=3,3)],a[4]=a[5]=e):a[0]<=f&&((n=r<2&&f<a[1])?(o=0,h.v=i,h.n=a[1]):f<v&&(n=r<3||a[0]>i||i>v)&&(a[4]=r,a[5]=i,h.n=v,o=0))}if(n||r>1)return s;throw d=!0,i}return function(n,c,v){if(u>1)throw TypeError("Generator is already running");for(d&&1===c&&f(c,v),o=c,l=v;(t=o<2?e:l)||!d;){a||(o?o<3?(o>1&&(h.n=-1),f(o,l)):h.n=l:h.v=l);try{if(u=2,a){if(o||(n="next"),t=a[n]){if(!(t=t.call(a,l)))throw TypeError("iterator result is not an object");if(!t.done)return t;l=t.value,o<2&&(o=0)}else 1===o&&(t=a.return)&&t.call(a),o<2&&(l=TypeError("The iterator does not provide a '"+n+"' method"),o=1);a=e}else if((t=(d=h.n<0)?l:r.call(i,h))!==s)break}catch(t){a=e,o=1,l=t}finally{u=1}}return{value:t,done:d}}}(r,n,a),!0),u}var s={};function o(){}function l(){}function u(){}t=Object.getPrototypeOf;var c=[][i]?t(t([][i]())):(k(t={},i,function(){return this}),t),d=u.prototype=o.prototype=Object.create(c);function h(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,k(e,n,"GeneratorFunction")),e.prototype=Object.create(d),e}return l.prototype=u,k(d,"constructor",u),k(u,"constructor",l),l.displayName="GeneratorFunction",k(u,n,"GeneratorFunction"),k(d),k(d,n,"Generator"),k(d,i,function(){return this}),k(d,"toString",function(){return"[object Generator]"}),(y=function(){return{w:a,m:h}})()}function k(e,t,r,i){var n=Object.defineProperty;try{n({},"",{})}catch(e){n=0}k=function(e,t,r,i){function a(t,r){k(e,t,function(e){return this._invoke(t,r,e)})}t?n?n(e,t,{value:r,enumerable:!i,configurable:!i,writable:!i}):e[t]=r:(a("next",0),a("throw",1),a("return",2))},k(e,t,r,i)}function E(e,t){return E=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},E(e,t)}function S(e,t){return i(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var i,n,a,s,o=[],l=!0,u=!1;try{if(a=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;l=!1}else for(;!(l=(i=a.call(r)).done)&&(o.push(i.value),o.length!==t);l=!0);}catch(e){u=!0,n=e}finally{try{if(!l&&null!=r.return&&(s=r.return(),Object(s)!==s))return}finally{if(u)throw n}}return o}}(e,t)||L(e,t)||p()}function T(e,t){for(;!{}.hasOwnProperty.call(e,t)&&null!==(e=h(e)););return e}function A(e,t,r,i){var n=d(h(1&i?e.prototype:e),t,r);return 2&i&&"function"==typeof n?function(e){return n.apply(r,e)}:n}function b(e){return function(e){if(Array.isArray(e))return r(e)}(e)||g(e)||L(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 I(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var i=r.call(e,t||"default");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}function R(e){return R="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},R(e)}function L(e,t){if(e){if("string"==typeof e)return r(e,t);var i={}.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?r(e,t):void 0}}function P(e){var r,i;function n(r,i){try{var s=e[r](i),o=s.value,l=o instanceof t;Promise.resolve(l?o.v:o).then(function(t){if(l){var i="return"===r&&o.k?r:"next";if(!o.k||t.done)return n(i,t);t=e[i](t).value}a(!!s.done,t)},function(e){n("throw",e)})}catch(e){a(2,e)}}function a(e,t){2===e?r.reject(t):r.resolve({value:t,done:e}),(r=r.next)?n(r.key,r.arg):i=null}this._invoke=function(e,t){return new Promise(function(a,s){var o={key:e,arg:t,resolve:a,reject:s,next:null};i?i=i.next=o:(r=i=o,n(e,t))})},"function"!=typeof e.return&&(this.return=void 0)}function w(e){var t="function"==typeof Map?new Map:void 0;return w=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return function(e,t,r){if(v())return Reflect.construct.apply(null,arguments);var i=[null];i.push.apply(i,t);var n=new(e.bind.apply(e,i));return r&&E(n,r.prototype),n}(e,arguments,h(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),E(r,e)},w(e)}P.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},P.prototype.next=function(e){return this._invoke("next",e)},P.prototype.throw=function(e){return this._invoke("throw",e)},P.prototype.return=function(e){return this._invoke("return",e)};var C=function(e,t){return C=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},C(e,t)};function D(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}C(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var _=function(){return _=Object.assign||function(e){for(var t,r=1,i=arguments.length;r<i;r++)for(var n in t=arguments[r])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e},_.apply(this,arguments)};function M(e,t){var r={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(r[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(e);n<i.length;n++)t.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(e,i[n])&&(r[i[n]]=e[i[n]])}return r}function x(e,t,r,i){return new(r||(r=Promise))(function(n,a){function s(e){try{l(i.next(e))}catch(e){a(e)}}function o(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,o)}l((i=i.apply(e,t||[])).next())})}function O(e,t){var r,i,n,a={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]},s=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return s.next=o(0),s.throw=o(1),s.return=o(2),"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(o){return function(l){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,o[0]&&(a=0)),a;)try{if(r=1,i&&(n=2&o[0]?i.return:o[0]?i.throw||((n=i.return)&&n.call(i),0):i.next)&&!(n=n.call(i,o[1])).done)return n;switch(i=0,n&&(o=[2&o[0],n.value]),o[0]){case 0:case 1:n=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,i=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!(n=a.trys,(n=n.length>0&&n[n.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!n||o[1]>n[0]&&o[1]<n[3])){a.label=o[1];break}if(6===o[0]&&a.label<n[1]){a.label=n[1],n=o;break}if(n&&a.label<n[2]){a.label=n[2],a.ops.push(o);break}n[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],i=0}finally{r=n=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}}Object.create;function F(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],i=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function N(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var i,n,a=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(i=a.next()).done;)s.push(i.value)}catch(e){n={error:e}}finally{try{i&&!i.done&&(r=a.return)&&r.call(a)}finally{if(n)throw n.error}}return s}function B(e,t,r){if(r||2===arguments.length)for(var i,n=0,a=t.length;n<a;n++)!i&&n in t||(i||(i=Array.prototype.slice.call(t,0,n)),i[n]=t[n]);return e.concat(i||Array.prototype.slice.call(t))}Object.create;"function"==typeof SuppressedError&&SuppressedError;"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function U(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var V,G={exports:{}},H={};var K,j={exports:{}},q={};function W(){if(K)return q;K=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),n=Symbol.for("react.profiler"),a=Symbol.for("react.consumer"),s=Symbol.for("react.context"),o=Symbol.for("react.forward_ref"),l=Symbol.for("react.suspense"),u=Symbol.for("react.memo"),c=Symbol.for("react.lazy"),d=Symbol.for("react.activity"),h=Symbol.for("react.view_transition"),f=Symbol.iterator;var v={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},g=Object.assign,p={};function m(e,t,r){this.props=e,this.context=t,this.refs=p,this.updater=r||v}function y(){}function k(e,t,r){this.props=e,this.context=t,this.refs=p,this.updater=r||v}m.prototype.isReactComponent={},m.prototype.setState=function(e,t){if("object"!==R(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")},y.prototype=m.prototype;var E=k.prototype=new y;E.constructor=k,g(E,m.prototype),E.isPureReactComponent=!0;var S=Array.isArray;function T(){}var A={H:null,A:null,T:null,S:null},b=Object.prototype.hasOwnProperty;function I(t,r,i){var n=i.ref;return{$$typeof:e,type:t,key:r,ref:void 0!==n?n:null,props:i}}function L(t){return"object"===R(t)&&null!==t&&t.$$typeof===e}var P=/\/+/g;function w(e,t){return"object"===R(e)&&null!==e&&null!=e.key?(r=""+e.key,i={"=":"=0",":":"=2"},"$"+r.replace(/[=:]/g,function(e){return i[e]})):t.toString(36);var r,i}function C(r,i,n,a,s){var o=R(r);"undefined"!==o&&"boolean"!==o||(r=null);var l,u,d=!1;if(null===r)d=!0;else switch(o){case"bigint":case"string":case"number":d=!0;break;case"object":switch(r.$$typeof){case e:case t:d=!0;break;case c:return C((d=r._init)(r._payload),i,n,a,s)}}if(d)return s=s(r),d=""===a?"."+w(r,0):a,S(s)?(n="",null!=d&&(n=d.replace(P,"$&/")+"/"),C(s,i,n,"",function(e){return e})):null!=s&&(L(s)&&(l=s,u=n+(null==s.key||r&&r.key===s.key?"":(""+s.key).replace(P,"$&/")+"/")+d,s=I(l.type,u,l.props)),i.push(s)),1;d=0;var h,v=""===a?".":a+":";if(S(r))for(var g=0;g<r.length;g++)d+=C(a=r[g],i,n,o=v+w(a,g),s);else if("function"==typeof(g=null===(h=r)||"object"!==R(h)?null:"function"==typeof(h=f&&h[f]||h["@@iterator"])?h:null))for(r=g.call(r),g=0;!(a=r.next()).done;)d+=C(a=a.value,i,n,o=v+w(a,g++),s);else if("object"===o){if("function"==typeof r.then)return C(function(e){switch(e.status){case"fulfilled":return e.value;case"rejected":throw e.reason;default:switch("string"==typeof e.status?e.then(T,T):(e.status="pending",e.then(function(t){"pending"===e.status&&(e.status="fulfilled",e.value=t)},function(t){"pending"===e.status&&(e.status="rejected",e.reason=t)})),e.status){case"fulfilled":return e.value;case"rejected":throw e.reason}}throw e}(r),i,n,a,s);throw i=String(r),Error("Objects are not valid as a React child (found: "+("[object Object]"===i?"object with keys {"+Object.keys(r).join(", ")+"}":i)+"). If you meant to render a collection of children, use an array instead.")}return d}function D(e,t,r){if(null==e)return e;var i=[],n=0;return C(e,i,"","",function(e){return t.call(r,e,n++)}),i}function _(e){if(-1===e._status){var t=(0,e._result)();t.then(function(r){0!==e._status&&-1!==e._status||(e._status=1,e._result=r,void 0===t.status&&(t.status="fulfilled",t.value=r))},function(r){0!==e._status&&-1!==e._status||(e._status=2,e._result=r,void 0===t.status&&(t.status="rejected",t.reason=r))}),-1===e._status&&(e._status=0,e._result=t)}if(1===e._status)return e._result.default;throw e._result}var M="function"==typeof reportError?reportError:function(e){if("object"===("undefined"==typeof window?"undefined":R(window))&&"function"==typeof window.ErrorEvent){var t=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:"object"===R(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":R(process))&&"function"==typeof process.emit)return void process.emit("uncaughtException",e);console.error(e)};function x(e){var t=A.T,r={};r.types=null!==t?t.types:null,A.T=r;try{var i=e(),n=A.S;null!==n&&n(r,i),"object"===R(i)&&null!==i&&"function"==typeof i.then&&i.then(T,M)}catch(e){M(e)}finally{null!==t&&null!==r.types&&(t.types=r.types),A.T=t}}var O={map:D,forEach:function(e,t,r){D(e,function(){t.apply(this,arguments)},r)},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(!L(e))throw Error("React.Children.only expected to receive a single React element child.");return e}};return q.Activity=d,q.Children=O,q.Component=m,q.Fragment=r,q.Profiler=n,q.PureComponent=k,q.StrictMode=i,q.Suspense=l,q.ViewTransition=h,q.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=A,q.__COMPILER_RUNTIME={__proto__:null,c:function(e){return A.H.useMemoCache(e)}},q.addTransitionType=function e(t){var r=A.T;if(null!==r){var i=r.types;null===i?r.types=[t]:-1===i.indexOf(t)&&i.push(t)}else x(e.bind(null,t))},q.cache=function(e){return function(){return e.apply(null,arguments)}},q.cacheSignal=function(){return null},q.cloneElement=function(e,t,r){if(null==e)throw Error("The argument must be a React element, but you passed "+e+".");var i=g({},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||(i[a]=t[a]);var a=arguments.length-2;if(1===a)i.children=r;else if(1<a){for(var s=Array(a),o=0;o<a;o++)s[o]=arguments[o+2];i.children=s}return I(e.type,n,i)},q.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},q.createElement=function(e,t,r){var i,n={},a=null;if(null!=t)for(i in void 0!==t.key&&(a=""+t.key),t)b.call(t,i)&&"key"!==i&&"__self"!==i&&"__source"!==i&&(n[i]=t[i]);var s=arguments.length-2;if(1===s)n.children=r;else if(1<s){for(var o=Array(s),l=0;l<s;l++)o[l]=arguments[l+2];n.children=o}if(e&&e.defaultProps)for(i in s=e.defaultProps)void 0===n[i]&&(n[i]=s[i]);return I(e,a,n)},q.createRef=function(){return{current:null}},q.forwardRef=function(e){return{$$typeof:o,render:e}},q.isValidElement=L,q.lazy=function(e){return{$$typeof:c,_payload:{_status:-1,_result:e},_init:_}},q.memo=function(e,t){return{$$typeof:u,type:e,compare:void 0===t?null:t}},q.startTransition=x,q.unstable_useCacheRefresh=function(){return A.H.useCacheRefresh()},q.use=function(e){return A.H.use(e)},q.useActionState=function(e,t,r){return A.H.useActionState(e,t,r)},q.useCallback=function(e,t){return A.H.useCallback(e,t)},q.useContext=function(e){return A.H.useContext(e)},q.useDebugValue=function(){},q.useDeferredValue=function(e,t){return A.H.useDeferredValue(e,t)},q.useEffect=function(e,t){return A.H.useEffect(e,t)},q.useEffectEvent=function(e){return A.H.useEffectEvent(e)},q.useId=function(){return A.H.useId()},q.useImperativeHandle=function(e,t,r){return A.H.useImperativeHandle(e,t,r)},q.useInsertionEffect=function(e,t){return A.H.useInsertionEffect(e,t)},q.useLayoutEffect=function(e,t){return A.H.useLayoutEffect(e,t)},q.useMemo=function(e,t){return A.H.useMemo(e,t)},q.useOptimistic=function(e,t){return A.H.useOptimistic(e,t)},q.useReducer=function(e,t,r){return A.H.useReducer(e,t,r)},q.useRef=function(e){return A.H.useRef(e)},q.useState=function(e){return A.H.useState(e)},q.useSyncExternalStore=function(e,t,r){return A.H.useSyncExternalStore(e,t,r)},q.useTransition=function(){return A.H.useTransition()},q.version="19.3.0",q}var Y;j.exports;function z(){return Y||(Y=1,j.exports=W()),j.exports}var X;G.exports;var Q=(X||(X=1,G.exports=function(){if(V)return H;V=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function r(t,r,i){var n=null;if(void 0!==i&&(n=""+i),void 0!==r.key&&(n=""+r.key),"key"in r)for(var a in i={},r)"key"!==a&&(i[a]=r[a]);else i=r;return r=i.ref,{$$typeof:e,type:t,key:n,ref:void 0!==r?r:null,props:i}}return H.Fragment=t,H.jsx=r,H.jsxs=r,H}()),G.exports),$=z(),J=U($),Z=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},ee=Number.isSafeInteger||function(e){return"number"==typeof e&&Math.abs(e)<=te},te=Number.MAX_SAFE_INTEGER||9007199254740991,re=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}({}),ie=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.PLAYLIST_UNCHANGED_ERROR="playlistUnchangedError",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_APPEND_NO_PROGRESS="bufferAppendNoProgress",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.MEDIA_SOURCE_REQUIRES_RESET="mediaSourceRequiresReset",e.UNKNOWN="unknown",e}({}),ne=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}({});function ae(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var se,oe={exports:{}};var le=(se||(se=1,function(e){var t,r,i,n,a;t=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,i=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(e,t,i){if(i=i||{},e=e.trim(),!(t=t.trim())){if(!i.alwaysNormalize)return e;var n=a.parseURL(e);if(!n)throw new Error("Error trying to parse base URL.");return n.path=a.normalizePath(n.path),a.buildURLFromParts(n)}var s=a.parseURL(t);if(!s)throw new Error("Error trying to parse relative URL.");if(s.scheme)return i.alwaysNormalize?(s.path=a.normalizePath(s.path),a.buildURLFromParts(s)):t;var o=a.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=r.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var u={scheme:o.scheme,netLoc:s.netLoc,path:null,params:s.params,query:s.query,fragment:s.fragment};if(!s.netLoc&&(u.netLoc=o.netLoc,"/"!==s.path[0]))if(s.path){var c=o.path,d=c.substring(0,c.lastIndexOf("/")+1)+s.path;u.path=a.normalizePath(d)}else u.path=o.path,s.params||(u.params=o.params,s.query||(u.query=o.query));return null===u.path&&(u.path=i.alwaysNormalize?a.normalizePath(s.path):s.path),a.buildURLFromParts(u)},parseURL:function(e){var r=t.exec(e);return r?{scheme:r[1]||"",netLoc:r[2]||"",path:r[3]||"",params:r[4]||"",query:r[5]||"",fragment:r[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(i,"");e.length!==(e=e.replace(n,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}},e.exports=a}(oe)),oe.exports),ue=l(function e(){s(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=function(e){return e.MANIFEST="manifest",e.LEVEL="level",e.AUDIO_TRACK="audioTrack",e.SUBTITLE_TRACK="subtitleTrack",e.MEDIA_FRAGMENT="media-fragment",e.KEY="key",e.STEERING_MANIFEST="steering-manifest",e.SERVER_CERTIFICATE="server-certificate",e.INTERSTITIAL_ASSET_LIST="interstitial-asset-list",e}({}),de=function(e){return e.MAIN="main",e.AUDIO="audio",e.SUBTITLE="subtitle",e}({}),he="audio",fe="video",ve="audiovideo",ge=function(){return l(function e(t){var r,i,n;s(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=Se(r=this,i="stats"))&&(n.enumerable=!0,Object.defineProperty(r,i,n))},[{key:"setByteRange",value:function(e,t){var r,i=e.split("@",2);r=1===i.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(i[1]),this._byteRange=[r,parseInt(i[0])+r]}},{key:"baseurl",get:function(){return this.base.url}},{key:"byteRange",get:function(){return null===this._byteRange?[]:this._byteRange}},{key:"byteRangeStartOffset",get:function(){return this.byteRange[0]}},{key:"byteRangeEndOffset",get:function(){return this.byteRange[1]}},{key:"elementaryStreams",get:function(){return null===this._streams&&(this._streams=c(c(c({},he,null),fe,null),ve,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 ue),this._stats},set:function(e){this._stats=e}},{key:"url",get:function(){return!this._url&&this.relurl&&(this._url=le.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""},set:function(e){this._url=e}},{key:"clearElementaryStreamInfo",value:function(){var e=this.elementaryStreams;e[he]=null,e[fe]=null,e[ve]=null,this.url=null}}])}();function pe(e){return"initSegment"!==e.sn}function me(e,t){return e.sn===(null==t?void 0:t.sn)&&e.level===t.level}function ye(e,t){return e.sn===(null==t?void 0:t.sn)&&e.level===t.level&&e.cc===t.cc}var ke=function(e){function t(e,r){var i;return s(this,t),(i=a(this,t,[r]))._decryptdata=null,i._programDateTime=null,i._ref=null,i._bitrate=void 0,i.rawProgramDateTime=null,i.tagList=[],i.duration=0,i.sn=0,i.levelkeys=void 0,i.type=void 0,i.loader=null,i.keyLoader=null,i.level=-1,i.cc=0,i.startPTS=void 0,i.endPTS=void 0,i.startDTS=void 0,i.endDTS=void 0,i.start=0,i.playlistOffset=0,i.deltaPTS=void 0,i.maxStartPTS=void 0,i.minEndPTS=void 0,i.data=void 0,i.bitrateTest=!1,i.title=null,i.initSegment=null,i.endList=void 0,i.gap=void 0,i.urlId=0,i.type=e,i}return f(t,e),l(t,[{key:"byteLength",get:function(){if(this.hasStats){var e=this.stats.total;if(e)return e}if(this.byteRange.length){var t=this.byteRange[0],r=this.byteRange[1];if(Z(t)&&Z(r))return r-t}return null}},{key:"bitrate",get:function(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null},set:function(e){this._bitrate=e}},{key:"decryptdata",get:function(){var e,t=this.levelkeys;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(null==(e=this._decryptdata)||!e.keyId){var r=Object.keys(t);if(1===r.length){var i=this._decryptdata=t[r[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,t))}}return this._decryptdata}},{key:"end",get:function(){return this.start+this.duration}},{key:"endProgramDateTime",get:function(){if(null===this.programDateTime)return null;var e=Z(this.duration)?this.duration:0;return this.programDateTime+1e3*e}},{key:"encrypted",get:function(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){var t,r=Object.keys(this.levelkeys),i=r.length;if(i>1||1===i&&null!=(t=this.levelkeys[r[0]])&&t.encrypted)return!0}return!1}},{key:"programDateTime",get:function(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime},set:function(e){Z(e)?this._programDateTime=e:this._programDateTime=this.rawProgramDateTime=null}},{key:"ref",get:function(){return pe(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}},{key:"addStart",value:function(e){this.setStart(this.start+e)}},{key:"setStart",value:function(e){this.start=e,this._ref&&(this._ref.start=e)}},{key:"setDuration",value:function(e){this.duration=e,this._ref&&(this._ref.duration=e)}},{key:"setKeyFormat",value:function(e){var t=this.levelkeys;if(t){var r,i=t[e];!i||null!=(r=this._decryptdata)&&r.keyId||(this._decryptdata=i.getDecryptData(this.sn,t))}}},{key:"abortRequests",value:function(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()}},{key:"setElementaryStreamInfo",value:function(e,t,r,i,n){var a=arguments.length>5&&void 0!==arguments[5]&&arguments[5],s=this.elementaryStreams,o=s[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,r),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,n)):s[e]={startPTS:t,endPTS:r,startDTS:i,endDTS:n,partial:a}}}])}(ge),Ee=function(e){function t(e,r,i,n,o){var l;s(this,t),(l=a(this,t,[i])).fragOffset=0,l.duration=0,l.independent=!1,l.relurl=void 0,l.fragment=void 0,l.index=void 0,l.gap=!1,l.duration=e.decimalFloatingPoint("DURATION"),l.gap=e.bool("GAP"),l.independent=e.bool("INDEPENDENT"),l.relurl=e.enumeratedString("URI"),l.fragment=r,l.index=n;var u=e.enumeratedString("BYTERANGE");return u&&l.setByteRange(u,o),o&&(l.fragOffset=o.fragOffset+o.duration),l}return f(t,e),l(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||this.fragment.type===de.SUBTITLE&&this.stats.loading.end>0)}}])}(ge);function Se(e,t){var r=Object.getPrototypeOf(e);if(r){var i=Object.getOwnPropertyDescriptor(r,t);return i||Se(r,t)}}function Te(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=R(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var i=r.call(e,t);if("object"!=R(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==R(t)?t:t+""}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Ae(){return Ae=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var i in r)({}).hasOwnProperty.call(r,i)&&(e[i]=r[i])}return e},Ae.apply(null,arguments)}function be(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,i)}return r}function Ie(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?be(Object(r),!0).forEach(function(t){Te(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):be(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function Re(e,t){if(null==e)return{};var r,i,n=function(e,t){if(null==e)return{};var r={};for(var i in e)if({}.hasOwnProperty.call(e,i)){if(-1!==t.indexOf(i))continue;r[i]=e[i]}return r}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)r=a[i],-1===t.indexOf(r)&&{}.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function Le(e){switch(e.details){case ie.FRAG_LOAD_TIMEOUT:case ie.KEY_LOAD_TIMEOUT:case ie.LEVEL_LOAD_TIMEOUT:case ie.MANIFEST_LOAD_TIMEOUT:case ie.AUDIO_TRACK_LOAD_TIMEOUT:case ie.SUBTITLE_TRACK_LOAD_TIMEOUT:case ie.ASSET_LIST_LOAD_TIMEOUT:return!0}return!1}function Pe(e){return e.details.startsWith("key")}function we(e){return Pe(e)&&!!e.frag&&!e.frag.decryptdata}function Ce(e,t){var r=Le(t);return e.default["".concat(r?"timeout":"error","Retry")]}function De(e,t){var r="linear"===e.backoff?1:Math.pow(2,t);return Math.min(r*e.retryDelayMs,e.maxRetryDelayMs)}function _e(e){return Ie(Ie({},e),{errorRetry:null,timeoutRetry:null})}function Me(e,t,r,i){if(!e)return!1;var n=null==i?void 0:i.code,a=t<e.maxNumRetry&&(function(e){return xe(e)||!!e&&(e<400||e>499)}(n)||!!r);return e.shouldRetry?e.shouldRetry(e,t,r,i,a):a}function xe(e){return 0===e&&!1===navigator.onLine}function Oe(e,t){return t>0&&e.loadError>0&&0!==e.loadErrorTime&&self.performance.now()-e.loadErrorTime>t}var Fe=function(){return l(function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;s(this,e),this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=r,this.totalWeight_=i},[{key:"sample",value:function(e,t){var r=Math.pow(this.alpha_,e);this.estimate_=t*(1-r)+r*this.estimate_,this.totalWeight_+=e}},{key:"getTotalWeight",value:function(){return this.totalWeight_}},{key:"getEstimate",value:function(){if(this.alpha_){var e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}])}(),Ne=function(){return l(function e(t,r,i){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:100;s(this,e),this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new Fe(t),this.fast_=new Fe(r),this.defaultTTFB_=n,this.ttfb_=new Fe(t)},[{key:"update",value:function(e,t){var r=this.slow_,i=this.fast_,n=this.ttfb_;r.halfLife!==e&&(this.slow_=new Fe(e,r.getEstimate(),r.getTotalWeight())),i.halfLife!==t&&(this.fast_=new Fe(t,i.getEstimate(),i.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new Fe(e,n.getEstimate(),n.getTotalWeight()))}},{key:"sample",value:function(e,t){if(!(t<=0)){var r=Math.min(this.minDelayMs_,t/1e5),i=8*t,n=Math.max(e,r)/1e3,a=i/n;this.fast_.sample(n,a),this.slow_.sample(n,a)}}},{key:"sampleTTFB",value:function(e){var t=e/1e3,r=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(r,Math.max(e,5))}},{key:"canEstimate",value:function(){return this.fast_.getTotalWeight()>=this.minWeight_}},{key:"getEstimate",value:function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}},{key:"getEstimateTTFB",value:function(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}},{key:"defaultEstimate",get:function(){return this.defaultEstimate_}},{key:"destroy",value:function(){}}])}(),Be=l(function e(t,r){s(this,e),this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;var i="[".concat(t,"]:");this.trace=Ue,this.debug=r.debug.bind(null,i),this.log=r.log.bind(null,i),this.warn=r.warn.bind(null,i),this.info=r.info.bind(null,i),this.error=r.error.bind(null,i)}),Ue=function(){},Ve={trace:Ue,debug:Ue,log:Ue,warn:Ue,info:Ue,error:Ue};function Ge(){return Ae({},Ve)}function He(e,t,r){return t[e]?t[e].bind(t):function(e,t){var r=self.console[e];return r?r.bind(self.console,"".concat(t?"["+t+"] ":"","[").concat(e,"] >")):Ue}(e,r)}var Ke=Ge();var je=Ke;function qe(){if("undefined"!=typeof self)return(!(arguments.length>0&&void 0!==arguments[0])||arguments[0]||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function We(e,t){var r=Object.keys(e),i=Object.keys(t),n=r.length,a=i.length;return!n||!a||n===a&&!r.some(function(e){return-1===i.indexOf(e)})}function Ye(e){return e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer}var ze="utf-16be",Xe="utf-16le",Qe="utf-8";function $e(e,t){if(e<0)return-$e(-e,t);var r=Math.pow(10,t);if(Math.abs(e*r%1-.5)<Number.EPSILON){var i=Math.floor(e*r);return(i%2==0?i:i+1)/r}return Math.round(e*r)/r}function Je(){try{return crypto.randomUUID()}catch(i){try{var e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(e){var r=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=(r+16*Math.random())%16|0;return r=Math.floor(r/16),("x"==e?t:3&t|8).toString(16)})}}}function Ze(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 et(e,t){var r=0;return r=(127&e[t])<<21,r|=(127&e[t+1])<<14,r|=(127&e[t+2])<<7,r|=127&e[t+3]}function tt(e,t){return Ze(e,t)&&et(e,t+6)+10<=e.length-t}function rt(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 it(e,t){for(var r=t,i=0;Ze(e,t);){i+=10,i+=et(e,t+6),rt(e,t+10)&&(i+=10),t+=i}if(i>0)return e.subarray(r,r+i)}function nt(e){return function(e,t,r,i){var n=(s=e,Ye(s)?s:s.buffer),a=1;var s;"BYTES_PER_ELEMENT"in i&&(a=i.BYTES_PER_ELEMENT);var o=(d=e,d&&Ye(d.buffer)&&void 0!==d.byteLength&&void 0!==d.byteOffset?e.byteOffset:0),l=(o+e.byteLength)/a,u=(o+t)/a,c=Math.floor(Math.max(0,Math.min(u,l)));var d;return new i(n,c,Math.floor(Math.min(c+Math.max(r,0),l))-c)}(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,arguments.length>2&&void 0!==arguments[2]?arguments[2]:1/0,Uint8Array)}function at(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=t?e.indexOf(0):e.length,i=function(e){var t,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};t=Ye(e)?new DataView(e):new DataView(e.buffer,e.byteOffset,e.byteLength);var i=0,n=r.encoding;if(!n){var a=t.getUint8(0),s=t.getUint8(1);239==a&&187==s&&191==t.getUint8(2)?(n=Qe,i=3):254==a&&255==s?(n=ze,i=2):255==a&&254==s?(n=Xe,i=2):n=Qe}if("undefined"!=typeof TextDecoder)return new TextDecoder(n).decode(t);for(var o,l=t.byteLength,u=n!==ze,c="";i<l;){switch(n){case Qe:if((o=t.getUint8(i))<128)i++;else if(o>=194&&o<=223)if(i+1<l){var d=t.getUint8(i+1);d>=128&&d<=191?(o=(31&o)<<6|63&d,i+=2):i++}else i++;else if(o>=224&&o<=239)if(i+2<=l-1){var h=t.getUint8(i+1),f=t.getUint8(i+2);h>=128&&h<=191&&f>=128&&f<=191?(o=(15&o)<<12|(63&h)<<6|63&f,i+=3):i++}else i++;else if(o>=240&&o<=244)if(i+3<=l-1){var v=t.getUint8(i+1),g=t.getUint8(i+2),p=t.getUint8(i+3);v>=128&&v<=191&&g>=128&&g<=191&&p>=128&&p<=191?(o=(7&o)<<18|(63&v)<<12|(63&g)<<6|63&p,i+=4):i++}else i++;else i++;break;case ze:case"utf-16":case Xe:o=t.getUint16(i,u),i+=2}c+=String.fromCodePoint(o)}return c}(new DataView(e.buffer,e.byteOffset,r),{encoding:Qe});return t?i:i.replace(/\0/g,"")}function st(e){var t={key:e.type,description:"",data:"",mimeType:null,pictureType:null};if(!(e.size<2))if(3===e.data[0]){var r=e.data.subarray(1).indexOf(0);if(-1!==r){var i=at(nt(e.data,1,r)),n=e.data[2+r],a=e.data.subarray(3+r).indexOf(0);if(-1!==a){var s,o,l=at(nt(e.data,3+r,a));return"--\x3e"===i?s=at(nt(e.data,4+r+a)):s=Ye(o=e.data.subarray(4+r+a))?o:0==o.byteOffset&&o.byteLength==o.buffer.byteLength?o.buffer:new Uint8Array(o).buffer,t.mimeType=i,t.pictureType=n,t.description=l,t.data=s,t}}}else console.log("Ignore frame with unrecognized character encoding")}function ot(e){return"PRIV"===e.type?function(e){if(!(e.size<2)){var t=at(e.data,!0),r=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:r.buffer}}}(e):"W"===e.type[0]?function(e){if("WXXX"===e.type){if(e.size<2)return;var t=1,r=at(e.data.subarray(t),!0);t+=r.length+1;var i=at(e.data.subarray(t));return{key:e.type,info:r,data:i}}var n=at(e.data);return{key:e.type,info:"",data:n}}(e):"APIC"===e.type?st(e):function(e){if(!(e.size<2)){if("TXXX"===e.type){var t=1,r=e.data,i=at(r.subarray(t),!0);t+=i.length+1;var n=at(r.subarray(t));return{key:e.type,info:i,data:n}}var a=at(e.data.subarray(1));return{key:e.type,info:"",data:a}}}(e)}function lt(e){var t=String.fromCharCode(e[0],e[1],e[2],e[3]),r=et(e,4);return{type:t,size:r,data:e.subarray(10,10+r)}}function ut(e){for(var t=0,r=[];Ze(e,t);){var i=et(e,t+6);e[t+5]>>6&1&&(t+=10);for(var n=(t+=10)+i;t+10<n;){var a=lt(e.subarray(t)),s=ot(a);s&&r.push(s),t+=a.size+10}rt(e,t)&&(t+=10)}return r}function ct(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info}function dt(e){if(8===e.data.byteLength){var t=new Uint8Array(e.data),r=1&t[3],i=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return i/=45,r&&(i+=47721858.84),Math.round(i)}}function ht(e){var t,r=u(ut(e));try{for(r.s();!(t=r.n()).done;){var i=t.value;if(ct(i))return dt(i)}}catch(e){r.e(e)}finally{r.f()}}function ft(e){for(var t="",r=0;r<e.length;r++){var i=e[r].toString(16);i.length<2&&(i="0"+i),t+=i}return t}function vt(e){return Uint8Array.from(e.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function gt(e){return Uint8Array.from(atob(e),function(e){return e.charCodeAt(0)})}function pt(e){return String.fromCharCode.apply(null,e)}var mt,yt=Math.pow(2,32)-1,kt={avc1:1635148593,avcC:1635148611,hvc1:1752589105,hvcC:1752589123,btrt:1651798644,dinf:1684631142,dref:1685218662,esds:1702061171,free:1718773093,ftyp:1718909296,hdlr:1751411826,mdat:1835295092,mdhd:1835296868,mdia:1835297121,mfhd:1835427940,minf:1835626086,moof:1836019558,moov:1836019574,mp4a:1836069985,".mp3":778924083,dac3:1684103987,"ac-3":1633889587,mvex:1836475768,mvhd:1836476516,pasp:1885434736,sdtp:1935963248,stbl:1937007212,stco:1937007471,stsc:1937011555,stsd:1937011556,stsz:1937011578,stts:1937011827,tfdt:1952867444,tfhd:1952868452,traf:1953653094,trak:1953653099,trun:1953658222,trex:1953654136,tkhd:1953196132,vmhd:1986881636,smhd:1936549988},Et={video:1,audio:2,id3:3,text:4};function St(e,t){var r=e[t]<<8|e[t+1];return r<0?65536+r:r}function Tt(e,t){var r=e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3];return r<0?4294967296+r:r}function At(e,t){var r=Tt(e,t);return r*=Math.pow(2,32),r+=Tt(e,t+4)}function bt(e,t){for(var r="",i=t;i<e.length;i++)if(r+=String.fromCharCode(e[i]),0===e[i])return r;return null}function It(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function Rt(e,t,r){e[t]=r>>24,e[t+1]=r>>16&255,e[t+2]=r>>8&255,e[t+3]=255&r}function Lt(e,t,r){var i=t.byteOffset-e.byteOffset-8,n=8+r,a=t.byteLength+8-n;a<8||(Rt(e,i,n),Rt(e,i+n,a),Rt(e,i+n+4,kt.free))}function Pt(e,t){return[e.byteOffset-t-8,e.byteOffset-t+e.byteLength]}function wt(e,t){t.sort(function(e,t){return e[0]-t[0]});for(var r=t.reduce(function(e,t){var r=S(t,2),i=r[0];return e+r[1]-i},0),i=new Uint8Array(e.byteLength-r),n=0,a=0,s=0;s<t.length;s++){var o=S(t[s],2),l=o[0],u=o[1];i.set(e.subarray(n,l),a),a+=l-n,n=u}i.set(e.subarray(n),a);return{result:i,dropped:r,droppedBefore:function(e){return t.reduce(function(t,r){var i=S(r,2),n=i[0],a=i[1];return a<=e?t+a-n:t},0)}}}function Ct(e,t){var r=[];return t.length?(Dt(e,t,0,0,e.byteLength,r),r):r}function Dt(e,t,r,i,n,a){var s=t[r];if(4===(null==s?void 0:s.length))for(var o=s.charCodeAt(0),l=s.charCodeAt(1),u=s.charCodeAt(2),c=s.charCodeAt(3),d=t.length-1,h=i;h<n;){var f=h+8<=n,v=h+4<=n?16777216*e[h]+(e[h+1]<<16|e[h+2]<<8|e[h+3]):Tt(e,h),g=v>1?h+v:n;if(f&&e[h+4]===o&&e[h+5]===l&&e[h+6]===u&&e[h+7]===c){var p=Math.min(g,n);r===d?a.push(e.subarray(h+8,p)):Dt(e,t,r+1,h+8,p,a)}h=g}}function _t(e){var t=[],r=e[0],i=8,n=Tt(e,i);i+=4;var a=0,s=0;0===r?(a=Tt(e,i),s=Tt(e,i+4),i+=8):(a=At(e,i),s=At(e,i+8),i+=16),i+=2;var o=e.length+s,l=St(e,i);i+=2;for(var u=0;u<l;u++){var c=i,d=Tt(e,c);c+=4;var h=2147483647&d;if(1===(2147483648&d)>>>31)return je.warn("SIDX has hierarchical references (not supported)"),null;var f=Tt(e,c);c+=4,t.push({referenceSize:h,subsegmentDuration:f,info:{duration:f/n,start:o,end:o+h-1}}),o+=h,i=c+=4}return{earliestPresentationTime:a,timescale:n,version:r,referencesCount:l,references:t}}function Mt(e){for(var t=[],r=Ct(e,["moov","trak"]),i=0;i<r.length;i++){var n=r[i],a=Ct(n,["tkhd"])[0];if(a){var s=a[0],o=Tt(a,0===s?12:20),l=Ct(n,["mdia","mdhd"])[0];if(l){var u=Tt(l,0===(s=l[0])?12:20),c=Ct(n,["mdia","hdlr"])[0];if(c){var d=pt(c.subarray(8,12)),h={soun:he,vide:fe}[d],f=xt(Ct(n,["mdia","minf","stbl","stsd"])[0]);h?(t[o]={timescale:u,type:h,stsd:f},t[h]=Ie({timescale:u,id:o},f)):t[o]={timescale:u,type:d,stsd:f}}}}}return Ct(e,["moov","mvex","trex"]).forEach(function(e){var r=Tt(e,4),i=t[r];i&&(i.default={duration:Tt(e,12),sampleSize:Tt(e,16),flags:Tt(e,20)})}),t}function xt(e){var t,r=e.subarray(8),i=r.subarray(86),n=pt(r.subarray(4,8)),a=n,s="enca"===n||"encv"===n;if(s){var o=Ct(r,[n])[0];Ct(o.subarray("enca"===n?28:78),["sinf"]).forEach(function(e){var t=Ct(e,["schm"])[0];if(t){var r=pt(t.subarray(4,8));if("cbcs"===r||"cenc"===r){var i=Ct(e,["frma"])[0];i&&(a=pt(i))}}})}var l=a;switch(a){case"avc1":case"avc2":case"avc3":case"avc4":var u=Ct(i,["avcC"])[0];u&&u.length>3&&(a+="."+Nt(u[1])+Nt(u[2])+Nt(u[3]),t=Ot("avc1"===l?"dva1":"dvav",i));break;case"mp4a":var c=Ct(r,[n])[0],d=Ct(c.subarray(28),["esds"])[0];if(d&&d.length>7){var h=4;if(3!==d[h++])break;h=Ft(d,h),h+=2;var f=d[h++];if(128&f&&(h+=2),64&f&&(h+=d[h++]),4!==d[h++])break;h=Ft(d,h);var v=d[h++];if(64!==v)break;if(a+="."+Nt(v),h+=12,5!==d[h++])break;h=Ft(d,h);var g=d[h++],p=(248&g)>>3;31===p&&(p+=1+((7&g)<<3)+((224&d[h])>>5)),a+="."+p}break;case"hvc1":case"hev1":var m=Ct(i,["hvcC"])[0];if(m&&m.length>12){var y=m[1],k=["","A","B","C"][y>>6],E=31&y,S=Tt(m,2),T=(32&y)>>5?"H":"L",A=m[12],b=m.subarray(6,12);a+="."+k+E,a+="."+function(e){for(var t=0,r=0;r<32;r++)t|=(e>>r&1)<<31-r;return t>>>0}(S).toString(16).toUpperCase(),a+="."+T+A;for(var I="",R=b.length;R--;){var L=b[R];if(L||I)I="."+L.toString(16).toUpperCase()+I}a+=I}t=Ot("hev1"==l?"dvhe":"dvh1",i);break;case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":a=Ot(a,i)||a;break;case"vp09":var P=Ct(i,["vpcC"])[0];if(P&&P.length>6){var w=P[4],C=P[5],D=P[6]>>4&15;a+="."+Bt(w)+"."+Bt(C)+"."+Bt(D)}break;case"av01":var _=Ct(i,["av1C"])[0];if(_&&_.length>2){var M=_[1]>>>5,x=31&_[1],O=_[2]>>>7?"H":"M",F=(64&_[2])>>6,N=(32&_[2])>>5,B=2===M&&F?N?12:10:F?10:8,U=(16&_[2])>>4,V=(8&_[2])>>3,G=(4&_[2])>>2,H=3&_[2];a+="."+M+"."+Bt(x)+O+"."+Bt(B)+"."+U+"."+V+G+H+"."+Bt(1)+"."+Bt(1)+"."+Bt(1)+".0",t=Ot("dav1",i)}}return{codec:a,encrypted:s,supplemental:t}}function Ot(e,t){var r=Ct(t,["dvvC"]),i=r.length?r[0]:Ct(t,["dvcC"])[0];if(i){var n=i[2]>>1&127,a=i[2]<<5&32|i[3]>>3&31;return e+"."+Bt(n)+"."+Bt(a)}}function Ft(e,t){for(var r=t+5;128&e[t++]&&t<r;);return t}function Nt(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function Bt(e){return(e<10?"0":"")+e}function Ut(e,t){Ct(e,["moov","trak"]).forEach(function(e){var r=Ct(e,["mdia","minf","stbl","stsd"])[0];if(r){var i=r.subarray(8),n=Ct(i,["enca"]),a=n.length>0;a||(n=Ct(i,["encv"])),n.forEach(function(e){Ct(a?e.subarray(28):e.subarray(78),["sinf"]).forEach(function(e){var r=Vt(e);r&&t(r,a)})})}})}function Vt(e){var t=Ct(e,["schm"])[0];if(t){var r=pt(t.subarray(4,8));if("cbcs"===r||"cenc"===r){var i=Ct(e,["schi","tenc"])[0];if(i)return i}}}function Gt(e){return"undefined"==typeof TextDecoder?at(e):(mt||(mt=new TextDecoder("utf-8"))).decode(e).replace(/\0/g,"")}function Ht(e,t,r,i,n){for(var a={},s=!1,o=function(e){for(var t=e.byteLength,r=[],i=0;i<t;){var n=i+8<=t,a=i+4<=t?16777216*e[i]+(e[i+1]<<16|e[i+2]<<8|e[i+3]):Tt(e,i),s=a>1?i+a:t;if(n&&109===e[i+4]&&111===e[i+5]&&111===e[i+6]&&102===e[i+7])for(var o=Math.min(s,t),l=i+8;l<o;){var u=l+8<=o,c=l+4<=o?16777216*e[l]+(e[l+1]<<16|e[l+2]<<8|e[l+3]):Tt(e,l),d=c>1?l+c:o;if(u&&116===e[l+4]&&114===e[l+5]&&97===e[l+6]&&102===e[l+7]){for(var h=Math.min(d,o),f=void 0,v=void 0,g=[],p=l+8;p<h;){var m=p+8<=h,y=p+4<=h?16777216*e[p]+(e[p+1]<<16|e[p+2]<<8|e[p+3]):Tt(e,p),k=y>1?p+y:h;if(m&&116===e[p+4]){var E=Math.min(k,h);102===e[p+5]&&104===e[p+6]&&100===e[p+7]?v||(v=e.subarray(p+8,E)):102===e[p+5]&&100===e[p+6]&&116===e[p+7]?f||(f=e.subarray(p+8,E)):114===e[p+5]&&117===e[p+6]&&110===e[p+7]&&g.push(e.subarray(p+8,E))}p=k}r.push({moofOffset:e.byteOffset+i,tfdt:f,tfhd:v,truns:g})}l=d}i=s}return r}(e),l=e.byteLength,u=0;u<o.length;u++){var c=o[u],d=c.moofOffset,h=c.tfdt,f=c.tfhd,v=c.truns,g=Tt(f,4),p=t[g];if(p){var m=a[g]||(a[g]={start:NaN,duration:0,sampleCount:0,trun:[],timescale:p.timescale,type:p.type}),y=void 0;if(h){var k=h[0];y=Tt(h,4),1===k&&(y===yt?r.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(y*=yt+1,y+=Tt(h,8))),Z(y)&&(!Z(m.start)||y<m.start)&&(m.start=y),n&&Z(y)&&(n.timeOffset=y/n.timescale)}var E=(null==n?void 0:n.trackId)===g&&p.type===fe,S=p.default,T=16777215&Tt(f,0),A=(null==S?void 0:S.duration)||0,b=void 0,I=(null==S?void 0:S.sampleSize)||0,R=8;1&T&&(R+=8),2&T&&(R+=4),8&T&&(A=Tt(f,R),b=f.byteOffset-e.byteOffset+R,R+=4),16&T&&(I=Tt(f,R));var L=0,P=!!(1&T),w=!P&&!!(131072&T);P?(L=Tt(f,8),L*=Math.pow(2,32),L+=Tt(f,12)):w&&(L=d);for(var C=y||0,D=0,_=A,M=0;M<v.length;M++){var x=v[M],O=Tt(x,4),F=m.sampleCount;m.sampleCount+=O;var N=1&x[3],B=0,U=4&x[3],V=1&x[2],G=2&x[2],H=4&x[2],K=8&x[2],j=8;if(N&&(B=It(x,j),j+=4),U)1&x[j+1]||void 0!==m.keyFrameIndex||(m.keyFrameIndex=F),j+=4;var q=L+B;if(i||0!==x[1]||6!==x[2]||1!==x[3]){var W=void 0,Y=void 0;i&&(Y={sampleOffset:q,samples:W=[],defaultSampleDurationOffset:b},q<=l&&m.trun.push(Y));for(var z=void 0,X=0;X<O;X++){var Q=void 0;V?(i&&(Q=x.byteOffset-e.byteOffset+j),_=Tt(x,j),j+=4):_=A,G?(z=Tt(x,j),j+=4):z=I;var $=void 0,J=void 0;H&&(J=1&x[j+1]?1:0,i&&($={isNonSync:J,dependsOn:1==(3&x[j])?1:2}),j+=4);var ee=0;if(K)ee=0===x[0]?Tt(x,j):It(x,j),j+=4;if(E){for(var te=q,re=0;re<z;){var ie=Tt(e,te);te+=4,qt(n.isHEVCFlavor,e[te])&&Wt(e.subarray(te,te+ie),n.isHEVCFlavor?2:1,n.timeOffset+ee/n.timescale,n.samples),te+=ie,re+=ie+4}n.timeOffset+=_/n.timescale}if((q+=z)<=l){Y&&void 0!==Q&&(Y.lastSampleDurationOffset=Q),0===J&&void 0===m.keyFrameIndex&&(m.keyFrameIndex=X,m.keyFrameStart=C);var ne=C+ee;(!Z(m.ptsMin)||ne<m.ptsMin)&&(m.ptsMin=ne),(!Z(m.ptsMax)||ne+_>m.ptsMax)&&(m.ptsMax=ne+_),W&&(W[X]={cts:ee,duration:_,flags:$,size:z})}C+=_,D+=_}!D&&A&&(D+=A*O)}else{for(var ae,se,oe=C,le=q,ue=j,ce=-1,de=0,he=0,ve=null!=(ae=null==n?void 0:n.timeOffset)?ae:0,ge=A/(null!=(se=null==n?void 0:n.timescale)?se:1),pe=!0===(null==n?void 0:n.isHEVCFlavor),me=pe?2:1,ye=0;ye<O;ye++){var ke=0===x[j]?x[j+1]<<16|x[j+2]<<8|x[j+3]:Tt(x,j),Ee=-1===ce&&void 0===m.keyFrameIndex&&!(1&x[j+5]);j+=8;var Se=q+ke;if(E){if(ke>0){var Te=q;do{var Ae=0===e[Te]?e[Te+1]<<16|e[Te+2]<<8|e[Te+3]:Tt(e,Te),be=e[Te+=4],Ie=pe?be>>1&63:31&be;(pe?39===Ie||40===Ie:6===Ie)&&Wt(e.subarray(Te,Te+Ae),me,ve,n.samples),Te+=Ae}while(Te<Se)}ve+=ge}q=Se,Ee&&(ce=ye,de=q)}if(q<=l)he=O;else for(var Re=le,Le=ue,Pe=0;Pe<O;Pe++){if((Re+=0===x[Le]?x[Le+1]<<16|x[Le+2]<<8|x[Le+3]:Tt(x,Le))>l)break;he=Pe+1,Le+=8}if(E&&(n.timeOffset=ve),-1!==ce&&de<=l&&void 0===m.keyFrameIndex&&(m.keyFrameIndex=ce,m.keyFrameStart=oe+ce*A),he){(!Z(m.ptsMin)||oe<m.ptsMin)&&(m.ptsMin=oe);var we=oe+he*A;(!Z(m.ptsMax)||we>m.ptsMax)&&(m.ptsMax=we)}var Ce=A*O;C=oe+Ce,D+=Ce}}m.duration+=D,m.duration&&(s=!0)}}if(!s){for(var De=1/0,_e=0,Me=Ct(e,["sidx"]),xe=0;xe<Me.length;xe++){var Oe=_t(Me[xe]);if(null!=Oe&&Oe.references){De=Math.min(De,Oe.earliestPresentationTime/Oe.timescale);var Fe=Oe.references.reduce(function(e,t){return e+t.info.duration||0},0);_e=Math.max(_e,Fe+Oe.earliestPresentationTime/Oe.timescale)}}_e&&Z(_e)&&Object.keys(a).forEach(function(e){a[e].duration||(a[e].duration=_e*a[e].timescale-a[e].start)})}return a}function Kt(e,t){var r=new Uint8Array(e.length+t.length);return r.set(e),r.set(t,e.length),r}function jt(e){if(!e)return!1;var t=e.substring(0,4);return"hvc1"===t||"hev1"===t||"dvh1"===t||"dvhe"===t}function qt(e,t){if(e){var r=t>>1&63;return 39===r||40===r}return 6===(31&t)}function Wt(e,t,r,i){var n=Yt(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){je.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=St(n,c);if(c+=2,49===d){var h=Tt(n,c);if(c+=4,1195456820===h){var f=n[c++];if(3===f){var v=n[c++],g=64&v,p=g?2+3*(31&v):0,m=new Uint8Array(p);if(g){m[0]=v;for(var y=1;y<p;y++)m[y]=n[c++]}i.push({type:f,payloadType:s,pts:r,bytes:m})}}}}}else if(5===s&&o>16){for(var k=[],E=0;E<16;E++){var S=n[c++].toString(16);k.push(1==S.length?"0"+S:S),3!==E&&5!==E&&7!==E&&9!==E||k.push("-")}for(var T=o-16,A=new Uint8Array(T),b=0;b<T;b++)A[b]=n[c++];i.push({payloadType:s,pts:r,uuid:k.join(""),userData:Gt(A),userDataBytes:A})}}}function Yt(e){for(var t,r=e.byteLength,i=e.indexOf(3,3);-1!==i;)0===e[i-1]&&0===e[i-2]&&(t||(t=[])).push(i),i=e.indexOf(3,i+1);if(!t)return e;for(var n=r-t.length,a=new Uint8Array(n),s=0,o=0,l=0;l<n;o++,l++)o===t[s]&&(o++,s++),a[l]=e[o];return a}function zt(e,t,r){if(16!==e.byteLength)throw new RangeError("Invalid system id");var i,n;i=new Uint8Array,n=new Uint8Array;var a=new Uint8Array(4);return r.byteLength>0&&new DataView(a.buffer).setUint32(0,r.byteLength,!1),function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];for(var n=r.length,a=8,s=n;s--;)a+=r[s].byteLength;var o=new Uint8Array(a);for(o[0]=a>>24&255,o[1]=a>>16&255,o[2]=a>>8&255,o[3]=255&a,o.set(e,4),s=0,a=8;s<n;s++)o.set(r[s],a),a+=r[s].byteLength;return o}([112,115,115,104],new Uint8Array([0,0,0,0]),e,n,i,a,r)}function Xt(e){var t=[];if(e instanceof ArrayBuffer)for(var r=e.byteLength,i=0;i+32<r;){var n=Qt(new DataView(e,i));t.push(n),i+=n.size}return t}function Qt(e){var t=e.getUint32(0),r=e.byteOffset,i=e.byteLength;if(i<t)return{offset:r,size:i};if(1886614376!==e.getUint32(4))return{offset:r,size:t};var n=e.getUint32(8)>>>24;if(0!==n&&1!==n)return{offset:r,size:t};var a,s=e.buffer,o=ft(new Uint8Array(s,r+12,16)),l=null,u=0;if(0===n)u=28;else{var c=e.getUint32(28);if(!c||i<32+16*c)return{offset:r,size:t};l=[];for(var d=0;d<c;d++)l.push(new Uint8Array(s,r+32+16*d,16));u=32+16*c}if(!u)return{offset:r,size:t};var h=e.getUint32(u);return t-32<h?{offset:r,size:t}:(a=new Uint8Array(s,r+u+4,h),0===n&&(l=function(e){for(var t=[],r=0;r<e.length;){var i=e[r++],n=7&i;if(0!==n)if(2===n){for(var a=0,s=0,o=128;128&o;s+=7)a|=(127&(o=e[r++]))<<s;if(i>>3==2)if(32===a){for(var l=new Uint8Array(16),u=0;u<16;u++)l[u]=parseInt(String.fromCharCode(e[r+2*u],e[r+2*u+1]),16);t.push(l)}else 16===a&&t.push(e.subarray(r,r+16));r+=a}else r+=1===n?8:4;else for(;128&e[r++];);}return t}(a)),{version:n,systemId:o,kids:l,data:a,offset:r,size:t})}var $t,Jt,Zt,er=rr("userAgent"),tr=rr("vendor");function rr(e){try{return navigator[e]||""}catch(e){}return""}function ir(){if(void 0===$t){var e=er.match(/Chrome\/(\d+)/i);$t=e?parseInt(e[1]):0}return $t}function nr(){return/\(Windows.+Firefox\//i.test(er)}var ar={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},image:{mjpg:1}};function sr(e,t){var r=ar[t];return!!r&&!!r[e.slice(0,4)]}function or(e,t){var r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return!e.split(",").some(function(e){return!lr(e,t,r)})}function lr(e,t){var r,i=qe(!(arguments.length>2&&void 0!==arguments[2])||arguments[2]);return null!=(r=null==i?void 0:i.isTypeSupported(ur(e,t)))&&r}function ur(e,t){return"".concat(t,"/mp4;codecs=").concat(e)}function cr(e){if(e){var t=e.substring(0,4);return ar.video[t]}return 2}function dr(e){var t=nr();return e.split(",").reduce(function(e,r){var i=t&&jt(r)?9:ar.video[r];return i?(2*i+e)/(e?3:2):(ar.audio[r]+e)/(e?2:1)},0)}var hr={};var fr=/flac|opus|mp4a\.40\.34/i;function vr(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return e.replace(fr,function(e){return function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(hr[e])return hr[e];for(var r={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e],i=0;i<r.length;i++){var n;if(lr(r[i],"audio",t))return hr[e]=r[i],r[i];if("mp3"===r[i]&&null!=(n=qe(t))&&n.isTypeSupported("audio/mpeg"))return""}return e}(e.toLowerCase(),t)})}function gr(e,t){if(e&&(e.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e))&&(pr(e,"audio")||pr(e,"video")))return e;if(t){var r=t.split(",");if(r.length>1){if(e)for(var i=r.length;i--;)if(r[i].substring(0,4)===e.substring(0,4))return r[i];return r[0]}}return t||e}function pr(e,t){return sr(e,t)&&lr(e,t)}function mr(e){if(e.startsWith("av01.")){for(var t=e.split("."),r=["0","111","01","01","01","0"],i=t.length;i>4&&i<10;i++)t[i]=r[i-4];return t.join(".")}return e}function yr(e){var t=qe(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 kr(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}var Er={supported:!1,smooth:!1,powerEfficient:!1},Sr={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function Tr(e,t){return{supported:!1,configurations:t,decodingInfoResults:[Er],error:e}}function Ar(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},n=e.videoCodec;if(!n&&!e.audioCodec||!r)return Promise.resolve(Sr);for(var a=[],s=function(e){var t,r=null==(t=e.videoCodec)?void 0:t.split(","),i=Ir(e),n=e.width||640,a=e.height||480,s=e.frameRate||30,o=e.videoRange.toLowerCase();return r?r.map(function(e){var t={contentType:ur(mr(e),"video"),width:n,height:a,bitrate:i,framerate:s};return"sdr"!==o&&(t.transferFunction=o),t}):[]}(e),o=s.length,l=function(e,t,r){var i,n=null==(i=e.audioCodec)?void 0:i.split(","),a=Ir(e);if(n&&e.audioGroups)return e.audioGroups.reduce(function(e,i){var s,o=i?null==(s=t.groups[i])?void 0:s.tracks:null;return o?o.reduce(function(e,t){if(t.groupId===i){var s=parseFloat(t.channels||"");n.forEach(function(t){var i={contentType:ur(t,"audio"),bitrate:r?br(t,a):a};s&&(i.channels=""+s),e.push(i)})}return e},e):e},[]);return[]}(e,t,o>0),u=l.length,c=o||1*u||1;c--;){var d={type:"media-source"};if(o&&(d.video=s[c%o]),u){d.audio=l[c%u];var h=d.audio.bitrate;d.video&&h&&(d.video.bitrate-=h)}a.push(d)}if(n){var f=navigator.userAgent;if(n.split(",").some(function(e){return jt(e)})&&nr())return Promise.resolve(Tr(new Error("Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (".concat(f,")")),a))}return Promise.all(a.map(function(e){var t=function(e){var t="",r=e.audio,i=e.video;if(i){var n=kr(i.contentType);t+="".concat(n,"_r").concat(i.height,"x").concat(i.width,"f").concat(Math.ceil(i.framerate)).concat(i.transferFunction||"sd","_").concat(Math.ceil(i.bitrate/1e5))}if(r){var a=kr(r.contentType);t+="".concat(i?"_":"").concat(a,"_c").concat(r.channels)}return t}(e);return i[t]||(i[t]=r.decodingInfo(e))})).then(function(e){return{supported:!e.some(function(e){return!e.supported}),configurations:a,decodingInfoResults:e}}).catch(function(e){return{supported:!1,configurations:a,decodingInfoResults:[],error:e}})}function br(e,t){if(t<=1)return 1;var r=128e3;return"ec-3"===e?r=768e3:"ac-3"===e&&(r=64e4),Math.min(t/2,r)}function Ir(e){return 1e3*Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)/1e3)||1}function Rr(e,t,r){var i=encodeURIComponent(t),n="".concat(i,"=").concat(encodeURIComponent(r)),a=!1,s=[];e.search.substring(1).split("&").forEach(function(e){e===i||e.startsWith(i+"=")?a||(s.push(n),a=!0):e&&s.push(e)}),a||s.push(n),e.search=s.join("&")}var Lr=["NONE","TYPE-0","TYPE-1",null];var Pr=["SDR","PQ","HLG"];var wr="",Cr="YES",Dr="v2";function _r(e){var t=e.canSkipUntil,r=e.canSkipDateRanges,i=e.age;return t&&i<t/2?r?Dr:Cr:wr}var Mr=function(){return l(function e(t,r,i){s(this,e),this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=r,this.skip=i},[{key:"addDirectives",value:function(e){var t=new self.URL(e);return void 0!==this.msn&&Rr(t,"_HLS_msn",this.msn.toString()),void 0!==this.part&&Rr(t,"_HLS_part",this.part.toString()),this.skip&&Rr(t,"_HLS_skip",this.skip),t.href}}])}(),xr=function(){return l(function e(t){if(s(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.imageCodec=void 0,this.iframes=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loadErrorTime=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,"imageCodec"in t&&(this.imageCodec=t.imageCodec),this.codecSet=[t.videoCodec,t.audioCodec].filter(function(e){return!!e}).map(function(e){return e.substring(0,4)}).join(","),"supplemental"in t){var r;this.supplemental=t.supplemental;var i=null==(r=t.supplemental)?void 0:r.videoCodec;i&&i!==t.videoCodec&&(this.codecSet+=",".concat(i.substring(0,4)))}"iframes"in t&&t.iframes?this.iframes=!0:(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 Or(this._audioGroups,e)}},{key:"hasSubtitleGroup",value:function(e){return Or(this._subtitleGroups,e)}},{key:"audioGroups",get:function(){return this._audioGroups}},{key:"subtitleGroups",get:function(){return this._subtitleGroups}},{key:"addGroupId",value:function(e,t){if(t)if("audio"===e){var r=this._audioGroups;r||(r=this._audioGroups=[]),-1===r.indexOf(t)&&r.push(t)}else if("text"===e){var i=this._subtitleGroups;i||(i=this._subtitleGroups=[]),-1===i.indexOf(t)&&i.push(t)}}},{key:"urlId",get:function(){return 0},set:function(e){}},{key:"audioGroupIds",get:function(){return this.audioGroups?[this.audioGroupId]:void 0}},{key:"textGroupIds",get:function(){return this.subtitleGroups?[this.textGroupId]:void 0}},{key:"audioGroupId",get:function(){var e;return null==(e=this.audioGroups)?void 0:e[0]}},{key:"textGroupId",get:function(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}},{key:"addFallback",value:function(){}}])}();function Or(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}function Fr(e,t){var r=!1,i=[];if(e&&(r="SDR"!==e,i=[e]),t){var n="SDR"!==(i=t.allowedVideoRanges||Pr.slice(0)).join("")&&!t.videoCodec;(r=void 0!==t.preferHDR?t.preferHDR:n&&function(){if("function"==typeof matchMedia){var e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}())||(i=["SDR"])}return{preferHDR:r,allowedVideoRanges:i}}var Nr=function(e,t){return JSON.stringify(e,function(e){var t=new WeakSet;return function(r,i){if(e&&(i=e(r,i)),"object"===R(i)&&null!==i){if(t.has(i))return;t.add(i)}return i}}(t))};function Br(e,t){je.log('[abr] start candidates with "'.concat(e,'" ignored because ').concat(t))}function Ur(e){return e.reduce(function(e,t){var r=e.groups[t.groupId];r||(r=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),r.tracks.push(t);var i=t.channels||"2";return r.channels[i]=(r.channels[i]||0)+1,r.hasDefault=r.hasDefault||t.default,r.hasAutoSelect=r.hasAutoSelect||t.autoselect,r.hasDefault&&(e.hasDefaultAudio=!0),r.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Vr(e){return e?{lang:e.lang,assocLang:e.assocLang,characteristics:e.characteristics,channels:e.channels,audioCodec:e.audioCodec}:e}function Gr(e,t,r){if("attrs"in e){var i=t.indexOf(e);if(-1!==i)return i}for(var n=0;n<t.length;n++){if(Hr(e,t[n],r))return n}return-1}function Hr(e,t,r){var i=e.groupId,n=e.name,a=e.lang,s=e.assocLang,o=e.default,l=e.forced;return(void 0===i||t.groupId===i)&&(void 0===n||t.name===n)&&(void 0===a||function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"--";if(e.length===t.length)return e===t;return e.startsWith(t)||t.startsWith(e)}(a,t.lang))&&(void 0===s||t.assocLang===s)&&(void 0===o||t.default===o)&&(void 0===l||t.forced===l)&&(!("characteristics"in e)||function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",r=e.split(","),i=t.split(",");return r.length===i.length&&!r.some(function(e){return-1===i.indexOf(e)})}(e.characteristics||"",t.characteristics))&&(void 0===r||r(e,t))}function Kr(e,t){var r=e.audioCodec,i=e.channels;return!(void 0!==r&&(t.audioCodec||"").substring(0,4)!==r.substring(0,4)||void 0!==i&&i!==(t.channels||"2"))}function jr(e,t,r){for(var i=t;i>-1;i--)if(r(e[i]))return i;for(var n=t+1;n<e.length;n++)if(r(e[n]))return n;return-1}function qr(e,t){var r;return!!e&&e!==(null==(r=t.loadLevelObj)?void 0:r.uri)}function Wr(e,t){return!t||-1!==t.indexOf(e)}function Yr(e,t){if(t||e){var r=Ae({},t);return e&&(e.videoCodec&&(r.videoCodec=e.videoCodec),e.videoRange&&(r.allowedVideoRanges=[e.videoRange])),r}}var zr=function(e){function t(e){var r;return s(this,t),(r=a(this,t,["abr",e.logger])).hls=void 0,r.lastLevelLoadSec=0,r.lastLoadedFragLevel=-1,r.firstSelection=-1,r.firstAutoFloor=-1,r._nextAutoLevel=-1,r.nextAutoLevelKey="",r.audioTracksByGroup=null,r.codecTiers=null,r.timer=-1,r.fragCurrent=null,r.partCurrent=null,r.bitrateTestDelay=0,r.rebufferNotice=-1,r.supportedCache={},r.bwEstimator=void 0,r._abandonRulesCheck=function(e){var t,i=r,n=i.fragCurrent,a=i.partCurrent,s=i.hls;if(s){var o=s.autoLevelEnabled,l=s.media;if(n&&l){var u=performance.now(),c=a?a.stats:n.stats,d=a?a.duration:n.duration,h=u-c.loading.start,f=s.minAutoLevel,v=n.level,g=r._nextAutoLevel;if(c.aborted||c.loaded&&c.loaded===c.total||v<=f)return r.clearTimer(),void(r._nextAutoLevel=-1);if(o){var p=g>-1&&g!==v,m=!!e||p;if(m||!l.paused&&l.playbackRate&&l.readyState){var y=s.mainForwardBufferInfo;if(m||null!==y){var k=r.bwEstimator.getEstimateTTFB(),E=Math.abs(l.playbackRate);if(!(h<=Math.max(k,d/(2*E)*1e3))){var S=y?y.len/E:0,T=c.loading.first?c.loading.first-c.loading.start:-1,A=c.loaded&&T>-1,b=r.getBwEstimate(),I=s.levels,R=I[v],L=Math.max(c.loaded,Math.round(d*(n.bitrate||R.averageBitrate)/8)),P=A?h-T:h;P<1&&A&&(P=Math.min(h,8*c.loaded/b));var w=A?1e3*c.loaded/P:0,C=k/1e3,D=w?(L-c.loaded)/w:8*L/b+C;if(!(D<=S)){var _,M=w?8*w:b,x=!0===(null==(t=(null==e?void 0:e.details)||s.latestLevelDetails)?void 0:t.live),O=s.config.abrBandWidthUpFactor,F=Number.POSITIVE_INFINITY;for(_=v-1;_>f;_--){var N=I[_].maxBitrate,B=!I[_].details||x;if((F=r.getTimeToLoadFrag(C,M,d*N,B))<Math.min(S,d+C))break}if(!(F>=D||F>10*d)){A?r.bwEstimator.sample(h-Math.min(k,T),c.loaded):r.bwEstimator.sampleTTFB(h);var U=I[_].maxBitrate;r.getBwEstimate()*O>U&&(r.firstAutoFloor=Math.min(_,s.firstLevel),r.resetEstimator(U));var V=r.findBestLevel(U,f,_,0,S,1,1);V>-1&&(_=V),r.warn("Fragment ".concat(n.sn).concat(a?" part "+a.index:""," of level ").concat(v," is loading too slowly;\n Fragment duration: ").concat(n.duration.toFixed(3),"\n Time to underbuffer: ").concat(S.toFixed(3)," s\n Estimated load time for current fragment: ").concat(D.toFixed(3)," s\n Estimated load time for down switch fragment: ").concat(F.toFixed(3)," s\n TTFB estimate: ").concat(0|T," ms\n Current BW estimate: ").concat(Z(b)?0|b:"Unknown"," bps\n New BW estimate: ").concat(0|r.getBwEstimate()," bps\n Switching to level ").concat(_," @ ").concat(0|U," bps")),s.nextLoadLevel=s.nextAutoLevel=_,r.clearTimer();var G=function(){r.clearTimer();var e=r.hls;if(r.fragCurrent===n&&e.loadLevel===_&&_>0){var t=r.getStarvationDelay();if(r.warn("Aborting inflight request ".concat(_>0?"and switching down":"","\n Fragment duration: ").concat(n.duration.toFixed(3)," s\n Time to underbuffer: ").concat(t.toFixed(3)," s")),n.abortRequests(),r.fragCurrent=r.partCurrent=null,_>f){var i=r.findBestLevel(e.levels[f].bitrate,f,_,0,t,1,1);-1===i&&(i=f),e.nextLoadLevel=e.nextAutoLevel=i,r.firstAutoFloor=Math.min(i,e.firstLevel),r.resetEstimator(e.levels[i].bitrate)}}};p||D>2*F?G():r.timer=self.setInterval(G,1e3*F),s.trigger(ne.FRAG_LOAD_EMERGENCY_ABORTED,{frag:n,part:a,stats:c})}}}}}}}}},r.hls=e,r.bwEstimator=r.initEstimator(),r.registerListeners(),r}return f(t,e),l(t,[{key:"resetEstimator",value:function(e){this.hls&&(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 Ne(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}},{key:"registerListeners",value:function(){var e=this.hls;e.on(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ne.FRAG_LOADING,this.onFragLoading,this),e.on(ne.FRAG_LOADED,this.onFragLoaded,this),e.on(ne.FRAG_BUFFERED,this.onFragBuffered,this),e.on(ne.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(ne.LEVEL_LOADED,this.onLevelLoaded,this),e.on(ne.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(ne.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(ne.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ne.FRAG_LOADING,this.onFragLoading,this),e.off(ne.FRAG_LOADED,this.onFragLoaded,this),e.off(ne.FRAG_BUFFERED,this.onFragBuffered,this),e.off(ne.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(ne.LEVEL_LOADED,this.onLevelLoaded,this),e.off(ne.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(ne.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(ne.ERROR,this.onError,this))}},{key:"destroy",value:function(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.audioTracksByGroup=this.codecTiers=this.fragCurrent=this.partCurrent=null}},{key:"onManifestLoading",value:function(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}},{key:"onLevelsUpdated",value:function(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}},{key:"onMaxAutoLevelUpdated",value:function(){this.firstSelection=-1,this.nextAutoLevelKey=""}},{key:"onFragLoading",value:function(e,t){var r=t.frag;if(!this.ignoreFragment(r)){var i;if(!r.bitrateTest)this.fragCurrent=r,this.partCurrent=null!=(i=t.part)?i:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}},{key:"onLevelSwitching",value:function(e,t){this.clearTimer()}},{key:"onError",value:function(e,t){if(!t.fatal)switch(t.details){case ie.BUFFER_ADD_CODEC_ERROR:case ie.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case ie.FRAG_LOAD_TIMEOUT:var r=t.frag,i=this.fragCurrent,n=this.partCurrent;if(r&&ye(r,i)){var a=performance.now(),s=n?n.stats:r.stats,o=a-s.loading.start,l=s.loading.first?s.loading.first-s.loading.start:-1;if(s.loaded&&l>-1){var u=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(o-Math.min(u,l),s.loaded)}else this.bwEstimator.sampleTTFB(o)}}}},{key:"getTimeToLoadFrag",value:function(e,t,r,i){return e+r/t+(i?e+this.lastLevelLoadSec:0)}},{key:"onLevelLoaded",value:function(e,t){var r=this.hls.config,i=t.stats.loading,n=i.end-i.first;Z(n)&&(this.lastLevelLoadSec=n/1e3),t.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}},{key:"onFragLoaded",value:function(e,t){var r,i=t.frag,n=t.part,a=n?n.stats:i.stats;if(i.type===de.MAIN&&this.bwEstimator.sampleTTFB(a.loading.first-a.loading.start),!this.ignoreFragment(i)){if(this.clearTimer(),i.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,null!=(r=this.hls)&&r.config.abrMaxWithRealBitrate){var s=n?n.duration:i.duration,o=this.hls.levels[i.level],l=(o.loaded?o.loaded.bytes:0)+a.loaded,u=(o.loaded?o.loaded.duration:0)+s;o.loaded={bytes:l,duration:u},o.realBitrate=Math.round(8*l/u)}if(i.bitrateTest){var c={stats:a,frag:i,part:n,id:i.type};this.onFragBuffered(ne.FRAG_BUFFERED,c),i.bitrateTest=!1}else this.lastLoadedFragLevel=i.level}}},{key:"onFragBuffered",value:function(e,t){var r=t.frag,i=t.part,n=null!=i&&i.stats.loaded?i.stats:r.stats;if(!n.aborted&&!this.ignoreFragment(r)){var a=((r.bitrate||0)>=1e5?n.parsing.end:n.loading.end)-n.loading.start-Math.min(n.loading.first-n.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,n.loaded),n.bwEstimate=this.getBwEstimate(),r.bitrateTest?this.bitrateTestDelay=a/1e3:(this.bitrateTestDelay=0,this.firstAutoFloor>-1&&this.bwEstimator.canEstimate()&&(this.firstAutoFloor=-1))}}},{key:"ignoreFragment",value:function(e){return e.type!==de.MAIN||"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;if(!e)return 0;var t=e.maxAutoLevel,r=e.minAutoLevel,i=this.getBwEstimate(),n=this.getStarvationDelay(),a=e.config.maxStarvationDelay,s=this.findBestLevel(i,r,t,n/2,a,1,1);if(s>-1)return s;var o=e.firstLevel,l=-1===this.firstAutoFloor?1/0:this.firstAutoFloor,u=Math.min(Math.max(o,r),t,l);return this.warn("Could not find best starting auto level. Defaulting to first in playlist ".concat(o," clamped to ").concat(u)),u}},{key:"forcedAutoLevel",get:function(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}},{key:"nextAutoLevel",get:function(){if(!this.hls)return-1;var e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),r=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&r&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;var i=t&&r?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){var n=this.hls.levels;if(n.length>Math.max(e,i)&&n[e].loadError<=n[i].loadError)return e}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i},set:function(e){var t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}},{key:"getAutoLevelKey",value:function(){return"".concat(this.getBwEstimate(),"_").concat(this.getStarvationDelay().toFixed(2))}},{key:"getNextABRAutoLevel",value:function(){var e=this.fragCurrent,t=this.partCurrent,r=this.hls;if(!r)return-1;if(r.levels.length<=1)return r.loadLevel;var i=r.maxAutoLevel,n=r.config,a=r.minAutoLevel,s=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay(),u=n.abrBandWidthFactor,c=n.abrBandWidthUpFactor;if(l){var d=this.findBestLevel(o,a,i,l,0,u,c);if(d>=0)return this.rebufferNotice=-1,d}var h=s?Math.min(s,n.maxStarvationDelay):n.maxStarvationDelay;if(!l){var f=this.bitrateTestDelay;if(f)h=(s?Math.min(s,n.maxLoadingDelay):n.maxLoadingDelay)-f,this.info("bitrate test took ".concat(Math.round(1e3*f),"ms, set first fragment max fetchDuration to ").concat(Math.round(1e3*h)," ms")),u=c=1}var v=this.findBestLevel(o,a,i,l,h,u,c);if(this.rebufferNotice!==v&&(this.rebufferNotice=v,this.info("".concat(l?"rebuffering expected":"buffer is empty",", optimal quality level ").concat(v))),v>-1)return v;var g=r.levels[a],p=r.loadLevelObj;return p&&(null==g?void 0:g.bitrate)<p.bitrate?a:r.loadLevel}},{key:"getStarvationDelay",value:function(){var e=this.hls,t=null==e?void 0:e.media;if(!t)return 1/0;var r=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/r}},{key:"getBwEstimate",value:function(){return this.bwEstimator.getEstimate()}},{key:"findBestLevel",value:function(e,t,r,i,n,a,s){var o=this,l=this.hls,u=this.lastLoadedFragLevel,c=this.fragCurrent,d=this.partCurrent;if(!l)return-1;var h=i+n,f=-1===u?l.firstLevel:u,v=l.levels,g=l.allAudioTracks,p=l.loadLevel,m=l.latestLevelDetails,y=l.config;if(1===v.length)return 0;var k,E=v[f],S=!(null==m||!m.live),T=-1===p||-1===u,A="SDR",b=(null==E?void 0:E.frameRate)||0,I=y.audioPreference,R=y.videoPreference,L=this.audioTracksByGroup||(this.audioTracksByGroup=Ur(g)),P=-1;if(T){if(-1!==this.firstSelection)return this.firstSelection;var w=this.codecTiers||(this.codecTiers=function(e,t,r,i){return e.slice(r,i+1).reduce(function(e,r,i){if(!r.codecSet)return e;var n=r.audioGroups,a=e[r.codecSet];a||(e[r.codecSet]=a={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:i,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!n,fragmentError:0}),a.minBitrate=Math.min(a.minBitrate,r.bitrate);var s=Math.min(r.height,r.width);return a.minHeight=Math.min(a.minHeight,s),a.minFramerate=Math.min(a.minFramerate,r.frameRate),a.minIndex=Math.min(a.minIndex,i),a.maxScore=Math.max(a.maxScore,r.score),a.fragmentError+=r.fragmentError,a.videoRanges[r.videoRange]=(a.videoRanges[r.videoRange]||0)+1,n&&n.forEach(function(e){if(e){var r=t.groups[e];r&&(a.hasDefaultAudio=a.hasDefaultAudio||t.hasDefaultAudio?r.hasDefault:r.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(r.channels).forEach(function(e){a.channels[e]=(a.channels[e]||0)+r.channels[e]}))}}),e},{})}(v,L,t,r)),C=function(e,t,r,i,n){for(var a=Object.keys(e),s=null==i?void 0:i.channels,o=null==i?void 0:i.audioCodec,l=null==n?void 0:n.videoCodec,u=s&&2===parseInt(s),c=!1,d=!1,h=1/0,f=1/0,v=1/0,g=1/0,p=0,m=[],y=Fr(t,n),k=y.preferHDR,E=y.allowedVideoRanges,S=function(){var t=e[a[T]];c||(c=t.channels[2]>0),h=Math.min(h,t.minHeight),f=Math.min(f,t.minFramerate),v=Math.min(v,t.minBitrate),E.filter(function(e){return t.videoRanges[e]>0}).length>0&&(d=!0)},T=a.length;T--;)S();h=Z(h)?h:0,f=Z(f)?f:0;var A=Math.max(1080,h),b=Math.max(30,f);v=Z(v)?v:r,r=Math.max(v,r),d||(t=void 0);var I=a.length>1;return{codecSet:a.reduce(function(t,i){var n=e[i];if(i===t)return t;if(m=d?E.filter(function(e){return n.videoRanges[e]>0}):[],I){if(n.minBitrate>r)return Br(i,"min bitrate of ".concat(n.minBitrate," > current estimate of ").concat(r)),t;if(!n.hasDefaultAudio)return Br(i,"no renditions with default or auto-select sound found"),t;if(o&&i.indexOf(o.substring(0,4))%5!=0)return Br(i,'audio codec preference "'.concat(o,'" not found')),t;if(s&&!u){if(!n.channels[s])return Br(i,"no renditions with ".concat(s," channel sound found (channels options: ").concat(Object.keys(n.channels),")")),t}else if((!o||u)&&c&&0===n.channels[2])return Br(i,"no renditions with stereo sound found"),t;if(n.minHeight>A)return Br(i,"min resolution of ".concat(n.minHeight," > maximum of ").concat(A)),t;if(n.minFramerate>b)return Br(i,"min framerate of ".concat(n.minFramerate," > maximum of ").concat(b)),t;if(!m.some(function(e){return n.videoRanges[e]>0}))return Br(i,"no variants with VIDEO-RANGE of ".concat(Nr(m)," found")),t;if(l&&i.indexOf(l.substring(0,4))%5!=0)return Br(i,'video codec preference "'.concat(l,'" not found')),t;if(n.maxScore<p)return Br(i,"max score of ".concat(n.maxScore," < selected max of ").concat(p)),t}return t&&(dr(i)>=dr(t)||n.fragmentError>e[t].fragmentError)?t:(g=n.minIndex,p=n.maxScore,i)},void 0),videoRanges:m,preferHDR:k,minFramerate:f,minBitrate:v,minIndex:g}}(w,A,e,I,R),D=C.codecSet,_=C.videoRanges,M=C.minFramerate,x=C.minBitrate,O=C.minIndex,F=C.preferHDR;P=O,k=D,A=F?_[_.length-1]:_[0],b=M,e=Math.max(e,x),this.log("picked start tier ".concat(Nr(C)))}else k=null==E?void 0:E.codecSet,A=null==E?void 0:E.videoRange;for(var N,B,U=d?d.duration:c?c.duration:0,V=this.bwEstimator.getEstimateTTFB()/1e3,G=[],H=function(){var t=v[K],l=K>f;if(!t)return 0;if(y.useMediaCapabilities&&!t.supportedResult&&!t.supportedPromise){var c=navigator.mediaCapabilities;"function"==typeof(null==c?void 0:c.decodingInfo)&&function(e,t,r,i,n,a){var s=e.videoCodec,o=e.audioCodec?e.audioGroups:null,l=null==a?void 0:a.audioCodec,u=null==a?void 0:a.channels,c=u?parseInt(u):l?1/0:2,d=null;if(null!=o&&o.length)try{d=1===o.length&&o[0]?t.groups[o[0]].channels:o.reduce(function(e,r){if(r){var i=t.groups[r];if(!i)throw new Error("Audio track group ".concat(r," not found"));Object.keys(i.channels).forEach(function(t){e[t]=(e[t]||0)+i.channels[t]})}return e},{2:0})}catch(e){return!0}return void 0!==s&&(s.split(",").some(function(e){return jt(e)})||e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(i,30)||"SDR"!==e.videoRange&&e.videoRange!==r||e.bitrate>Math.max(n,8e6))||!!d&&Z(c)&&Object.keys(d).some(function(e){return parseInt(e)>c})}(t,L,A,b,e,I)?(t.supportedPromise=Ar(t,L,c,o.supportedCache),t.supportedPromise.then(function(e){if(o.hls){t.supportedResult=e;var r=o.hls.levels,i=r.indexOf(t);e.error?o.warn('MediaCapabilities decodingInfo error: "'.concat(e.error,'" for level ').concat(i," ").concat(Nr(e))):e.supported?e.decodingInfoResults.some(function(e){return!1===e.smooth||!1===e.powerEfficient})&&o.log("MediaCapabilities decodingInfo for level ".concat(i," not smooth or powerEfficient: ").concat(Nr(e))):(o.warn("Unsupported MediaCapabilities decodingInfo result for level ".concat(i," ").concat(Nr(e))),i>-1&&r.length>1&&(o.log("Removing unsupported level ".concat(i)),o.hls.removeLevel(i),-1===o.hls.loadLevel&&(o.hls.nextLoadLevel=0)))}}).catch(function(e){o.warn("Error handling MediaCapabilities decodingInfo: ".concat(e))})):t.supportedResult=Sr}if((k&&t.codecSet!==k||A&&t.videoRange!==A||l&&b>t.frameRate||!l&&b>0&&b<t.frameRate||null!=(N=t.supportedResult)&&null!=(N=N.decodingInfoResults)&&N.some(function(e){return!1===e.smooth}))&&(!T||K!==P))return G.push(K),0;var g,m=t.details,E=(d?null==m?void 0:m.partTarget:null==m?void 0:m.averagetargetduration)||U||1;g=l?s*e:a*e;var R=U&&i>=2*U&&0===n?t.averageBitrate:t.maxBitrate,w=o.getTimeToLoadFrag(V,g,R*E,!m||m.live);if(g>=R&&(K===u||0===t.loadError&&0===t.fragmentError||Oe(t,y.errorPenaltyExpireMs))&&(w<=V||!Z(w)||S&&!o.bitrateTestDelay||w<h)){var C=o.forcedAutoLevel;return K===p||-1!==C&&C===p||(G.length&&o.trace("Skipped level(s) ".concat(G.join(",")," of ").concat(r,' max with CODECS and VIDEO-RANGE:"').concat(v[G[0]].codecs,'" ').concat(v[G[0]].videoRange,'; not compatible with "').concat(k,'" ').concat(A)),o.info("switch candidate:".concat(f,"->").concat(K," adjustedbw(").concat(Math.round(g),")-bitrate=").concat(Math.round(g-R)," ttfb:").concat(V.toFixed(1)," avgDuration:").concat(E.toFixed(1)," maxFetchDuration:").concat(h.toFixed(1)," fetchDuration:").concat(w.toFixed(1)," firstSelection:").concat(T," codecSet:").concat(t.codecSet," videoRange:").concat(t.videoRange," hls.loadLevel:").concat(p))),T&&(o.firstSelection=K),{v:K}}},K=r;K>=t;K--)if(0!==(B=H())&&B)return B.v;return-1}},{key:"deriveNextAutoLevel",value:function(e){if(!this.hls)return-1;var t=this.hls,r=t.maxAutoLevel,i=t.minAutoLevel;return Math.min(Math.max(e,i),r)}}])}(Be),Xr=function(e,t){for(var r=0,i=e.length-1,n=null,a=null;r<=i;){var s=t(a=e[n=(r+i)/2|0]);if(s>0)r=n+1;else{if(!(s<0))return a;i=n-1}}return null};function Qr(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:.005,a=null;if(e){a=t[1+e.sn-t[0].sn]||null;var s=e.endDTS-r;s>0&&s<15e-7&&(r+=15e-7),a&&e.level!==a.level&&a.end<=e.end&&(a=t[2+e.sn-t[0].sn]||null)}else 0===r&&0===t[0].start&&(a=t[0]);if(a&&((!e||e.level===a.level)&&0===$r(r,i,a)||function(e,t,r){if(0===(null==t?void 0:t.start)&&t.level<e.level&&(t.endPTS||0)>0){var i=t.tagList.reduce(function(e,t){return"INF"===t[0]&&(e+=parseFloat(t[1])),e},r);return e.start<=i}return!1}(a,e,Math.min(n,i))))return a;var o=Xr(t,$r.bind(null,r,i));return!o||o===e&&a?a:o}function $r(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2?arguments[2]:void 0;if(r.start<=e&&r.start+r.duration>e)return 0;var i=Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-i<=e?1:r.start-i>e&&r.start?-1:0}function Jr(e,t,r){var i=1e3*Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-i>e}function Zr(e,t,r){if(e&&e.startCC<=t&&e.endCC>=t){var i,n=e.fragments,a=e.fragmentHint;return a&&(n=n.concat(a)),Xr(n,function(e){return e.cc<t?1:e.cc>t?-1:(i=e,e.end<=r?1:e.start>r?-1:0)}),i||null}return null}function ei(e,t){return t===e.endSN&&e.fragmentHint?e.fragmentHint:e.fragments[1+t-e.startSN]||null}var ti=0,ri=2,ii=3,ni=5,ai=0,si=1,oi=2,li=4,ui=8,ci=16,di=function(e){function t(e){var r;return s(this,t),(r=a(this,t,["error-controller",e.logger])).hls=void 0,r.playlistError=0,r.hls=e,r.registerListeners(),r}return f(t,e),l(t,[{key:"registerListeners",value:function(){var e=this.hls;e.on(ne.ERROR,this.onError,this),e.on(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ne.LEVEL_UPDATED,this.onLevelUpdated,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ne.ERROR,this.onError,this),e.off(ne.ERROR,this.onErrorOut,this),e.off(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ne.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)===de.MAIN?e.level:this.getVariantIndex()}},{key:"getVariantIndex",value:function(){var e,t=this.hls,r=t.currentLevel;return null!=(e=t.loadLevelObj)&&e.details||-1===r?t.loadLevel:r}},{key:"variantHasKey",value:function(e,t){if(e){var r;if(null!=(r=e.details)&&r.hasKey(t))return!0;var i=e.audioGroups;if(i)return this.hls.allAudioTracks.filter(function(e){return i.indexOf(e.groupId)>=0}).some(function(e){var r;return null==(r=e.details)?void 0:r.hasKey(t)})}return!1}},{key:"onManifestLoading",value:function(){this.playlistError=0}},{key:"onLevelUpdated",value:function(){this.playlistError=0}},{key:"onError",value:function(e,t){var r;if(!t.fatal){var i=this.hls,n=t.context;switch(t.details){case ie.FRAG_LOAD_ERROR:case ie.FRAG_LOAD_TIMEOUT:case ie.KEY_LOAD_ERROR:case ie.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case ie.FRAG_PARSING_ERROR:if(null!=(r=t.frag)&&r.gap)return void(t.errorAction=vi());case ie.FRAG_GAP:case ie.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=ri);case ie.PLAYLIST_UNCHANGED_ERROR:case ie.LEVEL_EMPTY_ERROR:case ie.LEVEL_PARSING_ERROR:var a,s=t.parent===de.MAIN?t.level:i.loadLevel;return void(t.details===ie.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 ie.LEVEL_LOAD_ERROR:case ie.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==n?void 0:n.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level)));case ie.AUDIO_TRACK_LOAD_ERROR:case ie.AUDIO_TRACK_LOAD_TIMEOUT:case ie.SUBTITLE_LOAD_ERROR:case ie.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){var o=i.loadLevelObj;if(o&&(n.type===ce.AUDIO_TRACK&&o.hasAudioGroup(n.groupId)||n.type===ce.SUBTITLE_TRACK&&o.hasSubtitleGroup(n.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.loadLevel),t.errorAction.action=ri,void(t.errorAction.flags=si)}return;case ie.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(t.errorAction={action:ri,flags:oi});case ie.KEY_SYSTEM_SESSION_UPDATE_FAILED:case ie.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case ie.KEY_SYSTEM_NO_SESSION:return void(t.errorAction={action:ri,flags:li});case ie.BUFFER_ADD_CODEC_ERROR:case ie.REMUX_ALLOC_ERROR:case ie.BUFFER_APPEND_ERROR:return void(t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,t.level)));case ie.MEDIA_SOURCE_REQUIRES_RESET:return t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,t.level)),void(t.errorAction.flags|=ci|ui);case ie.INTERNAL_EXCEPTION:case ie.BUFFER_APPENDING_ERROR:case ie.BUFFER_APPEND_NO_PROGRESS:case ie.BUFFER_FULL_ERROR:case ie.LEVEL_SWITCH_ERROR:case ie.BUFFER_STALLED_ERROR:case ie.BUFFER_SEEK_OVER_HOLE:case ie.BUFFER_NUDGE_ON_STALL:return void(t.errorAction=vi())}t.type===re.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=vi())}}},{key:"getPlaylistRetryOrSwitchAction",value:function(e,t){var r=Ce(this.hls.config.playlistLoadPolicy,e),i=this.playlistError++;if(Me(r,i,Le(e),e.response))return{action:ni,flags:ai,retryConfig:r,retryCount:i};var n=this.getLevelSwitchAction(e,t);return r&&(n.retryConfig=r,n.retryCount=i),n}},{key:"getFragRetryOrSwitchAction",value:function(e){var t=this.hls,r=this.getVariantLevelIndex(e.frag),i=t.levels[r],n=t.config,a=n.fragLoadPolicy,s=n.keyLoadPolicy,o=Ce(Pe(e)?s:a,e),l=t.levels.reduce(function(e,t){return e+t.fragmentError},0);if(i&&(e.details!==ie.FRAG_GAP&&i.fragmentError++,!we(e)&&Me(o,l,Le(e),e.response)))return{action:ni,flags:ai,retryConfig:o,retryCount:l};var u=this.getLevelSwitchAction(e,r);return o&&(u.retryConfig=o,u.retryCount=l),u}},{key:"getLevelSwitchAction",value:function(e,t){var r=this.hls;null==t&&(t=r.loadLevel);var i=this.hls.levels[t];if(i){var n,a,s=e.details;i.loadError++,i.loadErrorTime=self.performance.now(),s===ie.BUFFER_APPEND_ERROR&&i.fragmentError++;var o=-1,l=r.levels,u=r.loadLevel,c=r.minAutoLevel,d=r.maxAutoLevel;r.autoLevelEnabled||r.config.preserveManualLevelOnError||(r.loadLevel=-1);for(var h,f,v,g=null==(n=e.frag)?void 0:n.type,p=(g===de.AUDIO&&s===ie.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&hi(e))&&l.some(function(e){var t=e.audioCodec;return i.audioCodec!==t}),m="video"===e.sourceBufferName&&hi(e)&&l.some(function(e){var t=e.codecSet,r=e.audioCodec;return i.codecSet!==t&&i.audioCodec===r}),y=null!=(a=e.context)?a:{},k=y.type,E=y.groupId,S=function(){var t=(T+u)%l.length;if(t!==u&&t>=c&&t<=d&&(0===l[t].loadError||Oe(l[t],r.config.errorPenaltyExpireMs))){var n=l[t];if(s===ie.FRAG_GAP&&g===de.MAIN&&e.frag){var a=l[t].details;if(a){var v=Qr(e.frag,a.fragments,e.frag.start);if(null!=v&&v.gap)return 0}}else{if(k===ce.AUDIO_TRACK&&n.hasAudioGroup(E)||k===ce.SUBTITLE_TRACK&&n.hasSubtitleGroup(E))return 0;if(g===de.AUDIO&&null!=(h=i.audioGroups)&&h.some(function(e){return n.hasAudioGroup(e)})||g===de.SUBTITLE&&null!=(f=i.subtitleGroups)&&f.some(function(e){return n.hasSubtitleGroup(e)})||p&&i.audioCodec===n.audioCodec||m&&i.codecSet===n.codecSet||!p&&i.audioCodec!==n.audioCodec)return 0}return o=t,1}},T=l.length;T--&&(0===(v=S())||1!==v););if(o>-1&&r.loadLevel!==o)return e.levelRetry=!0,this.playlistError=0,{action:ri,flags:ai,nextAutoLevel:o}}return{action:ri,flags:si}}},{key:"onErrorOut",value:function(e,t){var r,i;switch(null==(r=t.errorAction)?void 0:r.action){case ti:break;case ri:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===ie.FRAG_GAP||t.details===ie.PLAYLIST_UNCHANGED_ERROR||fi(t)||(t.fatal=!0)}((null==(i=t.errorAction)?void 0:i.flags)||0)&ci&&this.hls.recoverMediaError(),t.fatal&&this.hls.stopLoad()}},{key:"sendAlternateToPenaltyBox",value:function(e){var t=this.hls,r=e.errorAction;if(r){var i=r.nextAutoLevel;if(r.flags===ai)this.switchLevel(e,i);else if(r.flags&ui)for(var n=this.hls.levels,a=n.length;a--;)"SDR"!==n[a].videoRange?(n[a].fragmentError++,n[a].loadError++):void 0===i&&(i=a);else if(r.flags&oi){var s=this.getVariantLevelIndex(e.frag),o=t.levels[s],l=null==o?void 0:o.attrs["HDCP-LEVEL"];r.hdcpLevel=l;var u="NONE"===l;l&&!u?(t.maxHdcpLevel=Lr[Lr.indexOf(l)-1],r.resolved=!0,this.warn('Restricting playback to HDCP-LEVEL of "'.concat(t.maxHdcpLevel,'" or lower'))):(u&&this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE"),r.flags|=li)}if(r.flags&li){var c=e.decryptdata;if(c){for(var d=this.hls.levels,h=d.length,f=h;f--;){var v,g;if(this.variantHasKey(d[f],c))this.log("Banned key found in level ".concat(f," (").concat(d[f].bitrate,'bps) or audio group "').concat(null==(v=d[f].audioGroups)?void 0:v.join(","),'" (').concat(null==(g=e.frag)?void 0:g.type," fragment) ").concat(ft(c.keyId||[]))),d[f].fragmentError++,d[f].loadError++,this.log("Removing level ".concat(f," with key error (").concat(e.error,")")),this.hls.removeLevel(f)}var p=e.frag;if(this.hls.levels.length<h)r.resolved=!0;else if(p&&p.type!==de.MAIN){var m=p.decryptdata;m&&!c.matches(m)&&(r.resolved=!0)}}}r.resolved||this.switchLevel(e,i)}}},{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===ie.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&"audiovideo"!==e.sourceBufferName))for(var r=kr(e.mimeType),i=this.hls.levels,n=i.length;n--;)i[n]["".concat(e.sourceBufferName,"Codec")]===r&&(this.log("Removing level ".concat(n," for ").concat(e.details,' ("').concat(r,'" not supported)')),this.hls.removeLevel(n))}}])}(Be);function hi(e){var t=e.details;return t===ie.BUFFER_ADD_CODEC_ERROR||t===ie.MEDIA_SOURCE_REQUIRES_RESET||t===ie.BUFFER_APPEND_ERROR&&!fi(e)}function fi(e){return e.details===ie.BUFFER_APPEND_ERROR&&("QuotaExceededError"===e.error.name||"InvalidStateError"===e.error.name)}function vi(e){var t={action:ti,flags:ai};return e&&(t.resolved=!0),t}var gi="NOT_LOADED",pi="APPENDING",mi="PARTIAL",yi="OK",ki=function(){return l(function e(t){s(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(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ne.BUFFER_APPENDED,this.onBufferAppended,this),e.on(ne.FRAG_BUFFERED,this.onFragBuffered,this),e.on(ne.FRAG_LOADED,this.onFragLoaded,this))}},{key:"_unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ne.BUFFER_APPENDED,this.onBufferAppended,this),e.off(ne.FRAG_BUFFERED,this.onFragBuffered,this),e.off(ne.FRAG_LOADED,this.onFragLoaded,this))}},{key:"destroy",value:function(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}},{key:"getAppendedFrag",value:function(e,t){var r=this.activePartLists[t];if(r)for(var i=r.length;i--;){var n=r[i];if(!n)break;if(n.start<=e&&e<=n.end&&n.loaded)return n}return this.getBufferedFrag(e,t)}},{key:"getBufferedFrag",value:function(e,t){return this.getFragAtPos(e,t,!0)}},{key:"getFragAtPos",value:function(e,t,r){for(var i=this.fragments,n=Object.keys(i),a=n.length;a--;){var s=i[n[a]];if((null==s?void 0:s.body.type)===t&&(!r||s.buffered)){var o=s.body;if(o.start<=e&&e<=o.end)return o}}return null}},{key:"detectEvictedFragments",value:function(e,t,r,i,n,a){var s=this;this.timeRanges&&(this.timeRanges[e]=t);var o=(null==n?void 0:n.fragment.sn)||-1;Object.keys(this.fragments).forEach(function(n){var l=s.fragments[n];if(l&&s.hls){var u=l.body;if(!(o>=u.sn))if(l.buffered||l.loaded&&!a){var c=l.range[e];if(c)if(0!==c.time.length){if(c.time.some(function(e){var r=!s.isTimeBuffered(e.startPTS,e.endPTS,t);return r&&s.removeFragment(u),r}),i&&i!==u&&ir()){var d=i.endPTS,h=u.startPTS;if(d&&h&&l.range.video){var f=h-d;f<0&&f>-.1&&(s.removeFragment(u),s.hls.trigger(ne.BUFFER_FLUSHING,{startOffset:d+.004,endOffset:1/0,type:"video"}))}}}else s.removeFragment(u)}else u.type===r&&s.removeFragment(u)}})}},{key:"detectPartialFragments",value:function(e){var t=this,r=this.timeRanges,i=e.frag,n=e.part,a=e.id;if(r&&pe(i)){var s=Si(i),o=this.fragments[s];if(!(!o||o.buffered&&i.gap)){var l=!i.relurl;Object.keys(r).forEach(function(e){var s=i.elementaryStreams[e];if(s){var u=r[e],c=l||!0===s.partial;o.range[e]=t.getBufferedTimes(i,n,c,u),t.detectEvictedFragments(e,u,a,i,n)}}),o.loaded=null;var u=Object.keys(o.range);if(u.length){if(this.bufferedEnd(o,i),Ei(o)||this.removeParts(i.sn-1,i.type),!n){var c=Math.min(.004,i.duration);u.some(function(e){var r,n=null==(r=o.range[e])?void 0:r.time,a=0===n.length||1===n.length&&n[0].endPTS-n[0].startPTS<c;return a&&t.addAsGap(i),a})}}else this.removeFragment(i)}}}},{key:"addAsGap",value:function(e){e.gap=!0,this.removeFragment(e),this.fragBuffered(e,!0)}},{key:"bufferedEnd",value:function(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&!t.gap&&(this.endListFragments[e.body.type]=e)}},{key:"removeParts",value:function(e,t){var r=this.activePartLists[t];r&&(this.activePartLists[t]=Ti(r,function(t){return t.fragment.sn>=e}))}},{key:"fragBuffered",value:function(e,t){var r=Si(e),i=this.fragments[r];return!i&&t&&(i=this.fragments[r]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,this.bufferedEnd(i,e)),i}},{key:"getBufferedTimes",value:function(e,t,r,i){for(var n={time:[],partial:r},a=e.start,s=e.end,o=e.minEndPTS||s,l=e.maxStartPTS||a,u=0;u<i.length;u++){var c=i.start(u)-this.bufferPadding,d=i.end(u)+this.bufferPadding;if(l>=c&&o<=d){n.time.push({startPTS:Math.max(a,i.start(u)),endPTS:Math.min(s,i.end(u))});break}if(a<d&&s>c){var h=Math.max(a,i.start(u)),f=Math.min(s,i.end(u));f>h&&(n.partial=!0,n.time.push({startPTS:h,endPTS:f}))}else if(s<=c)break}return n}},{key:"getPartialFragment",value:function(e){var t,r,i,n=null,a=0,s=this.bufferPadding,o=this.fragments;return Object.keys(o).forEach(function(l){var u=o[l];u&&Ei(u)&&(r=u.body.start-s,i=u.body.end+s,e>=r&&e<=i&&(t=Math.min(e-r,i-e),a<=t&&(n=u.body,a=t)))}),n}},{key:"isEndListAppended",value:function(e){var t=this.endListFragments[e];return void 0!==t&&(t.buffered||Ei(t))}},{key:"getState",value:function(e){var t=Si(e),r=this.fragments[t];return r?r.buffered?Ei(r)?mi:yi:pi:gi}},{key:"isTimeBuffered",value:function(e,t,r){for(var i,n,a=0;a<r.length;a++){if(i=r.start(a)-this.bufferPadding,n=r.end(a)+this.bufferPadding,e>=i&&t<=n)return!0;if(t<=i)return!1}return!1}},{key:"onManifestLoading",value:function(){this.removeAllFragments()}},{key:"onFragLoaded",value:function(e,t){if(pe(t.frag)&&!t.frag.bitrateTest){var r=t.frag,i=t.part?null:t,n=Si(r);this.fragments[n]={body:r,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}}},{key:"onBufferAppended",value:function(e,t){var r=t.frag,i=t.part,n=t.timeRanges;if(pe(r)){var a=r.type;if(i){var s=this.activePartLists[a];s||(this.activePartLists[a]=s=[]),s.push(i)}this.timeRanges=n}}},{key:"onFragBuffered",value:function(e,t){this.detectPartialFragments(t)}},{key:"hasFragment",value:function(e){var t=Si(e);return!!this.fragments[t]}},{key:"hasFragments",value:function(e){var t=this.fragments,r=Object.keys(t);if(!e)return r.length>0;for(var i=r.length;i--;){var n=t[r[i]];if((null==n?void 0:n.body.type)===e)return!0}return!1}},{key:"hasParts",value:function(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)}},{key:"getBackBufferEvictionEnd",value:function(e,t,r){for(var i=this.fragments,n=0,a=0,s=Object.keys(i),o=0;o<s.length;o++){var l=i[s[o]];if(l&&l.buffered&&l.body.type===t){var u=l.body;if(u.gap)return 0;var c=u.hasStats&&u.stats.loaded||u.byteLength||u.bitrate&&8*u.bitrate*u.duration;if(u.end<=e&&c&&(n+=c,a=Math.max(a,u.end),n>=r))return a}}return a>0?a:0}},{key:"removeFragmentsInRange",value:function(e,t,r,i,n){var a=this;i&&!this.hasGaps||Object.keys(this.fragments).forEach(function(s){var o=a.fragments[s];if(o){var l=o.body;l.type!==r||i&&!l.gap||l.start<t&&l.end>e&&(o.buffered||n)&&a.removeFragment(l)}})}},{key:"removeFragment",value:function(e){var t=Si(e);e.clearElementaryStreamInfo();var r=this.activePartLists[e.type];if(r){var i=e.sn;this.activePartLists[e.type]=Ti(r,function(e){return e.fragment.sn!==i})}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}},{key:"removeAllFragments",value:function(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;var t=null==(e=this.hls)||null==(e=e.latestLevelDetails)?void 0:e.partList;t&&t.forEach(function(e){return e.clearElementaryStreamInfo()})}}])}();function Ei(e){var t,r,i,n;return e.buffered&&!!(e.body.gap||null!=(t=e.range.video)&&t.partial||null!=(r=e.range.audio)&&r.partial||null!=(i=e.range.audiovideo)&&i.partial||null!=(n=e.range.subs)&&n.partial)}function Si(e){return"".concat(e.type,"_").concat(e.level,"_").concat(e.sn)}function Ti(e,t){return e.filter(function(e){var r=t(e);return r||e.clearElementaryStreamInfo(),r})}var Ai=0,bi=1,Ii=function(){return l(function e(t,r,i){s(this,e),this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=r,this.aesMode=i},[{key:"decrypt",value:function(e,t){switch(this.aesMode){case Ai:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case bi: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 Ri=function(){return l(function e(){s(this,e),this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()},[{key:"uint8ArrayToUint32Array_",value:function(e){for(var t=new DataView(e),r=new Uint32Array(4),i=0;i<4;i++)r[i]=t.getUint32(4*i);return r}},{key:"initTable",value:function(){var e=this.sBox,t=this.invSBox,r=this.subMix,i=r[0],n=r[1],a=r[2],s=r[3],o=this.invSubMix,l=o[0],u=o[1],c=o[2],d=o[3],h=new Uint32Array(256),f=0,v=0,g=0;for(g=0;g<256;g++)h[g]=g<128?g<<1:g<<1^283;for(g=0;g<256;g++){var p=v^v<<1^v<<2^v<<3^v<<4;p=p>>>8^255&p^99,e[f]=p,t[p]=f;var m=h[f],y=h[m],k=h[y],E=257*h[p]^16843008*p;i[f]=E<<24|E>>>8,n[f]=E<<16|E>>>16,a[f]=E<<8|E>>>24,s[f]=E,E=16843009*k^65537*y^257*m^16843008*f,l[p]=E<<24|E>>>8,u[p]=E<<16|E>>>16,c[p]=E<<8|E>>>24,d[p]=E,f?(f=m^h[h[h[k^m]]],v^=h[h[v]]):f=v=1}}},{key:"expandKey",value:function(e){for(var t=this.uint8ArrayToUint32Array_(e),r=!0,i=0;i<t.length&&r;)r=t[i]===this.key[i],i++;if(!r){this.key=t;var n=this.keySize=t.length;if(4!==n&&6!==n&&8!==n)throw new Error("Invalid aes key size="+n);var a,s,o,l,u=this.ksRows=4*(n+6+1),c=this.keySchedule=new Uint32Array(u),d=this.invKeySchedule=new Uint32Array(u),h=this.sBox,f=this.rcon,v=this.invSubMix,g=v[0],p=v[1],m=v[2],y=v[3];for(a=0;a<u;a++)a<n?o=c[a]=t[a]:(l=o,a%n===0?(l=h[(l=l<<8|l>>>24)>>>24]<<24|h[l>>>16&255]<<16|h[l>>>8&255]<<8|h[255&l],l^=f[a/n|0]<<24):n>6&&a%n===4&&(l=h[l>>>24]<<24|h[l>>>16&255]<<16|h[l>>>8&255]<<8|h[255&l]),c[a]=o=(c[a-n]^l)>>>0);for(s=0;s<u;s++)a=u-s,l=3&s?c[a]:c[a-4],d[s]=s<4||a<=4?l:g[h[l>>>24]]^p[h[l>>>16&255]]^m[h[l>>>8&255]]^y[h[255&l]],d[s]=d[s]>>>0}}},{key:"networkToHostOrderSwap",value:function(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24}},{key:"decrypt",value:function(e,t,r){for(var i,n,a,s,o,l,u,c,d,h,f,v,g,p,m=this.keySize+6,y=this.invKeySchedule,k=this.invSBox,E=this.invSubMix,S=E[0],T=E[1],A=E[2],b=E[3],I=this.uint8ArrayToUint32Array_(r),R=I[0],L=I[1],P=I[2],w=I[3],C=new Int32Array(e),D=new Int32Array(C.length),_=this.networkToHostOrderSwap;t<C.length;){for(d=_(C[t]),h=_(C[t+1]),f=_(C[t+2]),v=_(C[t+3]),o=d^y[0],l=v^y[1],u=f^y[2],c=h^y[3],g=4,p=1;p<m;p++)i=S[o>>>24]^T[l>>16&255]^A[u>>8&255]^b[255&c]^y[g],n=S[l>>>24]^T[u>>16&255]^A[c>>8&255]^b[255&o]^y[g+1],a=S[u>>>24]^T[c>>16&255]^A[o>>8&255]^b[255&l]^y[g+2],s=S[c>>>24]^T[o>>16&255]^A[l>>8&255]^b[255&u]^y[g+3],o=i,l=n,u=a,c=s,g+=4;i=k[o>>>24]<<24^k[l>>16&255]<<16^k[u>>8&255]<<8^k[255&c]^y[g],n=k[l>>>24]<<24^k[u>>16&255]<<16^k[c>>8&255]<<8^k[255&o]^y[g+1],a=k[u>>>24]<<24^k[c>>16&255]<<16^k[o>>8&255]<<8^k[255&l]^y[g+2],s=k[c>>>24]<<24^k[o>>16&255]<<16^k[l>>8&255]<<8^k[255&u]^y[g+3],D[t]=_(i^R),D[t+1]=_(s^L),D[t+2]=_(a^P),D[t+3]=_(n^w),R=d,L=h,P=f,w=v,t+=4}return D.buffer}}])}(),Li=function(){return l(function e(t,r,i){s(this,e),this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=t,this.key=r,this.aesMode=i},[{key:"expandKey",value:function(){var e=function(e){switch(e){case Ai:return"AES-CBC";case bi: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 Pi=function(){return l(function e(t,r){if(s(this,e),this.logEnabled=!0,this.decryptRange=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,!0!==r)try{var i=self.crypto;i&&(this.subtle=i.subtle||i.webkitSubtle)}catch(e){}this.useSoftware=!this.subtle},[{key:"destroy",value:function(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}},{key:"isSync",value:function(){return this.useSoftware}},{key:"flush",value:function(){var e=this.currentResult,t=this.remainderData;if(!e||t)return this.reset(),null;var r=new Uint8Array(e);this.reset();var i,n,a,s=this.decryptRange;return s?0===s.start&&s.end>=r.length?r:r.slice(s.start,s.end):(n=(i=r).byteLength,(a=n&&new DataView(i.buffer).getUint8(n-1))?i.slice(0,n-a):i)}},{key:"reset",value:function(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}},{key:"decrypt",value:function(e,t,r,i,n){var a=this;return this.decryptRange=n,this.useSoftware||n?new Promise(function(n,s){var o=ArrayBuffer.isView(e)?e:new Uint8Array(e);a.softwareDecrypt(o,t,r,i);var l=a.flush();l?n(l.buffer):s(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,r,i)}},{key:"softwareDecrypt",value:function(e,t,r,i){var n=this.currentIV,a=this.currentResult,s=this.remainderData;if(i!==Ai||16!==t.byteLength)return je.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),s&&(e=Kt(s,e),this.remainderData=null);var o=this.getValidChunk(e);if(!o.length)return null;n&&(r=n);var l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Ri),l.expandKey(t);var u=a;return this.currentResult=l.decrypt(o.buffer,0,r),this.currentIV=o.slice(-16).buffer,u||null}},{key:"webCryptoDecrypt",value:function(e,t,r,i){var n=this;if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,r,i));this.key=t,this.fastAesKey=new Li(this.subtle,t,i)}return this.fastAesKey.expandKey().then(function(t){return n.subtle?(n.logOnce("WebCrypto AES decrypt"),new Ii(n.subtle,new Uint8Array(r),i).decrypt(e.buffer,t)):Promise.reject(new Error("web crypto not initialized"))}).catch(function(a){return je.warn("[decrypter]: WebCrypto Error, disable WebCrypto API, ".concat(a.name,": ").concat(a.message)),n.onWebCryptoError(e,t,r,i)})}},{key:"onWebCryptoError",value:function(e,t,r,i){var n=this.enableSoftwareAES;if(n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,r,i);var a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(n?" and softwareDecrypt":"")+": failed to decrypt data")}},{key:"getValidChunk",value:function(e){var t=e,r=e.length-e.length%16;return r!==e.length&&(t=e.slice(0,r),this.remainderData=e.slice(r)),t}},{key:"logOnce",value:function(e){this.logEnabled&&(je.log("[decrypter]: ".concat(e)),this.logEnabled=!1)}}])}(),wi=Math.pow(2,17),Ci=function(){return l(function e(t){s(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,r,i){var n=this,a=e.url;if(!a)return Promise.reject(new xi({type:re.NETWORK_ERROR,details:ie.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a ".concat(a?"part list":"url")),networkDetails:null}));this.abort();var s=this.config,o=s.fLoader,l=s.loader;return new Promise(function(u,c){if(n.loader&&n.loader.destroy(),e.gap){if(e.tagList.some(function(e){return"GAP"===e[0]}))return void c(Mi(e));e.gap=!1}var d=n.loader=o?new o(s):new l(s),h=Di(e,null,t);e.loader=d;var f=_e(s.fragLoadPolicy.default),v={loadPolicy:f,timeout:f.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:wi};d.stats.retry=e.stats.retry,e.stats=d.stats;var g={onSuccess:function(t,r,i,a){n.resetLoader(e,d);var s=t.data;i.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(s.slice(0,16)),s=s.slice(16)),u({frag:e,part:null,payload:s,networkDetails:a})},onError:function(t,r,i,s){n.resetLoader(e,d),c(new xi({type:re.NETWORK_ERROR,details:ie.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Ie({url:a,data:void 0},t),error:new Error("HTTP Error ".concat(t.code," ").concat(t.text)),networkDetails:i,stats:s}))},onAbort:function(t,r,i){n.resetLoader(e,d),c(new xi({type:re.NETWORK_ERROR,details:ie.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:i,stats:t}))},onTimeout:function(t,r,i){n.resetLoader(e,d),c(new xi({type:re.NETWORK_ERROR,details:ie.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error("Timeout after ".concat(v.timeout,"ms")),networkDetails:i,stats:t}))}};if(r){var p=n.gateProgress(r,i);g.onProgress=function(t,r,i,n){return p({frag:e,part:null,payload:i,networkDetails:n})}}d.load(h,v,g)})}},{key:"gateProgress",value:function(e,t){var r=e;if(t){var i=[],n=!1;t.then(function(){n=!0,i.forEach(function(t){return e(t)}),i.length=0}).catch(function(){}),r=function(t){n?e(t):i.push(t)}}return r}},{key:"loadPart",value:function(e,t,r){var i=this;this.abort();var n=this.config,a=n.fLoader,s=n.loader;return new Promise(function(o,l){if(i.loader&&i.loader.destroy(),e.gap||t.gap)l(Mi(e,t));else{var u=i.loader=a?new a(n):new s(n),c=Di(e,t);e.loader=u;var d=_e(n.fragLoadPolicy.default),h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:wi};t.stats=u.stats,u.load(c,h,{onSuccess:function(n,a,s,l){i.resetLoader(e,u),i.updateStatsFromPart(e,t);var c={frag:e,part:t,payload:n.data,networkDetails:l};r(c),o(c)},onError:function(r,n,a,s){i.resetLoader(e,u),l(new xi({type:re.NETWORK_ERROR,details:ie.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:Ie({url:c.url,data:void 0},r),error:new Error("HTTP Error ".concat(r.code," ").concat(r.text)),networkDetails:a,stats:s}))},onAbort:function(r,n,a){e.stats.aborted=t.stats.aborted,i.resetLoader(e,u),l(new xi({type:re.NETWORK_ERROR,details:ie.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:a,stats:r}))},onTimeout:function(r,n,a){i.resetLoader(e,u),l(new xi({type:re.NETWORK_ERROR,details:ie.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error("Timeout after ".concat(h.timeout,"ms")),networkDetails:a,stats:r}))}})}})}},{key:"updateStatsFromPart",value:function(e,t){var r=e.stats,i=t.stats,n=i.total;if(r.loaded+=i.loaded,n){var a=Math.round(e.duration/t.duration),s=Math.min(Math.round(r.loaded/n),a),o=(a-s)*Math.round(r.loaded/s);r.total=r.loaded+o}else r.total=Math.max(r.loaded,r.total);var l=r.loading,u=i.loading;l.start?l.first+=u.first-u.start:(l.start=u.start,l.first=u.first),l.end=u.end}},{key:"resetLoader",value:function(e,t){e.loader=null,e.url=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}])}();function Di(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,r=arguments.length>2?arguments[2]:void 0,i=t||e,n={type:ce.MEDIA_FRAGMENT,frag:e,part:t,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},a=_i(e,t,r);return a.resetIV&&(n.resetIV=!0),a.byteRange&&(n.rangeStart=a.byteRange.start,n.rangeEnd=a.byteRange.end),n}function _i(e){var t,r,i=arguments.length>2?arguments[2]:void 0,n={},a=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:null)||e,s=a.byteRangeStartOffset,o=a.byteRangeEndOffset;if(Z(s)&&Z(o))if("initSegment"!==e.sn&&!i||"AES-128"!==(r=null==(t=e.decryptdata)?void 0:t.method)&&"AES-256"!==r)n.byteRange={start:s,end:o};else{var l=16*Math.floor(s/16),u=16*Math.ceil(o/16);n.decryptRange={start:s-l,end:o-l},l>=16&&(n.resetIV=!0,l-=16),n.byteRange={start:l,end:u}}return n}function Mi(e,t){var r=new Error("GAP ".concat(e.gap?"tag":"attribute"," found")),i={type:re.MEDIA_ERROR,details:ie.FRAG_GAP,fatal:!1,frag:e,error:r,networkDetails:null};return t&&(i.part=t),(t||e).stats.aborted=!0,new xi(i)}var xi=function(e){function t(e){var r;return s(this,t),(r=a(this,t,[e.error.message])).data=void 0,r.data=e,r}return f(t,e),l(t)}(w(Error)),Oi=function(e){function t(e,r){var i;return s(this,t),(i=a(this,t,[e,r]))._boundTick=void 0,i._tickTimer=null,i._tickInterval=null,i._tickCallCount=0,i._boundTick=i.tick.bind(i),i}return f(t,e),l(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):(this.log("possible exception thrown in task-loop (".concat(this.constructor.name,".doTick)")),this._tickCallCount=0)}},{key:"tickImmediate",value:function(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}},{key:"doTick",value:function(){}}])}(Be),Fi=l(function e(t,r,i){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:-1,o=arguments.length>5&&void 0!==arguments[5]&&arguments[5],l=arguments.length>6?arguments[6]:void 0,u=arguments.length>7?arguments[7]:void 0,c=arguments.length>8?arguments[8]:void 0;s(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.iframe=void 0,this.duration=void 0,this.decryptRange=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=t,this.sn=r,this.id=i,this.size=n,this.part=a,this.partial=o,this.duration=l||0,this.decryptRange=c,this.iframe=u||!1});var Ni={length:0,start:function(){return 0},end:function(){return 0}},Bi=function(){function e(){s(this,e)}return l(e,null,[{key:"isBuffered",value:function(t,r){if(t)for(var i=e.getBuffered(t),n=i.length;n--;)if(r>=i.start(n)&&r<=i.end(n))return!0;return!1}},{key:"bufferedRanges",value:function(t){if(t){var r=e.getBuffered(t);return e.timeRangesToArray(r)}return[]}},{key:"timeRangesToArray",value:function(e){for(var t=[],r=0;r<e.length;r++)t.push({start:e.start(r),end:e.end(r)});return t}},{key:"bufferInfo",value:function(t,r,i){if(t){var n=e.bufferedRanges(t);if(n.length)return e.bufferedInfo(n,r,i)}return{len:0,start:r,end:r,bufferedIndex:-1}}},{key:"bufferedInfo",value:function(e,t,r){t=Math.max(0,t),e.length>1&&e.sort(function(e,t){return e.start-t.start||t.end-e.end});var i=-1,n=[];if(r)for(var a=0;a<e.length;a++){t>=e[a].start&&t<=e[a].end&&(i=a);var s=n.length;if(s){var o=n[s-1].end;e[a].start-o<r?e[a].end>o&&(n[s-1].end=e[a].end):n.push(e[a])}else n.push(e[a])}else n=e;for(var l,u=0,c=t,d=t,h=0;h<n.length;h++){var f=n[h].start,v=n[h].end;if(-1===i&&t>=f&&t<=v&&(i=h),t+r>=f&&t<v)c=f,u=(d=v)-t;else if(t+r<f){l=f;break}}return{len:u,start:c||0,end:d||0,nextStart:l,buffered:e,bufferedIndex:i}}},{key:"getBuffered",value:function(e){try{return e.buffered||Ni}catch(e){return je.log("failed to get media.buffered",e),Ni}}}])}(),Ui=/\{\$([a-zA-Z0-9-_]+)\}/g;function Vi(e){return Ui.lastIndex=0,Ui.test(e)}function Gi(e,t){if(null!==e.variableList||e.hasVariableRefs){var r=e.variableList;return t.replace(Ui,function(t){var i=t.substring(2,t.length-1),n=null==r?void 0:r[i];return void 0===n?(e.playlistParsingError||(e.playlistParsingError=new Error('Missing preceding EXT-X-DEFINE tag for Variable Reference: "'.concat(i,'"'))),t):n})}return t}function Hi(e,t,r){var i,n,a=e.variableList;if(a||(e.variableList=a={}),"QUERYPARAM"in t){i=t.QUERYPARAM;try{var s=new self.URL(r).searchParams;if(!s.has(i))throw new Error('"'.concat(i,'" does not match any query parameter in URI: "').concat(r,'"'));n=s.get(i)}catch(t){e.playlistParsingError||(e.playlistParsingError=new Error("EXT-X-DEFINE QUERYPARAM: ".concat(t.message)))}}else i=t.NAME,n=t.VALUE;i in a?e.playlistParsingError||(e.playlistParsingError=new Error('EXT-X-DEFINE duplicate Variable Name declarations: "'.concat(i,'"'))):a[i]=n||""}function Ki(e,t,r){var i=t.IMPORT;if(r&&i in r){var n=e.variableList;n||(e.variableList=n={}),n[i]=r[i]}else e.playlistParsingError||(e.playlistParsingError=new Error('EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "'.concat(i,'"')))}var ji=/^(\d+)x(\d+)$/,qi=/(.+?)=(".*?"|.*?)(?:,|$)/g,Wi=function(){return l(function e(t,r){s(this,e),"string"==typeof t&&(t=e.parseAttrList(t,r)),Ae(this,t)},[{key:"clientAttrs",get:function(){return Object.keys(this).filter(function(e){return"X-"===e.substring(0,2)})}},{key:"decimalInteger",value:function(e){var t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}},{key:"hexadecimalInteger",value:function(e){if(this[e]){var t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;for(var r=new Uint8Array(t.length/2),i=0;i<t.length/2;i++)r[i]=parseInt(t.slice(2*i,2*i+2),16);return r}return null}},{key:"hexadecimalIntegerAsNumber",value:function(e){var t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}},{key:"decimalFloatingPoint",value:function(e){return parseFloat(this[e])}},{key:"optionalFloat",value:function(e,t){var r=this[e];return r?parseFloat(r):t}},{key:"enumeratedString",value:function(e){return this[e]}},{key:"enumeratedStringList",value:function(e,t){var r=this[e];return(r?r.split(/[ ,]+/):[]).reduce(function(e,t){return e[t.toLowerCase()]=!0,e},t)}},{key:"bool",value:function(e){return"YES"===this[e]}},{key:"decimalResolution",value:function(e){var t=ji.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}}],[{key:"parseAttrList",value:function(e,t){var r,i={};for(qi.lastIndex=0;null!==(r=qi.exec(e));){var n=r[1].trim(),a=r[2],s=0===a.indexOf('"')&&a.lastIndexOf('"')===a.length-1,o=!1;if(s)a=a.slice(1,-1);else switch(n){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(t&&(s||o))a=Gi(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":je.warn("".concat(e,": attribute ").concat(n," is missing quotes"))}i[n]=a}return i}}])}();function Yi(e){return"ID"!==e&&"CLASS"!==e&&"CUE"!==e&&"START-DATE"!==e&&"DURATION"!==e&&"END-DATE"!==e&&"END-ON-NEXT"!==e}function zi(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e||"SCTE35-CMD"===e}var Xi=function(){return l(function e(t,r){var i,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;if(s(this,e),this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==r?void 0:r.tagAnchor)||null,this.tagOrder=null!=(i=null==r?void 0:r.tagOrder)?i:n,r){var a=r.attr;for(var o in a)if(Object.prototype.hasOwnProperty.call(t,o)&&t[o]!==a[o]){je.warn('DATERANGE tag attribute: "'.concat(o,'" does not match for tags with ID: "').concat(t.ID,'"')),this._badValueForSameId=o;break}t=Ae(new Wi({}),a,t)}if(this.attr=t,r?(this._startDate=r._startDate,this._cue=r._cue,this._endDate=r._endDate,this._dateAtEnd=r._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in t){var l=(null==r?void 0:r.endDate)||new Date(t["END-DATE"]);Z(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?(je.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(Z(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&&Z(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)}},{key:"invalidReason",get:function(){return this.id?this._badValueForSameId?"Date range ".concat(this._badValueForSameId," mismatch"):Z(this.startDate.getTime())?!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr?this.isValid?null:"Unknown (check DURATION(|END|NEXT), CLASS, and CUE)":"Interstitial Date range missing X-ASSET-(LIST|URI)":"Date range invalid start date":"Missing ID"}}])}(),Qi=function(){return l(function e(t){s(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.iframesOnly=!1,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=t},[{key:"reloaded",value:function(e){if(!e)return this.advanced=!0,void(this.updated=!0);var t=this.lastPartSn-e.lastPartSn,r=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!r||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&r>0,this.updated||this.advanced?this.misses=0:this.misses=e.misses+1}},{key:"hasKey",value:function(e){return this.encryptedFragments.some(function(t){var r=t.decryptdata;return r||(t.setKeyFormat(e.keyFormat),r=t.decryptdata),!!r&&e.matches(r)})}},{key:"hasProgramDateTime",get:function(){return!!this.fragments.length&&Z(this.fragments[this.fragments.length-1].programDateTime)}},{key:"levelTargetDuration",get:function(){return this.averagetargetduration||this.targetduration||10}},{key:"drift",get:function(){var e=this.driftEndTime-this.driftStartTime;return e>0?1e3*(this.driftEnd-this.driftStart)/e:1}},{key:"edge",get:function(){return this.partEnd||this.fragmentEnd}},{key:"partEnd",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}},{key:"fragmentEnd",get:function(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}},{key:"fragmentStart",get:function(){return this.fragments.length?this.fragments[0].start:0}},{key:"age",get:function(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}},{key:"lastPartIndex",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}},{key:"maxPartIndex",get:function(){var e=this.partList;if(e){var t=this.lastPartIndex;if(-1!==t){for(var r=e.length;r--;)if(e[r].index>t)return e[r].index;return t}}return 0}},{key:"lastPartSn",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}},{key:"expired",get:function(){if(this.live&&this.age&&this.misses<3){var e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}])}();function $i(e,t){return e.length===t.length&&!e.some(function(e,r){return e!==t[r]})}function Ji(e,t){return!e&&!t||!(!e||!t)&&$i(e,t)}function Zi(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function en(e){switch(e){case"AES-128":case"AES-256":return Ai;case"AES-256-CTR":return bi;default:throw new Error("invalid full segment method ".concat(e))}}function tn(e){return Uint8Array.from(unescape(encodeURIComponent(e)),function(e){return e.charCodeAt(0)})}function rn(e){var t=function(e,t,r){var i=e[t];e[t]=e[r],e[r]=i};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function nn(e){var t,r,i=e.split(":"),n=null;if("data"===i[0]&&2===i.length){var a=i[1].split(";"),s=a[a.length-1].split(",");if(2===s.length){var o="base64"===s[0],l=s[1];o?(a.splice(-1,1),n=gt(l)):(t=tn(l).subarray(0,16),(r=new Uint8Array(16)).set(t,16-t.length),n=r)}}return n}var an="undefined"!=typeof self?self:void 0,sn={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},on="org.w3.clearkey",ln="com.apple.streamingkeydelivery",un="com.microsoft.playready",cn="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function dn(e){switch(e){case ln:return sn.FAIRPLAY;case un:return sn.PLAYREADY;case cn:return sn.WIDEVINE;case on:return sn.CLEARKEY}}var hn="edef8ba979d64acea3c827dcd51d21ed";function fn(e){switch(e){case sn.FAIRPLAY:return ln;case sn.PLAYREADY:return un;case sn.WIDEVINE:return cn;case sn.CLEARKEY:return on}}function vn(e){var t=e.drmSystems,r=e.widevineLicenseUrl,i=t?[sn.FAIRPLAY,sn.WIDEVINE,sn.PLAYREADY,sn.CLEARKEY].filter(function(e){return!!t[e]}):[];return!i[sn.WIDEVINE]&&r&&i.push(sn.WIDEVINE),i}var gn,pn=null!=an&&null!=(gn=an.navigator)&&gn.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function mn(e){var t=pt(new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2)),r=t.substring(t.indexOf("<"),t.length),i=(new DOMParser).parseFromString(r,"text/xml").getElementsByTagName("KID")[0];if(i){var n=i.childNodes[0]?i.childNodes[0].nodeValue:i.getAttribute("VALUE");if(n){var a=gt(n).subarray(0,16);return rn(a),a}}return null}var yn={},kn=function(){function e(t,r,i){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[1],a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null,o=arguments.length>5?arguments[5]:void 0;s(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.scheme=void 0,this.method=t,this.uri=r,this.keyFormat=i,this.keyFormatVersions=n,this.iv=a,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&!Zi(t),null!=o&&o.startsWith("0x")&&(this.keyId=new Uint8Array(vt(o)))}return l(e,[{key:"matches",value:function(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&$i(e.keyFormatVersions,this.keyFormatVersions)&&Ji(e.iv,this.iv)&&Ji(e.keyId,this.keyId)}},{key:"isSupported",value:function(){if(this.method){if(Zi(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case ln:case cn:case un:case on:return-1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}},{key:"getDecryptData",value:function(t,r){var i;if(!this.encrypted||!this.uri)return null;if(Zi(this.method)){var n=this.iv;return n||("number"!=typeof t&&(je.warn('missing IV for initialization segment with method="'.concat(this.method,'" - compliance issue')),t=0),n=function(e){for(var t=new Uint8Array(16),r=12;r<16;r++)t[r]=e>>8*(15-r)&255;return t}(t)),new e(this.method,this.uri,"identity",this.keyFormatVersions,n)}if(this.keyId){var a=yn[this.uri];if(a&&!$i(this.keyId,a)&&e.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}var s,o=nn(this.uri);if(o)switch(this.keyFormat){case cn:if(this.pssh=o,!this.keyId){var l=Xt(o.buffer).filter(function(e){return e.systemId===hn});if(l.length){var u,c=l[0];this.keyId=null!=(u=c.kids)&&u.length?c.kids[0]:null}}this.keyId||(this.keyId=En(r));break;case un:var d=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=zt(d,0,o),this.keyId=mn(o);break;default:var h=o.subarray(0,16);if(16!==h.length){var f=new Uint8Array(16);f.set(h,16-h.length),h=f}this.keyId=h}16!==(null==(i=this.keyId)?void 0:i.byteLength)&&(s=function(e){var t=null==e?void 0:e[cn];if(t)return t.keyId;return null}(r),s||(s=En(r))||(s=yn[this.uri]),s&&(this.keyId=s,e.setKeyIdForUri(this.uri,s)));return this}}],[{key:"clearKeyUriToKeyIdMap",value:function(){yn={}}},{key:"setKeyIdForUri",value:function(e,t){yn[e]=t}},{key:"addKeyIdForUri",value:function(e){var t=Object.keys(yn).length%Number.MAX_SAFE_INTEGER,r=new Uint8Array(16);return new DataView(r.buffer,12,4).setUint32(0,t),yn[e]=r,r}}])}();function En(e){var t=null==e?void 0:e[un];if(t){var r=nn(t.uri);if(r)return mn(r)}return null}var Sn=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(I-FRAME-STREAM-INF|SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)(?:[\r\n]+|$)/g,Tn=/#EXT-X-MEDIA:(.*)/g,An=/^#EXT(?:INF|-X-TARGETDURATION):/m,bn=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),In=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|I-FRAMES-ONLY)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|")),Rn=function(){function e(){s(this,e)}return l(e,null,[{key:"findGroup",value:function(e,t){for(var r=0;r<e.length;r++){var i=e[r];if(i.id===t)return i}}},{key:"resolve",value:function(e,t){return le.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}},{key:"isMediaPlaylist",value:function(e){return An.test(e)}},{key:"parseMasterPlaylist",value:function(t,r){var i,n={contentSteering:null,levels:[],iframeVariants:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:Vi(t)},a=[];if(Sn.lastIndex=0,!t.startsWith("#EXTM3U"))return n.playlistParsingError=new Error("no EXTM3U delimiter"),n;for(;null!=(i=Sn.exec(t));)if(i[1]){var s=Ln(new Wi(i[1],n),i[2],r,n,a);s&&n.levels.push(s)}else if(i[3]){var o=i[3],l=i[4];switch(o){case"I-FRAME-STREAM-INF":var u=new Wi(l,n),c=Ln(u,u.URI,r,n,a,!0);c&&n.iframeVariants.push(c);break;case"SESSION-DATA":var d=new Wi(l,n),h=d["DATA-ID"];h&&(null===n.sessionData&&(n.sessionData={}),n.sessionData[h]=d);break;case"SESSION-KEY":var f=Cn(l,r,n);f.encrypted&&f.isSupported()?(null===n.sessionKeys&&(n.sessionKeys=[]),n.sessionKeys.push(f)):je.warn('[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "'.concat(l,'"'));break;case"DEFINE":Hi(n,new Wi(l,n),r);break;case"CONTENT-STEERING":var v=new Wi(l,n);n.contentSteering={uri:e.resolve(v["SERVER-URI"],r),pathwayId:v["PATHWAY-ID"]||"."};break;case"START":n.startTimeOffset=Dn(l)}}var g=a.length>0&&a.length<n.levels.length;return n.levels=g?a:n.levels,0===n.levels.length&&(n.playlistParsingError=new Error("no levels found in manifest")),n}},{key:"parseMasterPlaylistMedia",value:function(t,r,i){var n,a={},s=i.levels,o={AUDIO:s.map(function(e){return{id:e.attrs.AUDIO,audioCodec:e.audioCodec}}),SUBTITLES:s.map(function(e){return{id:e.attrs.SUBTITLES,textCodec:e.textCodec}}),"CLOSED-CAPTIONS":[]},l=0;for(Tn.lastIndex=0;null!==(n=Tn.exec(t));){var u=new Wi(n[1],i),c=u.TYPE;if(c){var d=o[c],h=a[c]||[];a[c]=h;var f=u.LANGUAGE,v=u["ASSOC-LANGUAGE"],g=u.CHANNELS,p=u.CHARACTERISTICS,m=u["INSTREAM-ID"],y={attrs:u,bitrate:0,id:l++,groupId:u["GROUP-ID"]||"",name:u.NAME||f||"",type:c,default:u.bool("DEFAULT"),autoselect:u.bool("AUTOSELECT"),forced:u.bool("FORCED"),lang:f,url:u.URI?e.resolve(u.URI,r):""};if(v&&(y.assocLang=v),g&&(y.channels=g),p&&(y.characteristics=p),m&&(y.instreamId=m),null!=d&&d.length){var k=e.findGroup(d,y.groupId)||d[0];Mn(y,k,"audioCodec"),Mn(y,k,"textCodec")}h.push(y)}}return a}},{key:"parseLevelPlaylist",value:function(e,t,r,i,n,a){var s,o,l,u,c,d={url:t},h=new Qi(t),f=h.fragments,v=[],g=null,p=0,m=0,y=0,k=0,E=0,S=null,T=new ke(i,d),A=-1,b=!1,I=null;if(bn.lastIndex=0,h.m3u8=e,h.hasVariableRefs=Vi(e),"#EXTM3U"!==(null==(s=bn.exec(e))?void 0:s[0]))return h.playlistParsingError=new Error("Missing format identifier #EXTM3U"),h;for(;null!==(o=bn.exec(e));){b&&(b=!1,(T=new ke(i,d)).playlistOffset=y,T.setStart(y),T.sn=p,T.cc=k,E&&(T.bitrate=E),T.level=r,g&&(T.initSegment=g,g.rawProgramDateTime&&(T.rawProgramDateTime=g.rawProgramDateTime,g.rawProgramDateTime=null),I&&(T.setByteRange(I),I=null)));var R=o[1];if(R){T.duration=parseFloat(R);var L=(" "+o[2]).slice(1);T.title=L||null,T.tagList.push(L?["INF",R,L]:["INF",R])}else if(o[3]){if(Z(T.duration)){var P;T.playlistOffset=y,T.setStart(y),u&&Fn(T,u,h),T.sn=p,T.level=r,T.cc=k;var w=(" "+o[3]).slice(1);T.relurl=Gi(h,w),xn(T,S,v),S=T,y+=T.duration,p++,m=0;var C=T.byteRange;if(2===C.length&&(T.bitrate=8*(C[1]-C[0])/T.duration|0),h.iframesOnly&&C[0]&&(null==(P=g)?void 0:P.cc)!==k){var D=new ke(i,d);D.relurl=T.relurl,D.setByteRange("".concat(Math.min(C[0],1316),"@0")),D.level=r,D.sn="initSegment",u&&(D.levelkeys=u,u.identity&&(D._decryptdata=u.identity.getDecryptData(0))),g=D,T.initSegment=g}f.push(T),b=!0}}else{if(!(o=o[0].match(In))){je.warn("No matches on slow regex match for level playlist!");continue}for(l=1;l<o.length&&void 0===o[l];l++);var _=(" "+o[l]).slice(1),M=(" "+o[l+1]).slice(1),x=o[l+2]?(" "+o[l+2]).slice(1):null;switch(_){case"BYTERANGE":S?T.setByteRange(M,S):T.setByteRange(M);break;case"PROGRAM-DATE-TIME":T.rawProgramDateTime=M,T.tagList.push(["PROGRAM-DATE-TIME",M]),-1===A&&(A=f.length);break;case"PLAYLIST-TYPE":h.type&&Nn(h,_,o),h.type=M.toUpperCase();break;case"MEDIA-SEQUENCE":0!==h.startSN?Nn(h,_,o):null!==S&&Bn(h,_,o),h.startSN=parseInt(M),p=h.startSN+h.skippedSegments;break;case"SKIP":h.skippedSegments&&Nn(h,_,o);var O=new Wi(M,h),F=O.decimalInteger("SKIPPED-SEGMENTS");if(Z(F)){h.skippedSegments+=F;for(var N=F;N--;)f.push(null);p+=F}var B=O.enumeratedString("RECENTLY-REMOVED-DATERANGES");B&&(h.recentlyRemovedDateranges=(h.recentlyRemovedDateranges||[]).concat(B.split("\t")));break;case"TARGETDURATION":0!==h.targetduration&&Nn(h,_,o),h.targetduration=Math.max(parseInt(M),1);break;case"VERSION":null!==h.version&&Nn(h,_,o),h.version=parseInt(M);break;case"INDEPENDENT-SEGMENTS":break;case"I-FRAMES-ONLY":h.iframesOnly=!0;break;case"ENDLIST":h.live||Nn(h,_,o),h.live=!1;break;case"#":(M||x)&&T.tagList.push(x?[M,x]:[M]);break;case"DISCONTINUITY":k++,T.tagList.push(["DIS"]);break;case"GAP":T.gap=!0,T.tagList.push([_]);break;case"BITRATE":T.tagList.push([_,M]),E=1e3*parseInt(M),Z(E)?T.bitrate=E:E=0;break;case"DATERANGE":var U=new Wi(M,h),V=new Xi(U,h.dateRanges[U.ID],h.dateRangeTagCount);h.dateRangeTagCount++,V.isValid||h.skippedSegments?h.dateRanges[V.id]=V:je.log("Ignoring invalid DATERANGE tag: ".concat(V.invalidReason,": ").concat(M)),T.tagList.push(["EXT-X-DATERANGE",M]);break;case"DEFINE":var G=new Wi(M,h);"IMPORT"in G?Ki(h,G,a):Hi(h,G,t);break;case"DISCONTINUITY-SEQUENCE":0!==h.startCC&&Nn(h,_,o),h.startCC=k=parseInt(M),f.forEach(function(e){return e&&(e.cc=k)});break;case"KEY":var H=Cn(M,t,h);if(H.isSupported()){if("NONE"===H.method){u=void 0;break}u||(u={});var K=u[H.keyFormat];null!=K&&K.matches(H)||(K&&(u=Ae({},u)),u[H.keyFormat]=H)}else je.warn('[Keys] Ignoring unsupported EXT-X-KEY tag: "'.concat(M,'"'));break;case"START":h.startTimeOffset=Dn(M);break;case"MAP":var j=new Wi(M,h);if(T.duration){var q=new ke(i,d);On(q,j,r,u),g=q,T.initSegment=g,g.rawProgramDateTime&&!T.rawProgramDateTime&&(T.rawProgramDateTime=g.rawProgramDateTime)}else{var W=T.byteRangeEndOffset;if(W){var Y=T.byteRangeStartOffset;I="".concat(W-Y,"@").concat(Y)}else I=null;On(T,j,r,u),g=T,b=!0}g.cc=k;break;case"SERVER-CONTROL":c&&Nn(h,_,o),c=new Wi(M),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&&Nn(h,_,o);var z=new Wi(M);h.partTarget=z.decimalFloatingPoint("PART-TARGET");break;case"PART":var X=h.partList;X||(X=h.partList=[]);var Q=m>0?X[X.length-1]:void 0,$=m++,J=new Wi(M,h),ee=new Ee(J,T,d,$,Q);X.push(ee),T.duration+=ee.duration;break;case"PRELOAD-HINT":var te=new Wi(M,h);h.preloadHint=te;break;case"RENDITION-REPORT":var re=new Wi(M,h);h.renditionReports=h.renditionReports||[],h.renditionReports.push(re);break;default:je.warn("line parsed but not handled: ".concat(o))}}}S&&!S.relurl?(f.pop(),y-=S.duration,h.partList&&(h.fragmentHint=S)):h.partList&&(xn(T,S,v),T.cc=k,h.fragmentHint=T,u&&Fn(T,u,h)),h.targetduration||(h.playlistParsingError=new Error("Missing Target Duration"));var ie=f.length,ne=f[0],ae=f[ie-1];if((y+=h.skippedSegments*h.targetduration)>0&&ie&&ae){h.averagetargetduration=y/ie;var se=ae.sn;h.endSN="initSegment"!==se?se:0,h.live||(ae.endList=!0),A>0&&(!function(e,t,r){if(r||(r=e[t]),!r)return;for(var i=t;i--;){var n=e[i];if(!n)return;n.programDateTime=r.programDateTime-1e3*n.duration,r=n}}(f,A,A>ie-1?T:null),ne&&v.unshift(ne))}return h.fragmentHint&&(y+=h.fragmentHint.duration),h.totalduration=y,v.length&&h.dateRangeTagCount&&ne&&Pn(v,h),h.endCC=k,h}}])}();function Ln(e,t,r,i,n,a){var s;if(void 0===t)return null;var o=Gi(i,t),l={attrs:e,bitrate:e.decimalInteger("BANDWIDTH")||e.decimalInteger("AVERAGE-BANDWIDTH"),name:e.NAME,url:Rn.resolve(o,r)},u=e.decimalResolution("RESOLUTION");u&&(l.width=u.width,l.height=u.height),_n(e.CODECS,l);var c=e["SUPPLEMENTAL-CODECS"];return c&&(l.supplemental={},_n(c,l.supplemental)),null!=(s=l.unknownCodecs)&&s.length||n.push(l),a&&(l.iframes=!0),l}function Pn(e,t){var r=e.length;if(!r){if(!t.hasProgramDateTime)return;var i=t.fragments[t.fragments.length-1];e.push(i),r++}for(var n=e[r-1],a=t.live?1/0:t.totalduration,s=Object.keys(t.dateRanges),o=s.length;o--;){var l=t.dateRanges[s[o]],u=l.startDate.getTime();l.tagAnchor=n.ref;for(var c=r;c--;){var d;if((null==(d=e[c])?void 0:d.sn)<t.startSN)break;var h=wn(t,u,e,c,a);if(h){l.tagAnchor=h.ref;break}}}}function wn(e,t,r,i,n){var a=r[i];if(a){var s,o=a.programDateTime;if(t>=o||0===i)if(t<=o+1e3*(((null==(s=r[i+1])?void 0:s.start)||n)-a.start)){var l=a.sn-e.startSN,u=e.fragments;if(l>=0&&l<u.length){if(u.length>r.length)for(var c=r[i+1]||u[u.length-1],d=Math.min(c.sn-e.startSN,u.length-1);d>l;d--){var h=u[d].programDateTime;if(t>=h&&t<h+1e3*u[d].duration)return u[d]}return u[l]}}}return null}function Cn(e,t,r){var i,n,a=new Wi(e,r),s=null!=(i=a.METHOD)?i:"",o=a.URI,l=a.hexadecimalInteger("IV"),u=a.KEYFORMATVERSIONS,c=null!=(n=a.KEYFORMAT)?n:"identity";o&&a.IV&&!l&&je.error("Invalid IV: ".concat(a.IV));var d=o?Rn.resolve(o,t):"",h=(u||"1").split("/").map(Number).filter(Number.isFinite);return new kn(s,d,c,h,l,a.KEYID)}function Dn(e){var t=new Wi(e).decimalFloatingPoint("TIME-OFFSET");return Z(t)?t:null}function _n(e,t){var r=(e||"").split(/[ ,]+/).filter(function(e){return e});["video","audio","text","image"].forEach(function(e){var i=r.filter(function(t){return sr(t,e)});i.length&&(t["".concat(e,"Codec")]=i.map(function(e){return e.split("/")[0]}).join(","),r=r.filter(function(e){return-1===i.indexOf(e)}))}),t.unknownCodecs=r}function Mn(e,t,r){var i=t[r];i&&(e[r]=i)}function xn(e,t,r){e.rawProgramDateTime?r.push(e):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function On(e,t,r,i){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=r,e.sn="initSegment",i&&(e.levelkeys=i),e.initSegment=null}function Fn(e,t,r){e.levelkeys=t;var i=r.encryptedFragments;i.length&&i[i.length-1].levelkeys===t||!Object.keys(t).some(function(e){return t[e].isCommonEncryption})||i.push(e)}function Nn(e,t,r){e.playlistParsingError=new Error("#EXT-X-".concat(t," must not appear more than once (").concat(r[0],")"))}function Bn(e,t,r){e.playlistParsingError=new Error("#EXT-X-".concat(t," must appear before the first Media Segment (").concat(r[0],")"))}function Un(e,t){var r=t.startPTS;if(Z(r)){var i,n=0;t.sn>e.sn?(n=r-e.start,i=e):(n=e.start-r,i=t),i.duration!==n&&i.setDuration(n)}else if(t.sn>e.sn){e.cc===t.cc&&e.minEndPTS?t.setStart(e.start+(e.minEndPTS-e.start)):t.setStart(e.start+e.duration)}else t.setStart(Math.max(e.start-t.duration,0))}function Vn(e,t,r,i,n,a,s,o){i-r<=0&&(o.warn("Fragment should have a positive duration",t),i=r+t.duration,a=n+t.duration);var l=r,u=i,c=t.startPTS,d=t.endPTS;if(Z(c)){var h=Math.abs(c-r);e&&h>e.totalduration?o.warn("media timestamps and playlist times differ by ".concat(h,"s for level ").concat(t.level," ").concat(e.url)):Z(t.deltaPTS)?t.deltaPTS=Math.max(h,t.deltaPTS):t.deltaPTS=h,l=Math.max(r,c),r=Math.min(r,c),n=void 0!==t.startDTS?Math.min(n,t.startDTS):n,u=Math.min(i,d),i=Math.max(i,d),a=void 0!==t.endDTS?Math.max(a,t.endDTS):a}var f=r-t.start;0!==t.start&&t.setStart(r),t.setDuration(i-t.start),t.startPTS=r,t.maxStartPTS=l,t.startDTS=n,t.endPTS=i,t.minEndPTS=u,t.endDTS=a;var v,g=t.sn;if(!e||g<e.startSN||g>e.endSN)return 0;var p=g-e.startSN,m=e.fragments;for(m[p]=t,v=p;v>0;v--)Un(m[v],m[v-1]);for(v=p;v<m.length-1;v++)Un(m[v],m[v+1]);return e.fragmentHint&&Un(m[m.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,f}function Gn(e,t,r){if(e!==t){for(var i,n=null,a=e.fragments,s=a.length-1;s>=0;s--){var o=a[s].initSegment;if(o){n=o;break}}e.fragmentHint&&delete e.fragmentHint.endPTS,function(e,t,r){for(var i,n=t.skippedSegments,a=Math.max(e.startSN,t.startSN)-t.startSN,s=(e.fragmentHint?1:0)+(n?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,o=t.startSN-e.startSN,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,u=null!=(i=e.fragmentHint)&&i.duration?e.fragments.concat(e.fragmentHint):e.fragments,c=a;c<=s;c++){var d=u[o+c],h=l[c];if(n&&!h&&d&&(h=t.fragments[c]=d),d&&h){r(d,h,c,l);var f=d.relurl,v=h.relurl;if(f&&Xn(f,v))return void(t.playlistParsingError=Hn("media sequence mismatch ".concat(h.sn,":"),e,t,d,h));if(d.cc!==h.cc)return void(t.playlistParsingError=Hn("discontinuity sequence mismatch (".concat(d.cc,"!=").concat(h.cc,")"),e,t,d,h))}}}(e,t,function(e,r,a,s){if((!t.startCC||t.skippedSegments)&&r.cc!==e.cc){for(var o=e.cc-r.cc,l=a;l<s.length;l++)s[l].cc+=o;t.endCC=s[s.length-1].cc}Z(e.startPTS)&&Z(e.endPTS)&&(r.setStart(r.startPTS=e.startPTS),r.startDTS=e.startDTS,r.maxStartPTS=e.maxStartPTS,r.endPTS=e.endPTS,r.endDTS=e.endDTS,r.minEndPTS=e.minEndPTS,r.setDuration(e.endPTS-e.startPTS),r.duration&&(i=r),t.PTSKnown=t.alignedSliding=!0),e.hasStreams&&(r.elementaryStreams=e.elementaryStreams),r.loader=e.loader,e.hasStats&&(r.stats=e.stats),e.initSegment&&(r.initSegment=e.initSegment,n=e.initSegment)});var l=t.fragments,u=t.fragmentHint?l.concat(t.fragmentHint):l;if(n&&u.forEach(function(e){var t;!e||e.initSegment&&e.initSegment.relurl!==(null==(t=n)?void 0:t.relurl)||(e.initSegment=n)}),t.skippedSegments){if(t.deltaUpdateFailed=l.some(function(e){return!e}),t.deltaUpdateFailed){r.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(var c=t.skippedSegments;c--;)l.shift();t.startSN=l[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=function(e,t,r){var i=t.dateRanges,n=t.recentlyRemovedDateranges,a=Ae({},e);n&&n.forEach(function(e){delete a[e]});var s=Object.keys(a).length;if(!s)return i;return Object.keys(i).forEach(function(e){var t=a[e],n=new Xi(i[e].attr,t);n.isValid?(a[e]=n,t||(n.tagOrder+=s)):r.warn('Ignoring invalid Playlist Delta Update DATERANGE tag: "'.concat(Nr(i[e].attr),'"'))}),a}(e.dateRanges,t,r));var d=e.fragments.filter(function(e){return e.rawProgramDateTime});if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(var h=1;h<u.length;h++)null===u[h].programDateTime&&xn(u[h],u[h-1],d);Pn(d,t)}t.endCC=l[l.length-1].cc}if(!t.startCC){var f,v=qn(e,t.startSN-1);t.startCC=null!=(f=null==v?void 0:v.cc)?f:l[0].cc}if(function(e,t,r){if(e&&t)for(var i=0,n=0,a=e.length;n<a;n++){var s=e[n],o=t[n+i];s&&o&&s.index===o.index&&s.fragment.sn===o.fragment.sn?r(s,o):i--}}(e.partList,t.partList,function(e,t){t.elementaryStreams=e.elementaryStreams,t.stats=e.stats,t.gap=e.gap||t.gap}),i){t.iframesOnly&&(i.type,de.MAIN);Vn(t,i,i.startPTS,i.endPTS,i.startDTS,i.endDTS,0,r)}else Kn(e,t);l.length&&(t.totalduration=t.edge-l[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;var g=t.advancedDateTime;if(t.advanced&&g){var p=t.edge;t.driftStart||(t.driftStartTime=g,t.driftStart=p),t.driftEndTime=g,t.driftEnd=p}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;-1===t.requestScheduled&&(t.requestScheduled=e.requestScheduled)}}function Hn(e,t,r,i,n){return new Error("".concat(e," ").concat(n.url,"\nPlaylist starting @").concat(t.startSN,"\n").concat(t.m3u8,"\n\nPlaylist starting @").concat(r.startSN,"\n").concat(r.m3u8))}function Kn(e,t){var r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],i=arguments.length>3?arguments[3]:void 0,n=t.startSN+t.skippedSegments-e.startSN,a=e.fragments,s=n>=0,o=0;if(s&&n<a.length)o=a[n].start,null==i||i.log("Aligning playlists based on SN ".concat(t.startSN," (diff: ").concat(o,")"));else if(s&&t.startSN===e.endSN+1)o=e.fragmentEnd,null==i||i.log("Aligning playlists based on first/last SN ".concat(t.startSN," (diff: ").concat(o,")"));else if(s&&r)o=e.fragmentStart+n*t.levelTargetDuration;else{if(t.skippedSegments||0!==t.fragmentStart)return o;o=e.fragmentStart,null==i||i.log("Aligning playlists based on first SN ".concat(t.startSN," (diff: ").concat(o,")"))}return function(e,t){if(t){for(var r=e.fragments,i=e.skippedSegments;i<r.length;i++)r[i].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}(t,o),o}function jn(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1/0,r=1e3*e.targetduration;if(e.updated){var i=e.fragments;if(i.length&&4*r>t){var n=1e3*i[i.length-1].duration;n>0&&n<r&&(r=n)}}else r/=2;return Math.round(r)}function qn(e,t,r){var i;if(!e)return null;var n=e.fragments[t-e.startSN];return n||((null==(i=n=e.fragmentHint)?void 0:i.sn)===t?n:r&&t<e.startSN&&r.sn===t?r:null)}function Wn(e,t,r){return e?Yn(e.partList,t,r):null}function Yn(e,t,r){if(e)for(var i=e.length;i--;){var n=e[i];if(n.index===r&&n.fragment.sn===t)return n}return null}function zn(e){e.forEach(function(e,t){var r;null==(r=e.details)||r.fragments.forEach(function(e){e.level=t,e.initSegment&&(e.initSegment.level=t)})})}function Xn(e,t){return!(e===t||!t)&&Qn(e)!==Qn(t)}function Qn(e){return e.replace(/\?[^?]*$/,"")}function $n(e,t){for(var r=0,i=e.length;r<i;r++){var n;if((null==(n=e[r])?void 0:n.cc)===t)return e[r]}return null}function Jn(e,t){var r=e.start+t;e.setStart(r)}function Zn(e,t){for(var r=t.fragments,i=0,n=r.length;i<n;i++)Jn(r[i],e);t.fragmentHint&&Jn(t.fragmentHint,e),t.alignedSliding=!0}function ea(e,t,r){e&&(!function(e,t,r){if(!function(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}(t,e))return;var i=Math.min(t.endCC,e.endCC),n=$n(t.fragments,i),a=$n(e.fragments,i);if(!n||!a)return;var s=n.start-a.start;r.log("Aligning playlists using dicontinuity sequence ".concat(i," (diff: ").concat(s,")")),Zn(s,e)}(t,e,r),t.alignedSliding||function(e,t,r){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;var i,n,a=e.fragments,s=t.fragments;if(!a.length||!s.length)return;var o=Math.min(t.endCC,e.endCC);t.startCC<o&&e.startCC<o&&(i=$n(s,o),n=$n(a,o));i&&n||(n=$n(a,(i=s[Math.floor(s.length/2)]||s.filter(function(e){return!!e})[0]).cc)||a[Math.floor(a.length/2)]);var l=i.programDateTime,u=n.programDateTime;if(!l||!u)return;var c=(u-l)/1e3;if(Math.abs(c)>Math.max(60,e.totalduration))return void r.log("Cannot align playlists using PDT without overlap (".concat(Math.abs(c)," > ").concat(e.totalduration,")"));var d=c-(n.start-i.start);r.log("Aligning playlists using PDT (diff: ".concat(d,")")),Zn(d,e)}(t,e,r),t.alignedSliding||t.skippedSegments||Kn(e,t,!1,r))}function ta(e,t,r){ra(e,t,r),e.addEventListener(t,r)}function ra(e,t,r){e.removeEventListener(t,r)}function ia(e){for(var t="",r=e.length,i=0;i<r;i++)t+="[".concat(e.start(i).toFixed(3),"-").concat(e.end(i).toFixed(3),"]");return t}var na="STOPPED",aa="IDLE",sa="KEY_LOADING",oa="FRAG_LOADING",la="FRAG_LOADING_WAITING_RETRY",ua="WAITING_TRACK",ca="PARSING",da="PARSED",ha="ENDED",fa="ERROR",va="WAITING_INIT_PTS",ga="WAITING_LEVEL",pa=function(e){function t(e,r,i,n,o){var l;return s(this,t),(l=a(this,t,[n,e.logger])).hls=void 0,l.fragPrevious=null,l.fragCurrent=null,l.fragPlaying=null,l.fragmentTracker=void 0,l.transmuxer=null,l._state=na,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=-1,l.startTimeOffset=null,l.retryDate=0,l.levels=null,l.fragmentLoader=void 0,l.initFragmentLoader=void 0,l.keyLoader=void 0,l.levelLastLoaded=null,l.startFragRequested=!1,l.decrypter=void 0,l.initPTS=[],l.buffering=!0,l.loadingParts=!1,l.loopSn=void 0,l.onMediaSeeking=function(){var e=l,t=e.config,r=e.fragCurrent,i=e.media,n=e.mediaBuffer,a=e.state,s=i?i.currentTime:0,o=Bi.bufferInfo(n||i,s,t.maxBufferHole),u=o.len;if(l.log("Media seeking to ".concat(s,", state: ").concat(a,", ").concat(u?"in":"out of"," buffer")),l.state===ha)l.resetLoadingState();else if(r){var c=t.maxFragLookUpTolerance,d=r.start-c,h=r.start+r.duration+c;if(!u||h<o.start||d>o.end){var f=s<d,v=s>h;(f||v)&&(!r.loader||!v&&l.isFragmentNearlyDownloaded(r)?l.fragPrevious=null:(l.log("Cancelling fragment load for seek (sn: ".concat(r.sn,") - ").concat(f?"backward":"forward"," seek")),r.abortRequests(),l.resetLoadingState()))}}if(i&&(l.fragmentTracker.removeFragmentsInRange(s,1/0,l.playlistType,!0),s>l.lastCurrentTime&&(l.lastCurrentTime=s),!l.loadingParts)){var g=Math.max(o.end,s),p=l.shouldLoadParts(l.getLevelDetails(),g);p&&(l.log("LL-Part loading ON after seeking to ".concat(s," with buffer @").concat(g)),l.loadingParts=p)}var m=!Bi.isBuffered(i,s);l.hls.hasEnoughToStart&&!m||(l.log("Setting ".concat(m?"startPosition":"nextLoadPosition"," to ").concat(s," for seek without enough to start")),l.nextLoadPosition=s,m&&(l.startPosition=s)),u<1&&l.state===aa&&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 Ci(e.config),l.initFragmentLoader=new Ci(e.config),l.keyLoader=i,l.fragmentTracker=r,l.config=e.config,l.decrypter=new Pi(e.config),l}return f(t,e),l(t,[{key:"registerListeners",value:function(){var e=this.hls;e.on(ne.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ne.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ne.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(ne.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(ne.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ne.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ne.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(ne.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!==na){this.fragmentLoader.abort(),this.initFragmentLoader.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=na}}},{key:"startPositionValue",get:function(){var e=this.nextLoadPosition,t=this.startPosition;if(-1===t&&e){var r=this.getLevelDetails();return null!=r&&r.live?(this.hls.liveSyncPosition||r.fragmentStart)+this.timelineOffset:e}return t}},{key:"bufferingEnabled",get:function(){return this.buffering}},{key:"backtrackFragment",get:function(){},set:function(e){}},{key:"couldBacktrack",get:function(){return!1},set:function(e){}},{key:"pauseBuffering",value:function(){this.buffering=!1}},{key:"resumeBuffering",value:function(){this.buffering=!0}},{key:"inFlightFrag",get:function(){return{frag:this.fragCurrent,state:this.state}}},{key:"_streamEnded",value:function(e,t){if(t.live||!this.media)return!1;var r=e.end||0,i=this.config.timelineOffset||0;if(r<=i)return!1;var n=e.buffered;this.config.maxBufferHole&&n&&n.length>1&&(e=Bi.bufferedInfo(n,e.start,0));var a=e.nextStart;if(a&&a>i&&a<t.edge)return!1;if(this.media.currentTime<e.start)return!1;var s=t.partList;if(null!=s&&s.length){var o=s[s.length-1];return Bi.isBuffered(this.media,o.start+o.duration/2)}var l=t.fragments[t.fragments.length-1];return this.fragmentTracker.isEndListAppended(l.type)}},{key:"getLevelDetails",value:function(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}},{key:"timelineOffset",get:function(){var e,t=this.config.timelineOffset;return t?(null==(e=this.getLevelDetails())?void 0:e.appliedTimelineOffset)||t:0}},{key:"onMediaAttached",value:function(e,t){var r=this.media=this.mediaBuffer=t.media;ta(r,"seeking",this.onMediaSeeking),ta(r,"ended",this.onMediaEnded);var i=this.config;this.levels&&i.autoStartLoad&&this.state===na&&this.startLoad(i.startPosition)}},{key:"onMediaDetaching",value:function(e,t){this.fragPlaying=null;var r=!!t.transferMedia,i=this.media;if(null!==i){if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),ra(i,"seeking",this.onMediaSeeking),ra(i,"ended",this.onMediaEnded),this.media=this.mediaBuffer=null,this.loopSn=void 0,r)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}},{key:"onManifestLoading",value:function(){this.initPTS=[],this.fragPlaying=this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=0,this.startPosition=-1,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),A(t,"onHandlerDestroying",this,3)([]),this.hls=this.onMediaSeeking=this.onMediaEnded=null}},{key:"onHandlerDestroyed",value:function(){this.state=na,this.fragmentLoader&&this.fragmentLoader.destroy(),this.initFragmentLoader&&this.initFragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.decrypter=this.keyLoader=null,this.fragmentLoader=this.initFragmentLoader=this.fragmentTracker=null,A(t,"onHandlerDestroyed",this,3)([])}},{key:"loadFragment",value:function(e,t,r){this.startFragRequested=!0,this._loadFragForPlayback(e,t,r)}},{key:"_loadFragForPlayback",value:function(e,t,r){var i=this;this._doFragLoad(e,t,r,function(e){var t=e.frag;if(i.fragContextChanged(t))return i.warn("".concat(t.type," sn: ").concat(t.sn).concat(e.part?" part: "+e.part.index:""," of ").concat(i.fragInfo(t,!1,e.part)," was dropped during download.")),void i.fragmentTracker.removeFragment(t);var r=++t.stats.chunkCount;i.log("load progress ".concat(t.type," sn: ").concat(t.sn).concat(e.part?" part: "+e.part.index:""," of ").concat(i.fragInfo(t,!1,e.part)," chunk: ").concat(r)),i._handleFragmentLoadProgress(e)}).then(function(e){if(e){var t=i.state,r=e.frag;i.fragContextChanged(r)?(t===oa||!i.fragCurrent&&t===ca)&&(i.fragmentTracker.removeFragment(r),i.state=aa):("payload"in e&&(i.log("Loaded ".concat(r.type," sn: ").concat(r.sn," of ").concat(i.playlistLabel()," ").concat(r.level," (bytes ").concat(r.stats.loaded,")")),i.hls.trigger(ne.FRAG_LOADED,e)),i._handleFragmentLoadComplete(e))}}).catch(function(t){i.state!==na&&i.state!==fa&&(i.log("Frag error ".concat(e.type," sn:").concat(e.sn," cc:").concat(e.cc,": ").concat((null==t?void 0:t.message)||t)),i.resetFragmentLoading(e))})}},{key:"clearTrackerIfNeeded",value:function(e){var t,r=this.fragmentTracker;if(r.getState(e)===pi){var i=e.type,n=this.getFwdBufferInfo(this.mediaBuffer,i),a=Math.max(e.duration,n?n.len:this.config.maxBufferLength),s=this.backtrackFragment;(1===(s?e.sn-s.sn:0)||this.reduceMaxBufferLength(a,e.duration))&&r.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?r.removeAllFragments():r.hasParts(e.type)&&(r.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),r.getState(e)===mi&&r.removeFragment(e))}},{key:"checkLiveUpdate",value:function(e){if(e.updated&&!e.live){var t=this.fragmentTracker,r=e.fragments[e.fragments.length-1];if(r.endList&&!t.isEndListAppended(this.playlistType)){var i=t.getPartialFragment(r.end);i&&(t.removeFragment(i),t.fragBuffered(r,!0))}t.detectPartialFragments({frag:r,part:null,stats:r.stats,id:r.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}},{key:"waitForLive",value:function(e){var t=e.details;return(null==t?void 0:t.live)&&"EVENT"!==t.type&&(this.levelLastLoaded!==e||t.expired)}},{key:"flushMainBuffer",value:function(e,t){if(e-t){var r={startOffset:e,endOffset:t,type:arguments.length>2&&void 0!==arguments[2]?arguments[2]:null};this.hls.trigger(ne.BUFFER_FLUSHING,r)}}},{key:"_loadInitSegment",value:function(e){var t=this,r=this.hls;return this.initFragmentLoader.abort(),r.trigger(ne.FRAG_LOADING,{frag:e,targetBufferTime:0}),this.initFragmentLoader.load(e).then(function(e){var r,i=e.frag;if(!t.levels||!ye(i,null==(r=t.fragCurrent)?void 0:r.initSegment))throw new xi({type:re.NETWORK_ERROR,details:ie.INTERNAL_ABORTED,error:new Error("init load aborted"),fatal:!1,frag:i,networkDetails:null});return e}).then(function(e){var i=e.frag,n=e.payload,a=i.decryptdata;if(n&&n.byteLength>0&&null!=a&&a.key&&a.iv&&Zi(a.method)){var s=self.performance.now(),o=_i(i,null,t.iframesOnly).decryptRange;return t.decrypter.decrypt(new Uint8Array(n),a.key.buffer,a.iv.buffer,en(a.method),o).catch(function(e){throw r.trigger(ne.ERROR,{type:re.MEDIA_ERROR,details:ie.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:i}),t.fragmentLoader.abort(),e}).then(function(n){var a=self.performance.now();return r.trigger(ne.FRAG_DECRYPTED,{frag:i,part:null,payload:n,stats:{tstart:s,tdecrypt:a}}),e.payload=n,t.completeInitSegmentLoad(e)})}return t.completeInitSegmentLoad(e)})}},{key:"completeInitSegmentLoad",value:function(e){var t=e.frag.stats;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()}},{key:"loadInitSegmentIfNeeded",value:function(e){var t,r=this,i=e.initSegment;if(!this.bitrateTest&&pe(e)&&i&&!i.data)return(!i.encrypted||null!=(t=i.decryptdata)&&t.key?this._loadInitSegment(i):this.keyLoader.load(i).then(function(){return r._loadInitSegment(i)})).catch(function(t){if(r.state===na||r.state===fa)throw t;throw"data"in t&&(t.data.frag=e,r.fragmentLoader.abort(),r.handleFragLoadError(t)),r.resetFragmentLoading(e),t})}},{key:"unhandledEncryptionError",value:function(e,t){var r,i,n=e.tracks;if(n&&!t.encrypted&&(null!=(r=n.audio)&&r.encrypted||null!=(i=n.video)&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){var a=this.media,s=new Error("Encrypted track with no key in ".concat(this.fragInfo(t)," (media ").concat(a?"attached mediaKeys: "+a.mediaKeys:"detached",")"));return this.warn(s.message),!a||a.mediaKeys?!1:(this.hls.trigger(ne.ERROR,{type:re.KEY_SYSTEM_ERROR,details:ie.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||!ye(e,t)}},{key:"fragBufferedComplete",value:function(e,t){var r=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log("Buffered ".concat(e.type," sn: ").concat(e.sn).concat(t?" part: "+t.index:""," of ").concat(this.fragInfo(e,!1,t)," > buffer:").concat(r?ia(Bi.getBuffered(r)):"(detached)",")")),pe(e)){var i;if(e.type!==de.SUBTITLE){var n=e.elementaryStreams;if(!Object.keys(n).some(function(e){return!!n[e]}))return void(this.state=aa)}var a=null==(i=this.levels)?void 0:i[e.level];null!=a&&a.fragmentError&&(t||this.fragmentTracker.getState(e)!==mi)&&(this.log("Resetting level fragment error count of ".concat(a.fragmentError," on frag buffered")),a.fragmentError=0,e.stats.retry=0)}this.state=aa}},{key:"_handleFragmentLoadComplete",value:function(e){var t=this.transmuxer;if(t){var r=e.frag,i=e.part,n=e.partsLoaded,a=!n||0===n.length||n.some(function(e){return!e}),s=_i(r,i).decryptRange,o=new Fi(r.level,r.sn,r.stats.chunkCount+1,0,i?i.index:-1,!a,r.duration,this.iframesOnly,s);this.log("load complete ".concat(r.type," sn: ").concat(r.sn).concat(i?" part: "+i.index:""," of ").concat(this.fragInfo(r,!1,i))),t.flush(o)}}},{key:"_handleFragmentLoadProgress",value:function(e){}},{key:"loadKeyFor",value:function(e,t,r){var i,n=this,a=null;return!e.encrypted||null!=(i=e.decryptdata)&&i.key?e.encrypted||(a=this.keyLoader.loadClear(e,t.encryptedFragments,this.startFragRequested))&&this.log("[eme] blocking frag sn: ".concat(e.sn," load until media-keys acquired")):(this.log("Loading key for ".concat(e.sn," of [").concat(t.startSN,"-").concat(t.endSN,"], ").concat(this.playlistLabel()," ").concat(e.level)),this.state=sa,a=this.keyLoader.load(e,r).then(function(e){if(!n.fragContextChanged(e.frag))return n.hls.trigger(ne.KEY_LOADED,e),n.state===sa&&(n.state=aa),e}),this.hls.trigger(ne.KEY_LOADING,{frag:e})),a}},{key:"_doFragLoad",value:function(e,t){var r=this,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,n=arguments.length>3?arguments[3]:void 0;this.fragCurrent=e;var a=t.details;if(!this.levels||!a)throw new Error("frag load aborted, missing level".concat(a?"":" detail","s"));var s,o=this.fragPrevious;if(!me(e,o)){var l=this.shouldLoadParts(t.details,e.end);l!==this.loadingParts&&(this.log("LL-Part loading ".concat(l?"ON":"OFF"," loading sn ").concat(null==o?void 0:o.sn,"->").concat(e.sn)),this.loadingParts=l)}if(i=Math.max(e.start,i||0),this.loadingParts){var u=a.partList;if(u&&n){i>a.fragmentEnd&&a.fragmentHint&&(e=a.fragmentHint);var c=this.getNextPart(u,e,i);if(c>-1){var d=u[c];if(!me(e=this.fragCurrent=d.fragment,o)&&!this.shouldLoadParts(t.details,e.end))return this.log("LL-Part loading OFF @".concat(this.playhead," next part: ").concat(this.fragInfo(e,!1,d))),this.loadingParts=!1,Promise.resolve(null);if(!this.filterReplacedPrimary(d,t.details))return Promise.resolve(null);var h,f=this.loadKeyFor(e,a);if(this.fragContextChanged(e))return Promise.resolve(null);this.log("Loading ".concat(e.type," sn: ").concat(e.sn," part: ").concat(d.index," (").concat(c,"/").concat(u.length-1,") of ").concat(this.fragInfo(e,!1,d)," cc: ").concat(e.cc," [").concat(a.startSN,"-").concat(a.endSN,"], target: ").concat(i).concat(d.byteRange.length?" range:".concat(d.byteRange.join("-")):"")),this.nextLoadPosition=d.start+d.duration,this.state=oa;var v=this.loadInitSegmentIfNeeded(e);if(f||v){var g=!!f;h=Promise.all([f,v]).then(function(i){var a=S(i,1)[0];return!g||a&&!r.fragContextChanged(a.frag)?r.doFragPartsLoad(e,d,t,n):null}).catch(function(e){return r.handleFragLoadError(e)})}else h=this.doFragPartsLoad(e,d,t,n).catch(function(e){return r.handleFragLoadError(e)});return this.hls.trigger(ne.FRAG_LOADING,{frag:e,part:d,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):h}if(!e.url||this.loadedEndOfParts(u,i))return Promise.resolve(null)}}if(this.loadingParts)this.log("LL-Part loading OFF after next part miss @".concat(i," Check buffer at sn: ").concat(e.sn," loaded parts: ").concat(null==(s=a.partList)?void 0:s.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);if(!this.filterReplacedPrimary(e,t.details))return Promise.resolve(null);var p,m=this.loadInitSegmentIfNeeded(e),y=this.loadKeyFor(e,a,m);if(this.fragContextChanged(e))return this.log("Context changed in KEY_LOADING sn: ".concat(e.sn," ").concat(e.relurl," > ").concat(null==(p=this.fragCurrent)?void 0:p.relurl)),null==m||m.catch(function(){return null}),null==y||y.catch(function(){return null}),Promise.resolve(null);this.log("Loading ".concat(e.type," sn: ").concat(e.sn," of ").concat(this.fragInfo(e,!1)," cc: ").concat(e.cc," ").concat("["+a.startSN+"-"+a.endSN+"]",", target: ").concat(i).concat(e.byteRange.length?" range:".concat(e.byteRange.join("-")):"")),Z(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=oa;var k,E=this.config.progressive&&e.type!==de.SUBTITLE;return k=E&&y?y.then(function(t){return!t||r.fragContextChanged(t.frag)?null:r.fragmentLoader.load(e,r.iframesOnly,n,m)}).catch(function(e){return r.handleFragLoadError(e)}):Promise.all([this.fragmentLoader.load(e,this.iframesOnly,E?n:void 0,E?m:void 0),y,m]).then(function(e){var t=S(e,1)[0];return!E&&n&&n(t),t}).catch(function(e){return r.handleFragLoadError(e)}),this.hls.trigger(ne.FRAG_LOADING,{frag:e,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):Promise.all([k,m]).then(function(e){return S(e,1)[0]})}},{key:"doFragPartsLoad",value:function(e,t,r,i){var n=this;return new Promise(function(a,s){var o,l=[],u=null==(o=r.details)?void 0:o.partList,c=function(t){n.fragmentLoader.loadPart(e,t,i).then(function(i){l[t.index]=i;var s=i.part;n.hls.trigger(ne.FRAG_LOADED,i);var o=Wn(r.details,e.sn,t.index+1)||Yn(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===ie.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===re.KEY_SYSTEM_ERROR&&!t.fatal&&(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)),this.hls.trigger(ne.ERROR,t)}else this.hls.trigger(ne.ERROR,{type:re.OTHER_ERROR,details:ie.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}},{key:"_handleTransmuxerFlush",value:function(e){var t=this.getCurrentContext(e);if(t&&this.state===ca){var r=t.frag,i=t.part,n=t.level,a=self.performance.now();r.stats.parsing.end=a,i&&(i.stats.parsing.end=a);var s=this.getLevelDetails(),o=s&&r.sn>s.endSN||this.shouldLoadParts(s,r.end);o!==this.loadingParts&&(this.log("LL-Part loading ".concat(o?"ON":"OFF"," after parsing segment ending @").concat(r.end)),this.loadingParts=o),this.updateLevelTiming(r,i,n,e)}else this.fragCurrent||this.state===na||this.state===fa||(this.state=aa)}},{key:"shouldLoadParts",value:function(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList&&!this.iframesOnly){var r,i=e.partList[0];if(t>=i.end+((null==(r=e.fragmentHint)?void 0:r.duration)||0))if(this.playhead>i.start-i.fragment.duration)return!0}}return!1}},{key:"getCurrentContext",value:function(e){var t=this.levels,r=this.fragCurrent,i=e.level,n=e.sn,a=e.part;if(null==t||!t[i])return this.warn("Levels object was unset while buffering fragment ".concat(n," of ").concat(this.playlistLabel()," ").concat(i,". The current chunk will not be buffered.")),null;var s=t[i],o=s.details,l=a>-1?Wn(o,n,a):null,u=l?l.fragment:qn(o,n,r);return u?(r&&r!==u&&(u.stats=r.stats),{frag:u,part:l,level:s}):null}},{key:"bufferFragmentData",value:function(e,t,r,i,n){if(this.state===ca){pe(t)&&!this.fragContextChanged(t)&&(this.fragPrevious=t);var a=e.data1,s=e.data2,o=a;if(s&&(o=Kt(a,s)),o.length){var l=this.initPTS[t.cc],u=l?-l.baseTime/l.timescale:void 0,c={type:e.type,frag:t,part:r,chunkMeta:i,offset:u,parent:t.type,data:o};if(this.hls.trigger(ne.BUFFER_APPENDING,c),e.dropped&&e.independent&&!r){if(n)return;this.flushBufferGap(t)}}}}},{key:"flushBufferGap",value:function(e){var t=this.media;if(t)if(Bi.isBuffered(t,t.currentTime)){var r=t.currentTime,i=Bi.bufferInfo(t,r,0),n=e.duration,a=Math.min(2*this.config.maxFragLookUpTolerance,.25*n),s=Math.max(Math.min(e.start-a,i.end-a),r+a);e.start-s>a&&this.flushMainBuffer(s,e.start)}else this.flushMainBuffer(0,e.start)}},{key:"getFwdBufferInfo",value:function(e,t){var r,i=this.playhead,n=this.lastCurrentTime>i||null!=(r=this.media)&&r.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,i,t,n)}},{key:"getFwdBufferInfoAtPos",value:function(e,t,r,i){var n=Bi.bufferInfo(e,t,i);if(0===n.len&&void 0!==n.nextStart){var a=this.fragmentTracker.getBufferedFrag(t,r);if(a&&(n.nextStart<=a.end||a.gap)){var s=Math.max(Math.min(n.nextStart,a.end)-t,i);return Bi.bufferInfo(e,t,s)}}return n}},{key:"getMaxBufferLength",value:function(e){var t,r=this.config;return t=e?Math.max(8*r.maxBufferSize/e,r.maxBufferLength):r.maxBufferLength,Math.min(t,r.maxMaxBufferLength)}},{key:"exceedsMaxBuffer",value:function(e,t,r){var i=e.nextStart;if(i&&r.start>i){var n=e.buffered;if(n){for(var a=e.len,s=e.bufferedIndex,o=n.length-1;o>s;o--)n[o].start<r.start&&(a+=n[o].end-n[o].start);return a>=t}}return!1}},{key:"reduceMaxBufferLength",value:function(e,t){var r=this.config,i=Math.max(Math.min(e-t,r.maxBufferLength),t/2),n=Math.max(e-3*t,r.maxMaxBufferLength/2,i);return n>=i&&(r.maxMaxBufferLength=n,this.warn("Reduce max buffer length to ".concat(n,"s")),!0)}},{key:"getAppendedFrag",value:function(e){var t=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,this.playlistType):null;return t&&"fragment"in t?t.fragment:t}},{key:"getNextFragment",value:function(e,t){var r=t.fragments,i=r.length;if(!i)return null;var n=this.config,a=t.fragmentStart,s=n.lowLatencyMode&&!!t.partList,o=null;if(t.live){var l=n.initialLiveManifestSize;if(i<l)return this.warn("Not enough fragments to start playback (have: ".concat(i,", need: ").concat(l,")")),null;if(this.startFragRequested||!s||this.loadingParts||(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),!t.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||e<a){var u;o=this.getInitialLiveFragment(t);var c,d,h=this.config.startPosition,f=this.hls.startPosition,v=this.hls.liveSyncPosition,g=(null==(u=o)?void 0:u.start)||0;if(-1!==f&&f>=a?(c=f,d=f===h?"config":"next load start"):v?(c=v,d="live edge"):(c=e,d="buffer pos"),c<g&&(c=g,d="live frag start"),c<a&&(c=a,d="playlist start"),this.startPosition!=c||this.nextLoadPosition!=c){var p=t.live&&!this.filterReplacedPrimary(o,t)?-1:c;this.log("Setting startPosition to ".concat(p," next load ").concat(c," ").concat(-1===f?"":"(from ".concat(h,") "),"based on ").concat(d,". live edge: ").concat(v," live frag start: ").concat(g," playlist start: ").concat(a," buffer pos: ").concat(e)),this.startPosition=p,this.nextLoadPosition=c}}}else e<=a&&(o=r[0]);if(!o){var m=this.loadingParts?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,m,t)}var y=this.filterReplacedPrimary(o,t);return!y&&o&&(y=ei(t,o.sn))&&(this.nextLoadPosition=y.start),y}},{key:"isLoopLoading",value:function(e,t){if(this.nextLoadPosition<=t)return!1;var r=this.fragmentTracker.getState(e);if(r===yi)return!0;if(r===mi){if(e.gap)return!0;if(e.stats.retry>1)return!0}return!1}},{key:"getNextFragmentLoopLoading",value:function(e,t,r,i,n){var a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t))&&!a.gap&&r.nextStart){var s=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,r.nextStart,i,0);if(null!==s&&r.len+s.len>=n){var o=a.sn;return this.loopSn!==o&&(this.log('buffer full after gaps in "'.concat(i,'" playlist starting at sn: ').concat(o)),this.loopSn=o),null}}return this.loopSn=void 0,a}},{key:"primaryPrefetch",get:function(){var e;if(ya(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(ya(this.config)&&("type"in e?e:e.fragment).type!==de.SUBTITLE){var r=this.hls.interstitialsManager,i=null==r?void 0:r.bufferingItem;if(i){var n=i.event;if(n){if(!n.appendInPlace&&(Math.abs(e.start-i.start)>1||0===i.start))return null}else{if(e.end<=i.start&&!1===(null==t?void 0:t.live))return null;if(e.start>=i.end&&i.nextEvent&&(i.nextEvent.appendInPlace&&!i.nextEvent.hasPlayed||e.start-i.end>1))return null}}if(ma(e,null==r?void 0:r.playerQueue,this.playhead))return null}return e}},{key:"getNextPart",value:function(e,t,r){for(var i=-1,n=!1,a=!0,s=0,o=e.length;s<o;s++){var l=e[s];if(a=a&&!l.independent,i>-1&&r<l.start)break;var u=l.loaded||l.gap;u?i=-1:(n||(l.independent||a)&&l.fragment===t)&&(i=s),n=u&&!l.gap}var c=e[i];return c&&c.fragment!==t&&this.log("Need buffer at ".concat(r," but next unloaded part starts at ").concat(c.start," (sn: ").concat(t.sn," -> ").concat(c.fragment.sn,")")),i}},{key:"loadedEndOfParts",value:function(e,t){for(var r,i=e.length;i--;){if(!(r=e[i]).loaded)return!1;if(t>r.start)return!0}return!1}},{key:"getInitialLiveFragment",value:function(e){var t=e.fragments,r=this.fragPrevious,i=null;if(r){if(e.hasProgramDateTime&&(i=function(e,t,r){if(null===t||!Array.isArray(e)||!e.length||!Z(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;for(var i=0;i<e.length;++i){var n=e[i];if(Jr(t,r,n))return n}return null}(t,r.endProgramDateTime,this.config.maxFragLookUpTolerance),i&&this.log("Live playlist, switching playlist, load frag with same PDT: ".concat(r.programDateTime))),!i){var n=r.sn+1;if(n>=e.startSN&&n<=e.endSN){var a=t[n-e.startSN];r.cc===a.cc&&(i=a,this.log("Live playlist, switching playlist, load frag with next SN: ".concat(i.sn)))}i||(i=Zr(e,r.cc,r.end))&&this.log("Live playlist, switching playlist, load frag with same CC: ".concat(i.sn))}}else{var s=this.hls.liveSyncPosition;null!==s&&(i=this.getFragmentAtPosition(s,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}},{key:"getFragmentAtPosition",value:function(e,t,r){var i,n,a=this.config,s=this.fragPrevious,o=r.fragments,l=r.endSN,u=r.fragmentHint,c=a.maxFragLookUpTolerance,d=r.partList,h=!!(this.loadingParts&&null!=d&&d.length&&u);(h&&!this.bitrateTest&&d[d.length-1].fragment.sn===u.sn&&(o=o.concat(u),l=u.sn),s&&this.fragmentTracker.getState(s)===gi&&(s=null),e<t)?i=Qr(s,o,e,e<this.lastCurrentTime||e>t-c||null!=(n=this.media)&&n.paused||!this.startFragRequested?0:c):i=o[o.length-1];if(i){var f=i.sn-r.startSN,v=this.fragmentTracker.getState(i);if((v===yi||v===mi&&i.gap)&&(s=i),me(i,s)&&(!h||d[0].fragment.sn>i.sn||!r.live)){var g=o[f+1];i=i.sn<l&&this.fragmentTracker.getState(g)!==yi?g:null}}return i}},{key:"alignPlaylists",value:function(e,t,r){var i=e.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;var n=e.fragmentStart,a=!t,s=e.alignedSliding&&Z(n);if(a||!s&&!n){ea(r,e,this);var o=e.fragmentStart;return this.log("Live playlist sliding: ".concat(o," start-sn: ").concat(t?t.startSN:"na","->").concat(e.startSN," fragments: ").concat(i)),o}return n}},{key:"waitForCdnTuneIn",value:function(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}},{key:"setStartPosition",value:function(e,t){var r=this.startPosition;r<t&&(r=-1);var i=this.timelineOffset;if(-1===r){var n=null!==this.startTimeOffset,a=n?this.startTimeOffset:e.startTimeOffset;if(null!==a&&Z(a))r=t+a,a<0&&(r+=e.edge),r=Math.min(Math.max(t,r),t+e.totalduration),this.log("Setting startPosition to ".concat(r," for start time offset ").concat(a," found in ").concat(n?"multivariant":"media"," playlist")),this.startPosition=r;else if(e.live){var s=this.hls.liveSyncPosition;r=s||t,this.log("Setting startPosition to -1 to start at ".concat(s?"live edge":"playlist start"," ").concat(r)),this.startPosition=-1}else this.log("setting startPosition to 0 by default"),this.startPosition=r=0;this.lastCurrentTime=r+i}this.nextLoadPosition=r+i}},{key:"getLoadPosition",value:function(){var e,t=this.media,r=0;return null!=(e=this.hls)&&e.hasEnoughToStart&&t&&!this.iframesOnly?r=t.currentTime:this.nextLoadPosition>=0&&(r=this.nextLoadPosition),r}},{key:"playhead",get:function(){var e;if(null!=(e=this.hls)&&e.hasEnoughToStart){var t,r=null==(t=this.media)?void 0:t.currentTime;return Z(r)?r:this.lastCurrentTime}return this.getLoadPosition()}},{key:"iframesOnly",get:function(){var e;if(this.playlistType!==de.MAIN)return!1;var t=this.getLevelDetails();return t?t.iframesOnly:null==(e=this.levelLastLoaded)?void 0:e.iframes}},{key:"handleFragLoadAborted",value:function(e,t){this.transmuxer&&e.type===this.playlistType&&pe(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===la)||(this.state=aa)}},{key:"onFragmentOrKeyLoadError",value:function(e,t){if(t.chunkMeta&&!t.frag){var r=this.getCurrentContext(t.chunkMeta);r&&(t.frag=r.frag)}var i=t.frag,n=t.part;if(i&&this.levels&&i.type===e)if(this.fragContextChanged(i)){var a;this.warn("Frag load error must match current frag to retry ".concat(i.relurl," > ").concat(null==(a=this.fragCurrent)?void 0:a.relurl))}else{var s=t.details===ie.FRAG_GAP;s&&this.fragmentTracker.addAsGap(i);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===ni,g=f&&!o.resolved&&u&si,p=this.hls.latestLevelDetails,m=null==p?void 0:p.live;if(!v&&g&&pe(i)&&m&&i.sn<p.endSN&&!we(t))this.resetFragmentErrors(e),n?n.gap=!0:this.treatAsGap(i),o.resolved=!0;else if((v||g)&&d<h.maxNumRetry){var y,k=xe(null==(y=t.response)?void 0:y.code),E=De(h,d);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+E,this.state=la,o.resolved=!0,k)return this.log("Waiting for connection (offline)"),this.retryDate=1/0,void(t.reason="offline");this.warn("Fragment ".concat(i.sn," of ").concat(e," ").concat(i.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===ii||(o.resolved=!0)}else this.state=l===ri?ga:fa;this.tickImmediate()}else this.state=fa}}},{key:"checkRetryDate",value:function(){var e=self.performance.now(),t=this.retryDate,r=t===1/0;(!t||e>=t||r&&!xe(0))&&(r&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=aa)}},{key:"reduceLengthAndFlushBuffer",value:function(e){if(this.state===ca||this.state===da){var t=e.frag,r=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,r),n=i&&i.len>.5;n&&this.reduceMaxBufferLength(i.len,(null==t?void 0:t.duration)||10);var a=!n;return a?this.warn("Buffer full error while media.currentTime (".concat(this.playhead,") is not buffered, flush ").concat(r," buffer")):i.nextStart&&t&&i.nextStart>t.start&&this.flushMainBuffer(i.nextStart,Number.POSITIVE_INFINITY,r===de.AUDIO?r:void 0),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}},{key:"resetFragmentErrors",value:function(e){e===de.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==na&&(this.state=aa)}},{key:"afterBufferFlushed",value:function(e,t){if(e){var r=Bi.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,this.playlistType),this.state===ha&&this.resetLoadingState()}}},{key:"resetLoadingState",value:function(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==na&&(this.state=aa)}},{key:"resetStartWhenNotLoaded",value:function(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;var e=this.getLevelDetails();null!=e&&e.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(e,e.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}},{key:"resetWhenMissingContext",value:function(e){this.log("Loading context changed while buffering sn ".concat(e.sn," of ").concat(this.playlistLabel()," ").concat(-1===e.level?"<removed>":e.level,". This chunk will not be buffered.")),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}},{key:"removeUnbufferedFrags",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}},{key:"updateLevelTiming",value:function(e,t,r,i){var n=this,a=r.details;if(a){if(this.log("update level timing ".concat(e.type," sn: ").concat(e.sn).concat(t?" part: "+t.index:""," of ").concat(this.fragInfo(e,!1,t))),!Object.keys(e.elementaryStreams).reduce(function(t,s){var o=e.elementaryStreams[s];if(o){var l=o.endPTS-o.startPTS;if(l<=0)return n.warn("Could not parse fragment ".concat(e.sn," ").concat(s," duration reliably (").concat(l,")")),t||!1;var u=i.partial?0:Vn(a,e,o.startPTS,o.endPTS,o.startDTS,o.endDTS,n.iframesOnly,n);return n.hls.trigger(ne.LEVEL_PTS_UPDATED,{details:a,level:r,drift:u,type:s,frag:e,start:o.startPTS,end:o.endPTS}),!0}return t},!1)){var s,o,l,u,c=null===(null==(s=this.transmuxer)?void 0:s.error),d=null!=(null==(o=this.transmuxer)?void 0:o.error),h=(null!=(l=null==(u=this.levels)?void 0:u.length)?l:0)>1;if((0===r.fragmentError||c&&(r.fragmentError<2||e.endList)||d&&h)&&this.treatAsGap(e,r),c){var f=new Error("Found no media in ".concat(this.playlistLabel()," ").concat(e.level," ").concat(t?"part: ".concat(t.index," of "):"","sn: ").concat(e.sn," at playlist time: ").concat(e.start,". Resetting transmuxer to fallback to playlist timing"));if(this.warn(f.message),this.hls.trigger(ne.ERROR,{type:re.MEDIA_ERROR,details:ie.FRAG_PARSING_ERROR,fatal:!1,error:f,frag:e,reason:"Found no media in msn ".concat(e.sn," of ").concat(this.playlistLabel(),' "').concat(r.url,'"')}),!this.hls)return;this.resetTransmuxer()}}this.state=da,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(ne.FRAG_PARSED,{frag:e,part:t,chunkMeta:i})}else this.warn("level.details undefined")}},{key:"playlistLabel",value:function(){return"".concat(this.playlistType," playlist")}},{key:"fragInfo",value:function(e){var t,r,i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],n=arguments.length>2?arguments[2]:void 0;return"".concat(this.playlistLabel()," ").concat(e.level," (").concat(n?"part":"frag",":[").concat(null!=(t=i&&!n?e.startPTS:(n||e).start)?t:NaN,"-").concat(null!=(r=i&&!n?e.endPTS:(n||e).end)?r:NaN,"]").concat(n&&"main"===e.type?"INDEPENDENT="+(n.independent?"YES":"NO"):"",")")}},{key:"treatAsGap",value:function(e,t){t&&t.fragmentError++,this.fragmentTracker.addAsGap(e)}},{key:"resetTransmuxer",value:function(){var e;null==(e=this.transmuxer)||e.reset()}},{key:"isFragmentNearlyDownloaded",value:function(e){var t,r=null==(t=e.loader)?void 0:t.stats;if(!r)return!1;var i=r.loading.first>0,n=(r.total-r.loaded)/(this.hls.bandwidthEstimate||this.hls.config.abrEwmaDefaultEstimate);return i&&n<=.15}},{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)))}},{key:"calculateOptimalSwitchPoint",value:function(e,t){var r=0,i=this.hls,n=this.media,a=this.config,s=this.levels,o=this.playlistType,l=this.getLevelDetails();if(n&&!n.paused&&s){var u,c=o===de.AUDIO?br(e.audioCodec,128e3):e.maxBitrate,d=1+i.ttfbEstimate/1e3,h=i.bandwidthEstimate*a.abrBandWidthUpFactor;r=d+c*(l&&(this.loadingParts?l.partTarget:l.averagetargetduration)||(null==(u=this.fragCurrent)?void 0:u.duration)||6)/h,e.details||(r+=d)}var f=this.playhead;return{fetchdelay:r,okToFlushForwardBuffer:!(null!=l&&l.live)||t.end-f>1.5*r}}},{key:"scheduleTrackSwitch",value:function(e,t,r){var i=this.media,n=this.playlistType;if(i&&e){var a=r?this.getBufferedFrag(this.playhead+t):null;if(a){var s=this.followingBufferedFrag(a);if(s){var o;this.abortCurrentFrag();var l=s.maxStartPTS?s.maxStartPTS:s.start,u=s.duration,c=Math.max(a.end,l+Math.min(Math.max(u-this.config.maxFragLookUpTolerance,u*(this.couldBacktrack?.5:.125)),u*(this.couldBacktrack?.75:.25)));if(((null==(o=this.getLevelDetails())?void 0:o.fragmentStart)||0)>c)return;var d=n===de.MAIN?null:"audio";this.flushMainBuffer(c,Number.POSITIVE_INFINITY,d),this.cleanupBackBuffer()}}}}},{key:"cleanupBackBuffer",value:function(){var e=this.media,t=this.playlistType;if(e){var r=this.getAppendedFrag(this.playhead);if(r&&r.start>1){var i=t===de.AUDIO;this.flushMainBuffer(0,r.start-(i?0:1),i?"audio":null)}}}},{key:"getBufferedFrag",value:function(e){return this.fragmentTracker.getBufferedFrag(e,this.playlistType)}},{key:"followingBufferedFrag",value:function(e){return e?this.getBufferedFrag(e.end+.5):null}},{key:"abortCurrentFrag",value:function(){var e=this.fragCurrent;switch(this.fragCurrent=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case sa:case oa:case la:case ca:case da:this.state=aa}this.nextLoadPosition=this.playhead}},{key:"checkFragPlaying",value:function(){var e=this.media,t=null;if(e&&e.readyState>1&&!1===e.seeking){var r=e.currentTime;if(Bi.isBuffered(e,r)?t=this.getAppendedFrag(r):Bi.isBuffered(e,r+.1)&&(t=this.getAppendedFrag(r+.1)),t&&(this.backtrackFragment=void 0,!me(t,this.fragPlaying)))return this.fragPlaying=t,!0}return!1}},{key:"getBufferOutput",value:function(){return null}},{key:"nextLevelSwitch",value:function(){var e=this.levels,t=this.media,r=this.hls,i=this.config,n=this.playlistType;if(null!=t&&t.readyState&&e&&r&&i){var a=this.getBufferOutput(),s=this.getFwdBufferInfo(a,n);if(!s)return;var o=e[n===de.AUDIO?r.nextAudioTrack:r.nextLoadLevel],l=this.calculateOptimalSwitchPoint(o,s),u=l.fetchdelay,c=l.okToFlushForwardBuffer;this.scheduleTrackSwitch(s,u,c)}this.tickImmediate()}}])}(Oi);function ma(e,t,r){if(t)for(var i=t.length;i--;){var n=t[i].interstitial,a=n.startTime,s=Math.min(a+n.duration,n.resumeTime);if(n.appendInPlace){if(e.start>=a&&e.end<=s)return!0;if(r>e.start&&e.end>a&&e.start<s)return!0}}return!1}function ya(e){return!!e.interstitialsController&&!1!==e.enableInterstitialPlayback}var ka=function(){return l(function e(){s(this,e),this.chunks=[],this.dataLength=0},[{key:"push",value:function(e){this.chunks.push(e),this.dataLength+=e.length}},{key:"flush",value:function(){var e,t=this.chunks,r=this.dataLength;return t.length?(e=1===t.length?t[0]:function(e,t){for(var r=new Uint8Array(t),i=0,n=0;n<e.length;n++){var a=e[n];r.set(a,i),i+=a.length}return r}(t,r),this.reset(),e):new Uint8Array(0)}},{key:"reset",value:function(){this.chunks.length=0,this.dataLength=0}}])}();var Ea,Sa={exports:{}};var Ta=(Ea||(Ea=1,function(e){var t=Object.prototype.hasOwnProperty,r="~";function i(){}function n(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function a(e,t,i,a,s){if("function"!=typeof i)throw new TypeError("The listener must be a function");var o=new n(i,a||e,s),l=r?r+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function s(e,t){0===--e._eventsCount?e._events=new i:delete e._events[t]}function o(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(r=!1)),o.prototype.eventNames=function(){var e,i,n=[];if(0===this._eventsCount)return n;for(i in e=this._events)t.call(e,i)&&n.push(r?i.slice(1):i);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(e)):n},o.prototype.listeners=function(e){var t=r?r+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var n=0,a=i.length,s=new Array(a);n<a;n++)s[n]=i[n].fn;return s},o.prototype.listenerCount=function(e){var t=r?r+e:e,i=this._events[t];return i?i.fn?1:i.length:0},o.prototype.emit=function(e,t,i,n,a,s){var o=r?r+e:e;if(!this._events[o])return!1;var l,u,c=this._events[o],d=arguments.length;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),d){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,i),!0;case 4:return c.fn.call(c.context,t,i,n),!0;case 5:return c.fn.call(c.context,t,i,n,a),!0;case 6:return c.fn.call(c.context,t,i,n,a,s),!0}for(u=1,l=new Array(d-1);u<d;u++)l[u-1]=arguments[u];c.fn.apply(c.context,l)}else{var h,f=c.length;for(u=0;u<f;u++)switch(c[u].once&&this.removeListener(e,c[u].fn,void 0,!0),d){case 1:c[u].fn.call(c[u].context);break;case 2:c[u].fn.call(c[u].context,t);break;case 3:c[u].fn.call(c[u].context,t,i);break;case 4:c[u].fn.call(c[u].context,t,i,n);break;default:if(!l)for(h=1,l=new Array(d-1);h<d;h++)l[h-1]=arguments[h];c[u].fn.apply(c[u].context,l)}}return!0},o.prototype.on=function(e,t,r){return a(this,e,t,r,!1)},o.prototype.once=function(e,t,r){return a(this,e,t,r,!0)},o.prototype.removeListener=function(e,t,i,n){var a=r?r+e:e;if(!this._events[a])return this;if(!t)return s(this,a),this;var o=this._events[a];if(o.fn)o.fn!==t||n&&!o.once||i&&o.context!==i||s(this,a);else{for(var l=0,u=[],c=o.length;l<c;l++)(o[l].fn!==t||n&&!o[l].once||i&&o[l].context!==i)&&u.push(o[l]);u.length?this._events[a]=1===u.length?u[0]:u:s(this,a)}return this},o.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&s(this,t)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=r,o.EventEmitter=o,e.exports=o}(Sa)),Sa.exports),Aa=ae(Ta),ba="1.7.3",Ia={};function Ra(e,t){return 255===e[t]&&240==(246&e[t+1])}function La(e,t){return 1&e[t+1]?7:9}function Pa(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function wa(e,t){return t+1<e.length&&Ra(e,t)}function Ca(e,t){if(wa(e,t)){var r=La(e,t);if(t+r>=e.length)return!1;var i=Pa(e,t);if(i<=r)return!1;var n=t+i;return n===e.length||wa(e,n)}return!1}function Da(e,t,r,i,n){if(!e.samplerate){var a=function(e,t,r,i){var n=t[r+2],a=n>>2&15;if(!(a>12)){var s,o=1+(n>>6&3),l=t[r+3]>>6&3|(1&n)<<2,u=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][a],c=a;5!==o&&29!==o||(c-=3);var d=(14&c)>>1,h=(1&c)<<7|l<<3,f=0;if(1===o&&a>=6){var v=a-3;s=[(f=5)<<3|d,h|(14&v)>>1,(1&v)<<7|8,0]}else s=[o<<3|d,h];var g="mp4a.40."+(f||o);return je.log("manifest codec:".concat(i,", parsed codec:").concat(g,", channels:").concat(l,", rate:").concat(u," (ADTS object type:").concat(o," sampling index:").concat(a," esds config:[").concat(s.join(","),"])")),{config:s,samplerate:u,channelCount:l,codec:g,parsedCodec:g,manifestCodec:i}}var p=new Error("invalid ADTS sampling index:".concat(a));e.emit(ne.ERROR,ne.ERROR,{type:re.MEDIA_ERROR,details:ie.FRAG_PARSING_ERROR,fatal:!0,error:p,reason:p.message})}(t,r,i,n);if(!a)return;Ae(e,a)}}function _a(e){return 9216e4/e}function Ma(e,t,r,i,n){var a,s=i+n*_a(e.samplerate),o=function(e,t){var r=La(e,t);if(t+r<=e.length){var i=Pa(e,t)-r;if(i>0)return{headerLength:r,frameLength:i}}}(t,r);if(o){var l=o.frameLength,u=o.headerLength,c=u+l,d=Math.max(0,r+c-t.length);d?(a=new Uint8Array(c-u)).set(t.subarray(r+u,t.length),0):a=t.subarray(r+u,r+c);var h={unit:a,pts:s};return d||e.samples.push(h),{sample:h,length:c,missing:d}}var f=t.length-r;return(a=new Uint8Array(f)).set(t.subarray(r,t.length),0),{sample:{unit:a,pts:s},length:f,missing:-1}}var xa=function(e){return e.audioId3="org.id3",e.dateRange="com.apple.quicktime.HLS",e.emsg="https://aomedia.org/emsg/ID3",e.misbklv="urn:misb:KLV:bin:1910.1",e}({});function Oa(){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 Fa=function(){return l(function e(){s(this,e),this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null},[{key:"resetInitSegment",value:function(e,t,r,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}},{key:"resetTimeStamp",value:function(e){this.initPTS=e,this.resetContiguity()}},{key:"resetContiguity",value:function(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}},{key:"canParse",value:function(e,t){return!1}},{key:"appendFrame",value:function(e,t,r){}},{key:"demux",value:function(e,t){this.cachedData&&(e=Kt(this.cachedData,e),this.cachedData=null);var r,i=it(e,0),n=i?i.length:0,a=this._audioTrack,s=this._id3Track,o=i?ht(i):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&Z(o))&&(this.basePTS=Na(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),i&&i.length>0&&s.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:xa.audioId3,duration:Number.POSITIVE_INFINITY});n<l;){if(this.canParse(e,n)){var u=this.appendFrame(a,e,n);u?(this.frameIndex++,this.lastPTS=u.sample.pts,r=n+=u.length):n=l}else tt(e,n)?(i=it(e,n),s.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:xa.audioId3,duration:Number.POSITIVE_INFINITY}),r=n+=i.length):n++;if(n===l&&r!==l){var c=e.slice(r);this.cachedData?this.cachedData=Kt(this.cachedData,c):this.cachedData=c}}return{audioTrack:a,videoTrack:Oa(),id3Track:s,textTrack:Oa()}}},{key:"demuxSampleAes",value:function(e,t,r){return Promise.reject(new Error("[".concat(this,"] This demuxer does not support Sample-AES decryption")))}},{key:"flush",value:function(e){var t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:Oa(),id3Track:this._id3Track,textTrack:Oa()}}},{key:"destroy",value:function(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}])}(),Na=function(e,t,r){return Z(e)?90*e:9e4*t+(r?9e4*r.baseTime/r.timescale:0)},Ba=[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],Ua=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Va=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Ga=[0,1,1,4];function Ha(e,t,r,i,n){if(!(r+24>t.length)){var a=Ka(t,r);if(a&&r+a.frameLength<=t.length){var s=i+n*(9e4*a.samplesPerFrame/a.sampleRate),o={unit:t.subarray(r,r+a.frameLength),pts:s,dts:s};return e.config=[],e.channelCount=a.channelCount,e.samplerate=a.sampleRate,e.samples.push(o),{sample:o,length:a.frameLength,missing:0}}}}function Ka(e,t){var r=e[t+1]>>3&3,i=e[t+1]>>1&3,n=e[t+2]>>4&15,a=e[t+2]>>2&3;if(1!==r&&0!==n&&15!==n&&3!==a){var s=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*Ba[14*(3===r?3-i:3===i?3:4)+n-1],u=Ua[3*(3===r?0:2===r?1:2)+a],c=3===o?1:2,d=Va[r][i],h=Ga[i],f=8*d*h,v=Math.floor(d*l/u+s)*h,g=ir();return!!g&&g<=87&&2===i&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:u,channelCount:c,frameLength:v,samplesPerFrame:f}}}function ja(e,t){return!(255!==e[t]||224&~e[t+1]||!(6&e[t+1]))}function qa(e,t){return t+1<e.length&&ja(e,t)}function Wa(e,t){if(t+1<e.length&&ja(e,t)){var r=Ka(e,t),i=4;null!=r&&r.frameLength&&(i=r.frameLength);var n=t+i;return n===e.length||qa(e,n)}return!1}var Ya=function(){return l(function e(t,r,i){s(this,e),this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Pi(r,!0)},[{key:"decryptBuffer",value:function(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Ai,{start:0,end:e.byteLength})}},{key:"decryptAacSample",value:function(e,t,r){var i=this,n=e[t].unit;if(!(n.length<=16)){var a=n.subarray(16,n.length-n.length%16),s=a.buffer.slice(a.byteOffset,a.byteOffset+a.length);this.decryptBuffer(s).then(function(a){var s=new Uint8Array(a);n.set(s,16),i.decrypter.isSync()||i.decryptAacSamples(e,t+1,r)}).catch(r)}}},{key:"decryptAacSamples",value:function(e,t,r){for(;;t++){if(t>=e.length)return void r();if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,r),!this.decrypter.isSync()))return}}},{key:"getAvcEncryptedData",value:function(e){for(var t=16*Math.floor((e.length-48)/160)+16,r=new Int8Array(t),i=0,n=32;n<e.length-16;n+=160,i+=16)r.set(e.subarray(n,n+16),i);return r}},{key:"getAvcDecryptedUnit",value:function(e,t){for(var r=new Uint8Array(t),i=0,n=32;n<e.length-16;n+=160,i+=16)e.set(r.subarray(i,i+16),n);return e}},{key:"decryptAvcSample",value:function(e,t,r,i,n){var a=this,s=Yt(n.data),o=this.getAvcEncryptedData(s);this.decryptBuffer(o.buffer).then(function(o){n.data=a.getAvcDecryptedUnit(s,o),a.decrypter.isSync()||a.decryptAvcSamples(e,t,r+1,i)}).catch(i)}},{key:"decryptAvcSamples",value:function(e,t,r,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,r=0){if(t>=e.length)return void i();for(var n=e[t].units;!(r>=n.length);r++){var a=n[r];if(!(a.data.length<=48||1!==a.type&&5!==a.type||(this.decryptAvcSample(e,t,r,i,a),this.decrypter.isSync())))return}}}}])}(),za=function(e){function t(e,r){var i;return s(this,t),(i=a(this,t)).observer=void 0,i.config=void 0,i.sampleAes=null,i.observer=e,i.config=r,i}return f(t,e),l(t,[{key:"resetInitSegment",value:function(e,r,i,n){A(t,"resetInitSegment",this,3)([e,r,i,n]),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:r,duration:n,inputTimeScale:9e4,dropped:0}}},{key:"canParse",value:function(e,t){return function(e,t){return function(e,t){return t+5<e.length}(e,t)&&Ra(e,t)&&Pa(e,t)<=e.length-t}(e,t)}},{key:"appendFrame",value:function(e,t,r){Da(e,this.observer,t,r,e.manifestCodec);var i=Ma(e,t,r,this.basePTS,this.frameIndex);if(0===(null==i?void 0:i.missing))return i}},{key:"demuxSampleAes",value:function(e,t,r){var i=this.demux(e,r),n=this.sampleAes=new Ya(this.observer,this.config,t);return new Promise(function(e){n.decryptAacSamples(i.audioTrack.samples,0,function(){e(i)})})}}],[{key:"probe",value:function(e,t){if(!e)return!1;var r=it(e,0),i=(null==r?void 0:r.length)||0;if(Wa(e,i))return!1;for(var n=e.length;i<n;i++)if(Ca(e,i))return t.log("ADTS sync word found !"),!0;return!1}}])}(Fa),Xa=function(e,t){var r=0,i=5;t+=i;for(var n=new Uint32Array(1),a=new Uint32Array(1),s=new Uint8Array(1);i>0;){s[0]=e[t];var o=Math.min(i,8),l=8-o;a[0]=4278190080>>>24+l<<l,n[0]=(s[0]&a[0])>>l,r=r?r<<o|n[0]:n[0],t+=1,i-=o}return r},Qa=function(e){function t(e){var r;return s(this,t),(r=a(this,t)).observer=void 0,r.observer=e,r}return f(t,e),l(t,[{key:"resetInitSegment",value:function(e,r,i,n){A(t,"resetInitSegment",this,3)([e,r,i,n]),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:r,duration:n,inputTimeScale:9e4,dropped:0}}},{key:"canParse",value:function(e,t){return t+64<e.length}},{key:"appendFrame",value:function(e,t,r){var i=$a(e,t,r,this.basePTS,this.frameIndex);if(-1!==i)return{sample:e.samples[e.samples.length-1],length:i,missing:0}}}],[{key:"probe",value:function(e){if(!e)return!1;var t=it(e,0);if(!t)return!1;var r=t.length;if(11===e[r]&&119===e[r+1]&&void 0!==ht(t)){if(Xa(e,r)<16)return!0;throw new Error("Containerless ec-3 is not supported")}return!1}}])}(Fa);function $a(e,t,r,i,n){if(r+8>t.length)return-1;if(11!==t[r]||119!==t[r+1])return-1;var a=t[r+4]>>6;if(a>=3)return-1;var s=[48e3,44100,32e3][a],o=63&t[r+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+a];if(r+l>t.length)return-1;var u=t[r+6]>>5,c=0;2===u?c+=2:(1&u&&1!==u&&(c+=2),4&u&&(c+=2));var d=(t[r+6]<<8|t[r+7])>>12-c&1,h=[2,1,2,3,3,4,4,5][u]+d,f=t[r+5]>>3,v=7&t[r+5],g=new Uint8Array([a<<6|f<<1|v>>2,(3&v)<<6|u<<3|d<<2|o>>4,o<<4&224]),p=i+n*(1536/s*9e4),m=t.subarray(r,r+l);return e.config=g,e.channelCount=h,e.samplerate=s,e.samples.push({unit:m,pts:p}),l}var Ja=function(e){function t(){return s(this,t),a(this,t,arguments)}return f(t,e),l(t,[{key:"resetInitSegment",value:function(e,r,i,n){A(t,"resetInitSegment",this,3)([e,r,i,n]),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:r,duration:n,inputTimeScale:9e4,dropped:0}}},{key:"canParse",value:function(e,t){return function(e,t){return ja(e,t)&&4<=e.length-t}(e,t)}},{key:"appendFrame",value:function(e,t,r){if(null!==this.basePTS)return Ha(e,t,r,this.basePTS,this.frameIndex)}}],[{key:"probe",value:function(e){if(!e)return!1;var t=it(e,0),r=(null==t?void 0:t.length)||0;if(t&&11===e[r]&&119===e[r+1]&&void 0!==ht(t)&&Xa(e,r)<=16)return!1;for(var i=e.length;r<i;r++)if(Wa(e,r))return je.log("MPEG Audio sync word found !"),!0;return!1}}])}(Fa),Za=/\/emsg[-/]ID3/i,es=function(){return l(function e(t,r,i){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:je;s(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.initData=void 0,this.logger=void 0,this.config=r,this.logger=n},[{key:"resetTimeStamp",value:function(){}},{key:"resetInitSegment",value:function(e,t,r,i){var n=this.videoTrack=Oa("video",1),a=this.audioTrack=Oa("audio",1),s=this.txtTrack=Oa("text",1);if(this.id3Track=Oa("id3",1),this.initData=void 0,this.timeOffset=0,null!=e&&e.byteLength){var o=this.initData=Mt(e);if(o.video){var l=o.video,u=l.id,c=l.timescale,d=l.codec,h=l.supplemental;n.id=u,n.timescale=s.timescale=c,n.codec=d,n.supplemental=h}if(o.audio){var f=o.audio,v=f.id,g=f.timescale,p=f.codec;a.id=v,a.timescale=g,a.codec=p}s.id=Et.text,n.sampleDuration=0,n.duration=a.duration=i}}},{key:"resetContiguity",value:function(){this.remainderData=null}},{key:"demux",value:function(e,t,r){this.timeOffset=t;var i=e,n=this.videoTrack,a=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=Kt(this.remainderData,e));var s=function(e){var t={valid:null,remainder:null},r=Ct(e,["moof"]);if(r.length<2)return t.remainder=e,t;var i=r[r.length-1];return t.valid=e.slice(0,i.byteOffset-8),t.remainder=e.slice(i.byteOffset-8),t}(i);this.remainderData=s.remainder,n.samples=s.valid||new Uint8Array}else n.samples=i;var o=this.extractID3Track(n,t),l=this.parseFragment(n,a,t,r);return{videoTrack:n,audioTrack:this.audioTrack,id3Track:o,textTrack:this.txtTrack,initData:this.initData,sampleData:l}}},{key:"flush",value:function(e,t){var r=this.timeOffset,i=this.videoTrack,n=this.txtTrack;i.samples=this.remainderData||new Uint8Array,this.remainderData=null;var a=this.extractID3Track(i,this.timeOffset),s=this.parseFragment(i,n,r,t);return{videoTrack:i,audioTrack:Oa(),id3Track:a,textTrack:Oa(),initData:this.initData,sampleData:s}}},{key:"parseFragment",value:function(e,t,r,i){var n=this.initData;if(n&&i){var a=function(e,t,r,i){var n=arguments.length>4&&void 0!==arguments[4]&&arguments[4],a=[];return{samples:a,sampleData:{includeSampleDetails:n,tracks:Ht(t.samples,r,i,n,{isHEVCFlavor:jt(t.codec),samples:a,timeOffset:e,timescale:t.timescale,trackId:t.id})}}}(r,e,n,this.logger,i.iframe),s=a.samples,o=a.sampleData;return t.samples=s,o}t.samples=function(e,t){var r=[],i=t.samples,n=t.timescale,a=t.id,s=!1;return Ct(i,["moof"]).map(function(o){var l=o.byteOffset-8;Ct(o,["traf"]).map(function(o){var u=Ct(o,["tfdt"]).map(function(e){var t=e[0],r=Tt(e,4);return 1===t&&(r*=Math.pow(2,32),r+=Tt(e,8)),r/n})[0];return void 0!==u&&(e=u),Ct(o,["tfhd"]).map(function(u){var c=Tt(u,4),d=16777215&Tt(u,0),h=!!(1&d),f=0,v=!!(2&d),g=!!(8&d),p=0,m=!!(16&d),y=0,k=!!(32&d),E=!h&&!!(131072&d),S=8;c===a&&(h?(f=Tt(u,S),S+=4,f*=Math.pow(2,32),f+=Tt(u,S),S+=4):E&&(f=l),v&&(S+=4),g&&(p=Tt(u,S),S+=4),m&&(y=Tt(u,S),S+=4),k&&(S+=4),"video"===t.type&&(s=jt(t.codec)),Ct(o,["trun"]).map(function(a){var o=a[0],l=16777215&Tt(a,0),u=!!(1&l),c=0,d=!!(4&l),h=!!(256&l),v=0,g=!!(512&l),m=0,k=!!(1024&l),E=!!(2048&l),S=0,T=Tt(a,4),A=8;u&&(c=Tt(a,A),A+=4),d&&(A+=4);for(var b=f+c,I=0;I<T;I++){if(h?(v=Tt(a,A),A+=4):v=p,g?(m=Tt(a,A),A+=4):m=y,k&&(A+=4),E&&(S=0===o?Tt(a,A):It(a,A),A+=4),t.type===fe)for(var R=0;R<m;){var L=Tt(i,b);qt(s,i[b+=4])&&Wt(i.subarray(b,b+L),s?2:1,e+S/n,r),b+=L,R+=L+4}e+=v/n}}))})})}),r}(r,e)}},{key:"extractID3Track",value:function(e,t){var r=this,i=this.id3Track;if(e.samples.length){var n=Ct(e.samples,["emsg"]);n&&n.forEach(function(e){var n=function(e){var t,r=e[0],i="",n="",a=0,s=0,o=0,l=0,u=4;if(0===r){var c=bt(e,u),d=null!==c?bt(e,u+c.length):null;null!==c&&null!==d?(i=c,n=d,a=Tt(e,u+=c.length+d.length),s=Tt(e,u+=4),o=Tt(e,u+=4),l=Tt(e,u+=4),u+=4):(je.warn("Unterminated ".concat(null===c?"scheme_id_uri":"value"," in parsing emsg box: version 0 box ends inside a string, dropping all of its fields")),u=e.length)}else if(1===r){a=Tt(e,u);var h=Tt(e,u+=4),f=Tt(e,u+=4);u+=4,t=Math.pow(2,32)*h+f,ee(t)||(t=Number.MAX_SAFE_INTEGER,je.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=Tt(e,u),l=Tt(e,u+=4);var v=bt(e,u+=4),g=null!==v?bt(e,u+v.length):null;null!==v&&(i=v,u+=v.length),null!==g?(n=g,u+=g.length):(je.warn("Unterminated ".concat(null===v?"scheme_id_uri":"value"," in parsing emsg box: version 1 box ends inside a string, dropping its ").concat(null===v?"strings and payload":"value and payload")),u=e.length)}return{schemeIdUri:i,value:n,timeScale:a,presentationTime:t,presentationTimeDelta:s,eventDuration:o,id:l,payload:e.subarray(u,e.byteLength)}}(e);if(Za.test(n.schemeIdUri)){var a=ts(n,t),s=4294967295===n.eventDuration?Number.POSITIVE_INFINITY:n.eventDuration/n.timeScale;s<=.001&&(s=Number.POSITIVE_INFINITY);var o=n.payload;i.samples.push({data:o,len:o.byteLength,dts:a,pts:a,type:xa.emsg,duration:s})}else if(r.config.enableEmsgKLVMetadata){var l=r.config.emsgKLVSchemaUri||xa.misbklv;if(n.schemeIdUri.startsWith(l)){var u=ts(n,t);i.samples.push({data:n.payload,len:n.payload.byteLength,dts:u,pts:u,type:xa.misbklv,duration:Number.POSITIVE_INFINITY})}}})}return i}},{key:"demuxSampleAes",value:function(e,t,r){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}},{key:"destroy",value:function(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0,this.initData=void 0}}],[{key:"probe",value:function(e){return function(e,t){for(var r=e.byteLength,i=0;i<r;){var n=Tt(e,i);if(n>8&&Tt(e,i+4)===kt[t])return!0;i=n>1?i+n:r}return!1}(e,"moof")}}])}();function ts(e,t){return Z(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}var rs=function(){return l(function e(){s(this,e),this.VideoSample=null},[{key:"createVideoSample",value:function(e,t,r){return{key:e,frame:!1,pts:t,dts:r,units:[],length:0}}},{key:"getLastNalUnit",value:function(e){var t,r,i=this.VideoSample;if(i&&0!==i.units.length||(i=e[e.length-1]),null!=(t=i)&&t.units){var n=i.units;r=n[n.length-1]}return r}},{key:"pushAccessUnit",value:function(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){var r=t.samples,i=r.length;if(!i)return void t.dropped++;var n=r[i-1];e.pts=n.pts,e.dts=n.dts}t.samples.push(e)}}},{key:"parseNALu",value:function(e,t,r){var i=t.byteLength;if(0===i)return[];var n=e.naluState||0,a=-1===n?0:n,s=[],o=0,l=0,u=-1,c=0;for(-1===n&&(u=0,c=this.getNALuType(t,0),l=1);l<i;){var d=t.indexOf(1,l);if(-1===d)break;l=d+1;for(var h=d;h>0&&0===t[h-1];)h--;if(!(d-h+(0===h?a:0)<2)){if(u>=0)s.push({data:t.subarray(u,h),type:c});else{var f=this.getLastNalUnit(e.samples);f&&(h>0?f.data=Kt(f.data,t.subarray(0,h)):a>0&&(f.data=f.data.subarray(0,f.data.byteLength-a)),f.state=0)}if(!(l<i)){o=-1,u=-1;break}u=l,c=this.getNALuType(t,l)}}if(-1!==o){for(var v=i;v>0&&0===t[v-1];)v--;o=i-v+(0===v?a:0)}if(u>=0)s.push({data:t.subarray(u),type:c,state:o});else if(0===s.length&&-1!==o){var g=this.getLastNalUnit(e.samples);g&&(g.data=Kt(g.data,t),g.state=o)}return e.naluState=o,s}}])}(),is=function(){return l(function e(t){s(this,e),this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0},[{key:"loadWord",value:function(){var e=this.data,t=this.bytesAvailable,r=e.byteLength-t,i=new Uint8Array(4),n=Math.min(4,t);if(0===n)throw new Error("no bytes available");i.set(e.subarray(r,r+n)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*n,this.bytesAvailable-=n}},{key:"skipBits",value:function(e){var t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,e-=(t=e>>3)<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}},{key:"readBits",value:function(e){var t=Math.min(this.bitsAvailable,e),r=this.word>>>32-t;if(e>32&&je.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return(t=e-t)>0&&this.bitsAvailable?r<<t|this.readBits(t):r}},{key:"skipLZ",value:function(){var e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}},{key:"skipUEG",value:function(){this.skipBits(1+this.skipLZ())}},{key:"skipEG",value:function(){this.skipBits(1+this.skipLZ())}},{key:"readUEG",value:function(){var e=this.skipLZ();return this.readBits(e+1)-1}},{key:"readEG",value:function(){var e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}},{key:"readBoolean",value:function(){return 1===this.readBits(1)}},{key:"readUByte",value:function(){return this.readBits(8)}}])}(),ns=function(e){function t(){return s(this,t),a(this,t,arguments)}return f(t,e),l(t,[{key:"parsePES",value:function(e,t,r,i,n){var a,s=this,o=n.iframe,l=this.parseNALu(e,r.data,i),u=this.VideoSample,c=!1;r.data=null,u&&l.length&&!e.audFound&&(this.pushAccessUnit(u,e),u=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),l.forEach(function(i){var n,l;switch(i.type){case 1:if(o)break;var d=!1;a=!0;var h,f=i.data;if(c&&f.length>4){var v=s.readSliceType(f);2!==v&&4!==v&&7!==v&&9!==v||(d=!0)}if(d)null!=(h=u)&&h.frame&&!u.key&&(s.pushAccessUnit(u,e),u=s.VideoSample=null);u||(u=s.VideoSample=s.createVideoSample(!0,r.pts,r.dts)),u.frame=!0,u.key=d;break;case 5:a=!0,null!=(n=u)&&n.frame&&!u.key&&(s.pushAccessUnit(u,e),u=s.VideoSample=null),u||(u=s.VideoSample=s.createVideoSample(!0,r.pts,r.dts)),u.key=!0,u.frame=!0;break;case 6:if(o)break;a=!0,Wt(i.data,1,r.pts,t.samples);break;case 7:var g,p;a=!0,c=!0;var m=i.data,y=s.readSPS(m);if(!e.sps||e.width!==y.width||e.height!==y.height||(null==(g=e.pixelRatio)?void 0:g[0])!==y.pixelRatio[0]||(null==(p=e.pixelRatio)?void 0:p[1])!==y.pixelRatio[1]){e.width=y.width,e.height=y.height,e.pixelRatio=y.pixelRatio,e.sps=[m];for(var k=m.subarray(1,4),E="avc1.",S=0;S<3;S++){var T=k[S].toString(16);T.length<2&&(T="0"+T),E+=T}e.codec=E}break;case 8:a=!0,e.pps=[i.data];break;case 9:a=!0,e.audFound=!0,null!=(l=u)&&l.frame&&(s.pushAccessUnit(u,e),u=null),u||(u=s.VideoSample=s.createVideoSample(!1,r.pts,r.dts));break;case 12:a=!0;break;default:a=!1}u&&a&&u.units.push(i)}),i&&u&&(this.pushAccessUnit(u,e),this.VideoSample=null)}},{key:"getNALuType",value:function(e,t){return 31&e[t]}},{key:"readSliceType",value:function(e){var t=new is(e);return t.readUByte(),t.readUEG(),t.readUEG()}},{key:"skipScalingList",value:function(e,t){for(var r=8,i=8,n=0;n<e;n++)0!==i&&(i=(r+t.readEG()+256)%256),r=0===i?r:i}},{key:"readSPS",value:function(e){var t,r,i,n=new is(e),a=0,s=0,o=0,l=0,u=n.readUByte.bind(n),c=n.readBits.bind(n),d=n.readUEG.bind(n),h=n.readBoolean.bind(n),f=n.skipBits.bind(n),v=n.skipEG.bind(n),g=n.skipUEG.bind(n),p=this.skipScalingList.bind(this);u();var m=u();if(c(5),f(3),u(),g(),100===m||110===m||122===m||244===m||44===m||83===m||86===m||118===m||128===m){var y=d();if(3===y&&f(1),g(),g(),f(1),h())for(r=3!==y?8:12,i=0;i<r;i++)h()&&p(i<6?16:64,n)}g();var k=d();if(0===k)d();else if(1===k)for(f(1),v(),v(),t=d(),i=0;i<t;i++)v();g(),f(1);var E=d(),S=d(),T=c(1);0===T&&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*(E+1)-2*a-2*s),height:(2-T)*(S+1)*16-(T?2:4)*(o+l),pixelRatio:A}}}])}(rs),as=function(e){function t(){var e;s(this,t);for(var r=arguments.length,i=new Array(r),n=0;n<r;n++)i[n]=arguments[n];return(e=a(this,t,[].concat(i))).initVPS=null,e}return f(t,e),l(t,[{key:"parsePES",value:function(e,t,r,i){var n,a=this,s=this.parseNALu(e,r.data,i),o=this.VideoSample,l=!1;r.data=null;var u=function(e){return o=a.VideoSample=a.createVideoSample(e,r.pts,r.dts)};s.forEach(function(i,s){var c,d;if(a.startsNewAccessUnit(o,e,i,s)){a.pushAccessUnit(o,e);var h=i.type>=16&&i.type<=23;o=u(h),l=!1}switch(i.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:o||(o=u(!1)),o.frame=!0,n=!0;break;case 16:case 17:case 18:case 21:case 22:case 23:var f;if(n=!0,l)null!=(f=o)&&f.frame&&!o.key&&(a.pushAccessUnit(o,e),o=a.VideoSample=null);o||(o=u(!0)),o.key=!0,o.frame=!0;break;case 19:case 20:n=!0,null!=(c=o)&&c.frame&&!o.key&&(a.pushAccessUnit(o,e),o=a.VideoSample=null),o||(o=u(!0)),o.key=!0,o.frame=!0;break;case 39:n=!0,Wt(i.data,2,r.pts,t.samples);break;case 32:n=!0,e.vps||("object"!==R(e.params)&&(e.params={}),e.params=Ae(e.params,a.readVPS(i.data)),a.initVPS=i.data),e.vps=[i.data];break;case 33:if(n=!0,l=!0,void 0===e.vps||e.vps[0]===a.initVPS||void 0===e.sps||a.matchSPS(e.sps[0],i.data)||(a.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){var v=a.readSPS(i.data);for(var g in e.width=v.width,e.height=v.height,e.pixelRatio=v.pixelRatio,e.codec=v.codecString,e.sps=[],"object"!==R(e.params)&&(e.params={}),v.params)e.params[g]=v.params[g]}a.pushParameterSet(e.sps,i.data,e.vps),o||(o=u(!1));break;case 34:if(n=!0,"object"===R(e.params)){if(!e.pps){e.pps=[];var p=a.readPPS(i.data);for(var m in p)e.params[m]=p[m]}a.pushParameterSet(e.pps,i.data,e.vps)}break;case 35:n=!0,e.audFound=!0,null!=(d=o)&&d.frame&&(a.pushAccessUnit(o,e),o=null),o||(o=u(!1));break;default:n=!1}o&&n&&o.units.push(i)}),i&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}},{key:"pushParameterSet",value:function(e,t,r){(r&&r[0]===this.initVPS||!r&&!e.length)&&e.push(t)}},{key:"startsNewAccessUnit",value:function(e,t,r,i){if(!e)return!1;if(!t.audFound&&0===i)return!0;if(!e.frame)return!1;var n=r.type,a=r.data;return!!(n>=32&&n<=35||39===n||n>=41&&n<=44||n>=48&&n<=55)||n<=31&&a.length>2&&!!(128&a[2])}},{key:"getNALuType",value:function(e,t){return(126&e[t])>>>1}},{key:"ebsp2rbsp",value:function(e){for(var t=new Uint8Array(e.byteLength),r=0,i=0;i<e.byteLength;i++)i>=2&&3===e[i]&&0===e[i-1]&&0===e[i-2]||(t[r]=e[i],r++);return new Uint8Array(t.buffer,0,r)}},{key:"pushAccessUnit",value:function(e,r){A(t,"pushAccessUnit",this,3)([e,r]),this.initVPS&&(this.initVPS=null)}},{key:"readVPS",value:function(e){var t=new is(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 is(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);var r=t.readBits(3);t.readBoolean();for(var i=t.readBits(2),n=t.readBoolean(),a=t.readBits(5),s=t.readUByte(),o=t.readUByte(),l=t.readUByte(),u=t.readUByte(),c=t.readUByte(),d=t.readUByte(),h=t.readUByte(),f=t.readUByte(),v=t.readUByte(),g=t.readUByte(),p=t.readUByte(),m=[],y=[],k=0;k<r;k++)m.push(t.readBoolean()),y.push(t.readBoolean());if(r>0)for(var E=r;E<8;E++)t.readBits(2);for(var S=0;S<r;S++)m[S]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),y[S]&&t.readUByte();t.readUEG();var T=t.readUEG();3==T&&t.skipBits(1);var A=t.readUEG(),b=t.readUEG(),I=t.readBoolean(),R=0,L=0,P=0,w=0;I&&(R+=t.readUEG(),L+=t.readUEG(),P+=t.readUEG(),w+=t.readUEG());for(var C=t.readUEG(),D=t.readUEG(),_=t.readUEG(),M=t.readBoolean()?0:r;M<=r;M++)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 x=0;x<4;x++)for(var O=0;O<(3===x?2:6);O++){if(t.readBoolean()){var F=Math.min(64,1<<4+(x<<1));x>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,V=0;V<B;V++){var G=!1;if(0!==V&&(G=t.readBoolean()),G){V===B&&t.readUEG(),t.readBoolean(),t.readUEG();for(var H=0,K=0;K<=U;K++){var j=t.readBoolean(),q=!1;j||(q=t.readBoolean()),(j||q)&&H++}U=H}else{var W=t.readUEG(),Y=t.readUEG();U=W+Y;for(var z=0;z<W;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,re=!0,ie=1,ne=0;t.readBoolean(),t.readBoolean();if(t.readBoolean()){if(t.readBoolean()){var ae=t.readUByte();ae>0&&ae<16?(ee=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][ae-1],te=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][ae-1]):255===ae&&(ee=t.readBits(16),te=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean())t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte());if(t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean())if(ie=t.readBits(32),ne=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean()){var se=t.readBoolean(),oe=t.readBoolean(),le=!1;(se||oe)&&((le=t.readBoolean())&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),le&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(var ue=0;ue<=r;ue++){var ce=!1;(re=t.readBoolean())||t.readBoolean()?t.readEG():ce=t.readBoolean();var de=ce?1:t.readUEG()+1;if(se)for(var he=0;he<de;he++)t.readUEG(),t.readUEG(),le&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(oe)for(var fe=0;fe<de;fe++)t.readUEG(),t.readUEG(),le&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),Z=t.readUEG())}var ve=A,ge=b;if(I){var pe=1,me=1;1===T?pe=me=2:2==T&&(pe=2),ve=A-pe*L-pe*R,ge=b-me*w-me*P}for(var ye=i?["A","B","C"][i]:"",ke=s<<24|o<<16|l<<8|u,Ee=0,Se=0;Se<32;Se++)Ee=(Ee|(ke>>Se&1)<<31-Se)>>>0;var Te=Ee.toString(16);1===a&&"2"===Te&&(Te="6");var Ae=n?"H":"L";return{codecString:"hvc1.".concat(ye).concat(a,".").concat(Te,".").concat(Ae).concat(p,".B0"),params:{general_tier_flag:n,general_profile_idc:a,general_profile_space:i,general_profile_compatibility_flags:[s,o,l,u],general_constraint_indicator_flags:[c,d,h,f,v,g],general_level_idc:p,bit_depth:C+8,bit_depth_luma_minus8:C,bit_depth_chroma_minus8:D,min_spatial_segmentation_idc:Z,chroma_format_idc:T,frame_rate:{fixed:re,fps:ne/ie}},width:ve,height:ge,pixelRatio:[ee,te]}}},{key:"readPPS",value:function(e){var t=new is(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);var r=t.readBoolean(),i=t.readBoolean(),n=1;return i&&r?n=0:i?n=3:r&&(n=2),{parallelismType:n}}},{key:"matchSPS",value:function(e,t){return pt(e).substring(3)===pt(t).substring(3)}}])}(rs),ss=188,os=function(){function e(t,r,i,n){s(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._klvPid=-1,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.videoIntegrityChecker=null,this.observer=t,this.config=r,this.typeSupported=i,this.logger=n,this.videoParser=null}return l(e,[{key:"resetInitSegment",value:function(t,r,i,n,a,s){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=e.createTrack("video"),this._videoTrack.duration=n,this.videoIntegrityChecker="skip"===this.config.handleMpegTsVideoIntegrityErrors?new gs(this.logger):null,this._audioTrack=e.createTrack("audio",n),this._id3Track=e.createTrack("id3"),this._txtTrack=e.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=r,this.videoCodec=i,t&&this.demux(t,0,s,"SAMPLE-AES"===(null==a?void 0:a.method))}},{key:"resetTimeStamp",value:function(){}},{key:"resetContiguity",value:function(){var e=this._audioTrack,t=this._videoTrack,r=this._id3Track;e&&(e.pesData=null),t&&(t.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.remainderData=null}},{key:"demux",value:function(t,r,i){var n,a=arguments.length>3&&void 0!==arguments[3]&&arguments[3],s=arguments.length>4&&void 0!==arguments[4]&&arguments[4];a||(this.sampleAes=null);var o=this._videoTrack,l=this.videoIntegrityChecker,u=this._audioTrack,c=this._id3Track,d=this._txtTrack,h=i.iframe,f=o.pid,v=o.pesData,g=u.pid,p=c.pid,m=this._klvPid,y=u.pesData,k=c.pesData,E=null,S=null,T=this.pmtParsed,A=this._pmtId,b=t.length;if(this.remainderData&&(b=(t=Kt(this.remainderData,t)).length,this.remainderData=null),b<ss&&!s)return this.remainderData=t,{audioTrack:u,videoTrack:o,id3Track:c,textTrack:d};var I=Math.max(0,e.syncOffset(t));(b-=(b-I)%ss)<t.byteLength&&!s&&(this.remainderData=new Uint8Array(t.buffer,b,t.buffer.byteLength-b));for(var R=0,L=I;L<b;L+=ss)if(71===t[L]){var P=!!(64&t[L+1]),w=ls(t,L),C=void 0;if((48&t[L+3])>>4>1){if((C=L+5+t[L+4])===L+ss)continue}else C=L+4;switch(w){case f:P&&(!v||null!=l&&l.isCorrupted||!(n=fs(v,this.logger))||(this.readyVideoParser(o.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(o,d,n,!1,i)),v={data:[],size:0},null==l||l.reset(f)),null==l||l.handlePacket(t.subarray(L)),v&&(v.data.push(t.subarray(C,L+ss)),v.size+=L+ss-C);break;case g:if(h)break;if(P){if(y&&(n=fs(y,this.logger)))switch(u.segmentCodec){case"aac":this.parseAACPES(u,n,i);break;case"mp3":this.parseMPEGPES(u,n);break;case"ac3":this.parseAC3PES(u,n)}y={data:[],size:0}}y&&(y.data.push(t.subarray(C,L+ss)),y.size+=L+ss-C);break;case p:if(h)break;P&&(k&&(n=fs(k,this.logger))&&this.parseID3PES(c,n),k={data:[],size:0}),k&&(k.data.push(t.subarray(C,L+ss)),k.size+=L+ss-C);break;case m:if(h)break;P&&(E&&(n=fs(E,this.logger))&&this.parseKlvPES(c,n),E={data:[],size:0}),E&&(E.data.push(t.subarray(C,L+ss)),E.size+=L+ss-C);break;case 0:P&&(C+=t[C]+1),A=this._pmtId=us(t,C);break;case A:P&&(C+=t[C]+1);var D=cs(t,C,this.typeSupported,a,this.observer,this.logger,this.config,i);(f=D.videoPid)>0&&(o.pid=f,o.segmentCodec=D.segmentVideoCodec),(g=D.audioPid)>0&&(u.pid=g,u.segmentCodec=D.segmentAudioCodec),(p=D.id3Pid)>0&&(c.pid=p),(m=D.klvPid)>0&&(this._klvPid=m),null===S||T||(this.logger.warn("MPEG-TS PMT found at ".concat(L," after unknown PID '").concat(S,"'. Backtracking to sync byte @").concat(I," to parse all TS packets.")),S=null,L=I-188),T=this.pmtParsed=!0;break;case 17:case 8191:break;default:S=w}}else R++;R>0&&ds(this.observer,new Error("Found ".concat(R," TS packet/s that do not start with 0x47")),i,void 0,this.logger),o.pesData=v,u.pesData=y,c.pesData=k;var _={audioTrack:u,videoTrack:o,id3Track:c,textTrack:d};return s&&this.extractRemainingSamples(_,i),_}},{key:"flush",value:function(e,t){var r,i=this.remainderData;return this.remainderData=null,r=i?this.demux(i,0,t,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(r,t),this.sampleAes?this.decrypt(r,this.sampleAes):r}},{key:"extractRemainingSamples",value:function(e,t){var r,i=e.audioTrack,n=e.videoTrack,a=e.id3Track,s=e.textTrack,o=n.pesData,l=i.pesData,u=a.pesData,c=this.videoIntegrityChecker;if(!o||null!=c&&c.isCorrupted||!(r=fs(o,this.logger))?n.pesData=o:(this.readyVideoParser(n.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(n,s,r,!0,t),n.pesData=null)),l&&(r=fs(l,this.logger))){switch(i.segmentCodec){case"aac":this.parseAACPES(i,r,t);break;case"mp3":this.parseMPEGPES(i,r);break;case"ac3":this.parseAC3PES(i,r)}i.pesData=null}else null!=l&&l.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),i.pesData=l;u&&(r=fs(u,this.logger))?(this.parseID3PES(a,r),a.pesData=null):a.pesData=u}},{key:"demuxSampleAes",value:function(e,t,r,i){var n=this.demux(e,r,i,!0,!this.config.progressive),a=this.sampleAes=new Ya(this.observer,this.config,t);return this.decrypt(n,a)}},{key:"readyVideoParser",value:function(e){null===this.videoParser&&("avc"===e?this.videoParser=new ns:"hevc"===e&&(this.videoParser=new as))}},{key:"decrypt",value:function(e,t){return new Promise(function(r){var i=e.audioTrack,n=e.videoTrack;i.samples&&"aac"===i.segmentCodec?t.decryptAacSamples(i.samples,0,function(){n.samples?t.decryptAvcSamples(n.samples,0,0,function(){r(e)}):r(e)}):n.samples&&t.decryptAvcSamples(n.samples,0,0,function(){r(e)})})}},{key:"destroy",value:function(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0,this.videoIntegrityChecker=null}},{key:"parseAACPES",value:function(e,t,r){var i,n,a,s=0,o=this.aacOverFlow,l=t.data;if(o){this.aacOverFlow=null;var u=o.missing,c=o.sample.unit.byteLength;if(-1===u)l=Kt(o.sample.unit,l);else{var d=c-u;o.sample.unit.set(l.subarray(0,u),d),e.samples.push(o.sample),s=o.missing}}for(i=s,n=l.length;i<n-1&&!wa(l,i);i++);if(i!==s){var h,f=i<n-1;if(h=f?"AAC PES did not start with ADTS header,offset:".concat(i):"No ADTS header found in AAC PES",ds(this.observer,new Error(h),r,f,this.logger),!f)return}if(Da(e,this.observer,l,i,this.audioCodec),void 0!==t.pts)a=t.pts;else{if(!o)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");var v=_a(e.samplerate);a=o.sample.pts+v}for(var g,p=0;i<n;){if(i+=(g=Ma(e,l,i,a,p)).length,g.missing){this.aacOverFlow=g;break}for(p++;i<n-1&&!wa(l,i);i++);}}},{key:"parseMPEGPES",value:function(e,t){var r=t.data,i=r.length,n=0,a=0,s=t.pts;if(void 0!==s)for(;a<i;)if(qa(r,a)){var o=Ha(e,r,a,s,n);if(!o)break;a+=o.length,n++}else a++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}},{key:"parseAC3PES",value:function(e,t){var r=t.data,i=t.pts;if(void 0!==i)for(var n,a=r.length,s=0,o=0;o<a&&(n=$a(e,r,o,i,s++))>0;)o+=n;else this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS")}},{key:"parseID3PES",value:function(e,t){if(void 0!==t.pts){var r=Ae({},t,{type:this._videoTrack?xa.emsg:xa.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(r)}else this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS")}},{key:"parseKlvPES",value:function(e,t){var r,i=null!=(r=t.pts)?r:t.dts;if(void 0!==i){var n=t.data;if(n.length<16)this.logger.warn("[tsdemuxer]: KLV PES payload too short");else for(var a=0;a<n.length;){var s;if(a+16>n.length)break;var o=a;if((a+=16)>=n.length)break;var l=n[a];a+=1;var u=0;if(128&l){var c=127&l;if(0===c||c>4||a+c>n.length){this.logger.warn("[tsdemuxer]: Invalid KLV length encoding");break}for(var d=0;d<c;d++)u=u<<8|n[a+d];a+=c}else u=l;if(a+u>n.length){this.logger.warn("[tsdemuxer]: KLV value extends beyond PES payload");break}var h=a+u,f=n.subarray(o,h),v={data:f,len:f.byteLength,pts:i,dts:null!=(s=t.dts)?s:i,type:xa.misbklv,duration:Number.POSITIVE_INFINITY};e.samples.push(v),a=h}}else this.logger.warn("[tsdemuxer]: KLV PES unknown PTS and DTS")}}],[{key:"probe",value:function(t,r){var i=e.syncOffset(t);return i>0&&r.warn("MPEG2-TS detected but first sync word found @ offset ".concat(i)),-1!==i}},{key:"syncOffset",value:function(e){for(var t=e.length,r=Math.min(940,t-ss)+1,i=0;i<r;){for(var n=!1,a=-1,s=0,o=i;o<t;o+=ss){if(71!==e[o]||t-o!==ss&&71!==e[o+ss]){if(s)return-1;break}if(s++,-1===a&&0!==(a=o)&&(r=Math.min(a+18612,e.length-ss)+1),n||(n=0===ls(e,o)),n&&s>1&&(0===a&&s>2||o+ss>r))return a}i++}return-1}},{key:"createTrack",value:function(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:Et[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}}])}();function ls(e,t){return((31&e[t+1])<<8)+e[t+2]}function us(e,t){return(31&e[t+10])<<8|e[t+11]}function cs(e,t,r,i,n,a,s,o){var l={audioPid:-1,videoPid:-1,id3Pid:-1,klvPid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},u=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t<u;){var c=ls(e,t),d=(15&e[t+3])<<8|e[t+4];switch(e[t]){case 207:if(!i){hs("ADTS AAC",a);break}case 15:-1===l.audioPid&&(l.audioPid=c);break;case 21:-1===l.id3Pid&&(l.id3Pid=c);break;case 219:if(!i){hs("H.264",a);break}case 27:-1===l.videoPid&&(l.videoPid=c);break;case 3:case 4:r.mpeg||r.mp3?-1===l.audioPid&&(l.audioPid=c,l.segmentAudioCodec="mp3"):a.log("MPEG audio found, not supported in this browser");break;case 193:if(!i){hs("AC-3",a);break}case 129:r.ac3?-1===l.audioPid&&(l.audioPid=c,l.segmentAudioCodec="ac3"):a.log("AC-3 audio found, not supported in this browser");break;case 6:if(d>0)for(var h=t+5,f=d;f>2;){switch(e[h]){case 106:-1===l.audioPid&&(!0!==r.ac3?a.log("AC-3 audio found, not supported in this browser for now"):(l.audioPid=c,l.segmentAudioCodec="ac3"));break;case 5:-1===l.klvPid&&s.enableEmsgKLVMetadata&&(l.klvPid=c,a.log("KLV metadata PID found: ".concat(c)))}var v=e[h+1]+2;h+=v,f-=v}break;case 194:case 135:return ds(n,new Error("Unsupported EC-3 in M2TS found"),o,void 0,a),l;case 36:-1===l.videoPid&&(l.videoPid=c,l.segmentVideoCodec="hevc",a.log("HEVC in M2TS found"))}t+=d+5}return l}function ds(e,t,r,i,n){n.warn("parsing error: ".concat(t.message)),e.emit(ne.ERROR,ne.ERROR,{type:re.MEDIA_ERROR,details:ie.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,chunkMeta:r,error:t,reason:t.message})}function hs(e,t){t.log("".concat(e," with AES-128-CBC encryption found in unencrypted stream"))}function fs(e,t){var r,i,n,a,s,o=0,l=e.data;if(!e||0===e.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=Kt(l[0],l[1]),l.splice(1,1);if(1===((r=l[0])[0]<<16)+(r[1]<<8)+r[2]){if((i=(r[4]<<8)+r[5])&&i>e.size-6)return null;var u=r[7];192&u&&(a=536870912*(14&r[9])+4194304*(255&r[10])+16384*(254&r[11])+128*(255&r[12])+(254&r[13])/2,64&u?a-(s=536870912*(14&r[14])+4194304*(255&r[15])+16384*(254&r[16])+128*(255&r[17])+(254&r[18])/2)>54e5&&(t.warn("".concat(Math.round((a-s)/9e4),"s delta between PTS and DTS, align them")),a=s):s=a);var c=(n=r[8])+9;if(e.size<=c)return null;e.size-=c;for(var d=new Uint8Array(e.size),h=0,f=l.length;h<f;h++){var v=(r=l[h]).byteLength;if(c){if(c>v){c-=v;continue}r=r.subarray(c),v-=c,c=0}d.set(r,o),o+=v}return i&&(i-=n+3),{data:d,pts:a,dts:s,len:i}}return null}var vs,gs=function(){return l(function e(t){s(this,e),this.logger=void 0,this.pid=0,this.lastContinuityCounter=-1,this.integrityState="ok",this.logger=t},[{key:"isCorrupted",get:function(){return"ok"!==this.integrityState}},{key:"reset",value:function(e){this.pid=e,this.lastContinuityCounter=-1,this.integrityState="ok"}},{key:"handlePacket",value:function(e){if(!(e.byteLength<4)){var t=ls(e,0);if(t===this.pid){var r=(48&e[3])>>4;if(0!==r){var i=15&e[3],n=this.lastContinuityCounter;this.lastContinuityCounter=i;var a=!!(1&r);if(!(!!(2&r)&&0!=e[4]&&!!(128&e[5])||n<0)){var s=a?n+1&15:n;return i!==s?(this.logger.warn("MPEG-TS Continuity Counter check failed for PID='".concat(t,"', CC=").concat(i,", Expected-CC=").concat(s," Last-CC=").concat(n)),void(this.integrityState="cc-failed")):128&e[1]?(this.logger.warn("MPEG-TS Packet had TEI flag set for PID='".concat(t,"'")),void(this.integrityState="tei-bit")):void 0}}}else this.logger.debug("Packet PID mismatch, expected ".concat(this.pid," got ").concat(t))}}}])}(),ps=function(){return l(function e(){s(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])}}}])}(),ms={video: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]),audio: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])},ys=new Uint8Array([0,0,0,0,0,0,0,0]),ks=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Es=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Ss=new Uint8Array([0,0,0,0,0,0,0,0]),Ts=new Uint8Array([0,0,0,0,0,0,0,1]),As=new Uint8Array([105,115,111,109]),bs=new Uint8Array([97,118,99,49]),Is=new Uint8Array([0,0,0,1]),Rs=function(){function e(){s(this,e)}return l(e,null,[{key:"box",value:function(e){for(var t=8,r=arguments.length,i=new Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];for(var a=i.length,s=a;a--;)t+=i[a].byteLength;var o=new Uint8Array(t);for(Rt(o,0,t),Rt(o,4,e),a=0,t=8;a<s;a++)o.set(i[a],t),t+=i[a].byteLength;return o}},{key:"hdlr",value:function(t){return e.box(kt.hdlr,ms[t])}},{key:"mdat",value:function(t){return e.box(kt.mdat,t)}},{key:"mdhd",value:function(t,r){r*=t;var i=Math.floor(r/(yt+1)),n=Math.floor(r%(yt+1));return e.box(kt.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n,85,196,0,0]))}},{key:"mdia",value:function(t){return e.box(kt.mdia,e.mdhd(t.timescale||0,t.duration||0),e.hdlr(t.type),e.minf(t))}},{key:"mfhd",value:function(t){return e.box(kt.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(kt.minf,e.box(kt.smhd,Ss),e.DINF,e.stbl(t)):e.box(kt.minf,e.box(kt.vmhd,Es),e.DINF,e.stbl(t))}},{key:"moof",value:function(t,r,i){return e.box(kt.moof,e.mfhd(t),e.traf(i,r))}},{key:"moov",value:function(t){for(var r=t.length,i=[];r--;)i[r]=e.trak(t[r]);return e.box.apply(null,[kt.moov,e.mvhd(t[0].timescale||0,t[0].duration||0)].concat(i).concat(e.mvex(t)))}},{key:"mvex",value:function(t){for(var r=t.length,i=[];r--;)i[r]=e.trex(t[r]);return e.box.apply(null,[kt.mvex].concat(i))}},{key:"mvhd",value:function(t,r){r*=t;var i=Math.floor(r/(yt+1)),n=Math.floor(r%(yt+1)),a=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return e.box(kt.mvhd,a)}},{key:"sdtp",value:function(t){var r,i,n=t.samples||[],a=new Uint8Array(4+n.length);for(r=0;r<n.length;r++)i=n[r].flags,a[r+4]=i.dependsOn<<4|i.isDependedOn<<2|i.hasRedundancy;return e.box(kt.sdtp,a)}},{key:"stbl",value:function(t){return e.box(kt.stbl,e.stsd(t),e.box(kt.stts,ys),e.box(kt.stsc,ys),e.box(kt.stsz,ks),e.box(kt.stco,ys))}},{key:"avc1",value:function(t){var r,i,n,a=[],s=[];for(r=0;r<t.sps.length;r++)n=(i=t.sps[r]).byteLength,a.push(n>>>8&255),a.push(255&n),a=a.concat(Array.prototype.slice.call(i));for(r=0;r<t.pps.length;r++)n=(i=t.pps[r]).byteLength,s.push(n>>>8&255),s.push(255&n),s=s.concat(Array.prototype.slice.call(i));var o=e.box(kt.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(kt.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(kt.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(kt.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,r=t.length;return new Uint8Array([0,0,0,0,3,23+r,0,1,0,4,15+r,64,21,0,0,0,0,0,0,0,0,0,0,0,5,r].concat(b(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(kt.mp4a,e.audioStsd(t),e.box(kt.esds,e.esds(t)))}},{key:"mp3",value:function(t){return e.box(kt[".mp3"],e.audioStsd(t))}},{key:"ac3",value:function(t){return e.box(kt["ac-3"],e.audioStsd(t),e.box(kt.dac3,t.config))}},{key:"stsd",value:function(t){var r=t.segmentCodec;if("audio"===t.type){if("aac"===r)return e.box(kt.stsd,Ts,e.mp4a(t));if("ac3"===r&&t.config)return e.box(kt.stsd,Ts,e.ac3(t));if("mp3"===r&&"mp3"===t.codec)return e.box(kt.stsd,Ts,e.mp3(t))}else{if(!t.pps||!t.sps)throw new Error("video track missing pps or sps");if("avc"===r)return e.box(kt.stsd,Ts,e.avc1(t));if("hevc"===r&&t.vps)return e.box(kt.stsd,Ts,e.hvc1(t))}throw new Error("unsupported ".concat(t.type," segment codec (").concat(r,"/").concat(t.codec,")"))}},{key:"tkhd",value:function(t){var r=t.id,i=(t.duration||0)*(t.timescale||0),n=t.width||0,a=t.height||0,s=Math.floor(i/(yt+1)),o=Math.floor(i%(yt+1));return e.box(kt.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,r>>24&255,r>>16&255,r>>8&255,255&r,0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,o>>24,o>>16&255,o>>8&255,255&o,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,n>>8&255,255&n,0,0,a>>8&255,255&a,0,0]))}},{key:"traf",value:function(t,r){var i=e.sdtp(t),n=t.id,a=Math.floor(r/(yt+1)),s=Math.floor(r%(yt+1));return e.box(kt.traf,e.box(kt.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n])),e.box(kt.tfdt,new Uint8Array([1,0,0,0,a>>24,a>>16&255,a>>8&255,255&a,s>>24,s>>16&255,s>>8&255,255&s])),e.trun(t,i.length+16+20+8+16+8+8),i)}},{key:"trak",value:function(t){return t.duration=t.duration||4294967295,e.box(kt.trak,e.tkhd(t),e.mdia(t))}},{key:"trex",value:function(t){var r=t.id;return e.box(kt.trex,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}},{key:"trun",value:function(t,r){var i,n,a,s,o,l,u=t.samples||[],c=u.length,d=12+16*c,h=new Uint8Array(d);for(r+=8+d,h.set(["video"===t.type?1:0,0,15,1,c>>>24&255,c>>>16&255,c>>>8&255,255&c,r>>>24&255,r>>>16&255,r>>>8&255,255&r],0),i=0;i<c;i++)a=(n=u[i]).duration,s=n.size,o=n.flags,l=n.cts,h.set([a>>>24&255,a>>>16&255,a>>>8&255,255&a,s>>>24&255,s>>>16&255,s>>>8&255,255&s,o.isLeading<<2|o.dependsOn,o.isDependedOn<<6|o.hasRedundancy<<4|o.paddingValue<<1|o.isNonSync,61440&o.degradPrio,15&o.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*i);return e.box(kt.trun,h)}},{key:"initSegment",value:function(t){var r=e.moov(t);return Kt(e.FTYP,r)}},{key:"hvc1",value:function(t){for(var r=t.params,i=[t.vps,t.sps,t.pps],n=new Uint8Array([1,r.general_profile_space<<6|(r.general_tier_flag?32:0)|r.general_profile_idc,r.general_profile_compatibility_flags[0],r.general_profile_compatibility_flags[1],r.general_profile_compatibility_flags[2],r.general_profile_compatibility_flags[3],r.general_constraint_indicator_flags[0],r.general_constraint_indicator_flags[1],r.general_constraint_indicator_flags[2],r.general_constraint_indicator_flags[3],r.general_constraint_indicator_flags[4],r.general_constraint_indicator_flags[5],r.general_level_idc,240|r.min_spatial_segmentation_idc>>8,255&r.min_spatial_segmentation_idc,252|r.parallelismType,252|r.chroma_format_idc,248|r.bit_depth_luma_minus8,248|r.bit_depth_chroma_minus8,0,parseInt(r.frame_rate.fps),3|r.temporal_id_nested<<2|r.num_temporal_layers<<3|(r.frame_rate.fixed?64:0),i.length]),a=n.length,s=0;s<i.length;s+=1){a+=3;for(var o=0;o<i[s].length;o+=1)a+=2+i[s][o].length}var l=new Uint8Array(a);l.set(n,0),a=n.length;for(var u=i.length-1,c=0;c<i.length;c+=1){l.set(new Uint8Array([32+c|(c===u?128:0),0,i[c].length]),a),a+=3;for(var d=0;d<i[c].length;d+=1)l.set(new Uint8Array([i[c][d].length>>8,255&i[c][d].length]),a),a+=2,l.set(i[c][d],a),a+=i[c][d].length}var h=e.box(kt.hvcC,l),f=t.width,v=t.height,g=t.pixelRatio[0],p=t.pixelRatio[1];return e.box(kt.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(kt.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(kt.pasp,new Uint8Array([g>>24,g>>16&255,g>>8&255,255&g,p>>24,p>>16&255,p>>8&255,255&p])))}}])}();vs=Rs,Rs.FTYP=vs.box(kt.ftyp,As,Is,As,bs),Rs.DINF=vs.box(kt.dinf,vs.box(kt.dref,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1])));function Ls(e,t){var r=e*t*(arguments.length>2&&void 0!==arguments[2]?arguments[2]:1);return arguments.length>3&&void 0!==arguments[3]&&arguments[3]?Math.round(r):r}function Ps(e){return Ls(e,1e3,1/9e4,arguments.length>1&&void 0!==arguments[1]&&arguments[1])}function ws(e){var t=e.baseTime,r=e.timescale,i=e.trackId;return"".concat(t/r," (").concat(t,"/").concat(r,") trackId: ").concat(i)}var Cs=8589934592;function Ds(e,t,r,i){return{duration:t,size:r,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1,paddingValue:0}}}var _s=function(e){function t(e,r,i,n){var o;return s(this,t),(o=a(this,t,["mp4-remuxer",n])).observer=void 0,o.config=void 0,o.typeSupported=void 0,o.ISGenerated=!1,o._initPTS=null,o._initDTS=null,o.nextVideoTs=null,o.nextAudioTs=null,o.videoSampleDuration=null,o.isAudioContiguous=!1,o.isVideoContiguous=!1,o.videoTrackConfig=void 0,o.observer=e,o.config=r,o.typeSupported=i,o.ISGenerated=!1,o}return f(t,e),l(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?ws(t):t," > ").concat(e?ws(e):e)),this._initPTS=this._initDTS=e}},{key:"resetNextTimestamp",value:function(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}},{key:"resetInitSegment",value:function(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}},{key:"getVideoStartPts",value:function(e){var t=!1,r=e[0].pts,i=e.reduce(function(e,i){var n=i.pts,a=n-e;return a<-4294967296&&(t=!0,a=(n=Ms(n,r))-e),a>0?e:n},r);return t&&this.debug("PTS rollover detected"),i}},{key:"remux",value:function(e,t,r,i,n,a,s,o,l){var u,c,d,h,f,v,g=n,p=n,m=!l.iframe&&e.pid>-1,y=t.pid>-1,k=t.samples.length,E=e.samples.length>0,S=s&&k>0||k>1;if((!m||E)&&(!y||S)||this.ISGenerated||s){if(this.ISGenerated){var T,A,b,I,R=this.videoTrackConfig;(R&&(t.width!==R.width||t.height!==R.height||(null==(T=t.pixelRatio)?void 0:T[0])!==(null==(A=R.pixelRatio)?void 0:A[0])||(null==(b=t.pixelRatio)?void 0:b[1])!==(null==(I=R.pixelRatio)?void 0:I[1]))||!R&&S||null===this.nextAudioTs&&E)&&this.resetInitSegment()}this.ISGenerated||(d=this.generateIS(e,t,n,a));var L,P=this.isVideoContiguous,w=-1;if(S&&(w=function(e){for(var t=0;t<e.length;t++)if(e[t].key)return t;return-1}(t.samples),!P&&this.config.forceKeyFrameOnDiscontinuity))if(v=!0,w>0){this.warn("Dropped ".concat(w," out of ").concat(k," video samples due to a missing keyframe"));var C=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(w),t.dropped+=w,L=p+=(t.samples[0].pts-C)/t.inputTimeScale}else-1===w&&(this.warn("No keyframe found out of ".concat(k," video samples")),v=!1);if(this.ISGenerated){if(E&&S&&n){var D=this.getVideoStartPts(t.samples),_=(Ms(e.samples[0].pts,D)-D)/t.inputTimeScale;g+=Math.max(0,_),p+=Math.max(0,-_)}if(E){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),d=this.generateIS(e,t,n,a)),c=this.remuxAudio(e,g,this.isAudioContiguous,a,y||S||o===de.AUDIO?p:void 0,l),S){var M=c?c.endPTS-c.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),d=this.generateIS(e,t,n,a)),u=this.remuxVideo(t,p,P,M,l)}}else S&&(u=this.remuxVideo(t,p,P,0,l));u&&(u.firstKeyFrame=w,u.independent=-1!==w,u.firstKeyFramePTS=L)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(f=xs(r,n,this._initPTS,this._initDTS)),i.samples.length&&(h=Os(i,n,this._initPTS))),{audio:c,video:u,initSegment:d,independent:v,text:h,id3:f}}},{key:"computeInitPts",value:function(e,t,r,i){var n=Math.round(r*t),a=Ms(e,n);if(a<n)for(this.log("Adjusting PTS for rollover in timeline near ".concat((n-a)/t," ").concat(i));a<n;)a+=Cs;return a-n}},{key:"generateIS",value:function(e,t,r,i){var n,a,s,o=e.samples,l=t.samples,u=this.typeSupported,c={},d=this._initPTS,h=!d||i,f="audio/mp4",v=-1;if(h&&(n=a=1/0),e.config&&o.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":u.mpeg?(f="audio/mpeg",e.codec=""):u.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}if(c.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&u.mpeg?new Uint8Array(0):Rs.initSegment([e]),metadata:{channelCount:e.channelCount}},h){v=e.id,s=e.inputTimeScale;var g=this.computeInitPts(o[0].pts,s,r,"audio");(!d||s!==d.timescale||0===r&&g<d.baseTime)&&(n=a=g)}}if(t.sps&&t.pps&&l.length){if(t.timescale=t.inputTimeScale,c.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:Rs.initSegment([t]),metadata:{width:t.width,height:t.height}},h){v=t.id,s=t.inputTimeScale;var p=this.getVideoStartPts(l),m=Ms(l[0].dts,p),y=this.computeInitPts(m,s,r,"video"),k=this.computeInitPts(p,s,r,"video");(!d||s!==d.timescale||Z(n)||0===r&&k<d.baseTime)&&(a=Math.min(a,y),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&&Z(n)?(d&&this.warn("Timestamps at playlist time: ".concat(i?"":"~").concat(r," ").concat(n/s," != initPTS: ").concat(d.baseTime/d.timescale," (").concat(d.baseTime,"/").concat(d.timescale,") trackId: ").concat(d.trackId)),this.log("Found initPTS at playlist time: ".concat(r," offset: ").concat(n/s," (").concat(n,"/").concat(s,") trackId: ").concat(v)),this._initPTS={baseTime:n,timescale:s,trackId:v},this._initDTS={baseTime:a,timescale:s,trackId:v}):n=s=void 0,{tracks:c,initPTS:n,timescale:s,trackId:v}}},{key:"remuxVideo",value:function(e,t,r,i,n){var a,s,o=e.inputTimeScale,l=e.samples,u=[],c=l.length,d=this._initPTS,h=d.baseTime*o/d.timescale,f=this.nextVideoTs,v=8,g=this.videoSampleDuration,p=Number.POSITIVE_INFINITY,m=Number.NEGATIVE_INFINITY,y=!1;if(!r||null===f){var k=h+t*o,E=l[0].pts-Ms(l[0].dts,l[0].pts);ir()&&null!==f&&Math.abs(k-E-(f+h))<15e3?r=!0:f=k-E-h}for(var S=f+h,T=0;T<c;T++){var A=l[T];A.pts=Ms(A.pts,S),A.dts=Ms(A.dts,S),A.dts<l[T>0?T-1:T].dts&&(y=!0)}y&&l.sort(function(e,t){var r=e.dts-t.dts,i=e.pts-t.pts;return r||i}),a=l[0].dts;var b=(s=l[l.length-1].dts)-a,I=b?Math.round(b/(c-1)):g||e.inputTimeScale/30;if(r){var R=a-S,L=R>I,P=R<-1;if((L||P)&&(L?this.warn("".concat((e.segmentCodec||"").toUpperCase(),": ").concat(Ps(R,!0)," ms (").concat(R,"dts) hole between fragments detected at ").concat(t.toFixed(3))):this.warn("".concat((e.segmentCodec||"").toUpperCase(),": ").concat(Ps(-R,!0)," ms (").concat(R,"dts) overlapping between fragments detected at ").concat(t.toFixed(3))),!P||S>=l[0].pts||ir())){a=S;var w=l[0].pts-R;if(L)l[0].dts=a,l[0].pts=w;else for(var C=!0,D=0;D<l.length&&!(l[D].dts>w&&C);D++){var _=l[D].pts;if(l[D].dts-=R,l[D].pts-=R,D<l.length-1){var M=l[D+1].pts;C=M<=l[D].pts==M<=_}}this.log("Video: Initial PTS/DTS adjusted: ".concat(Ps(w,!0),"/").concat(Ps(a,!0),", delta: ").concat(Ps(R,!0)," ms"))}}for(var x=0,O=0,F=a=Math.max(0,a),N=0;N<c;N++){for(var B=l[N],U=B.units,V=U.length,G=0,H=0;H<V;H++)G+=U[H].data.length;O+=G,x+=V,B.length=G,B.dts<F?(B.dts=F,F+=I/4|0||1):F=B.dts,p=Math.min(B.pts,p),m=Math.max(B.pts,m)}s=l[c-1].dts;var K,j=O+4*x+8;try{K=new Uint8Array(j)}catch(e){return void this.observer.emit(ne.ERROR,ne.ERROR,{type:re.MUX_ERROR,details:ie.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:n,error:e,bytes:j,reason:"fail allocating video mdat ".concat(j)})}Rt(K,0,j),Rt(K,4,kt.mdat);for(var q=!1,W=Number.POSITIVE_INFINITY,Y=Number.POSITIVE_INFINITY,z=Number.NEGATIVE_INFINITY,X=Number.NEGATIVE_INFINITY,Q=0;Q<c;Q++){for(var $=l[Q],J=$.units,Z=0,ee=0,te=J.length;ee<te;ee++){var ae=J[ee],se=ae.data,oe=ae.data.byteLength;Rt(K,v,oe),v+=4,K.set(se,v),v+=oe,Z+=4+oe}var le=void 0;if(Q<c-1)g=l[Q+1].dts-$.dts,le=l[Q+1].pts-$.pts;else{var ue=this.config,ce=Q>0?$.dts-l[Q-1].dts:I;if(le=Q>0?$.pts-l[Q-1].pts:I,ue.stretchShortVideoTrack&&null!==this.nextAudioTs){var de=Math.floor(ue.maxBufferHole*o),he=(i?p+i*o:this.nextAudioTs+h)-$.pts;he>de?((g=he-ce)<0?g=ce:q=!0,this.log("It is approximately ".concat(he/90," ms to the next segment; using duration ").concat(g/90," ms for the last video frame."))):g=ce}else g=ce}var fe=Math.round($.pts-$.dts);if(W=Math.min(W,g),z=Math.max(z,g),Y=Math.min(Y,le),X=Math.max(X,le),!r&&0===Q&&fe>g){var ve=Math.round(fe/I)*I;ve-fe===1&&(this.log("pad first CTS ".concat(fe," -> ").concat(ve," of sn: ").concat(n.sn)),fe=ve)}u.push(Ds($.key,g,Z,fe))}if(u.length){var ge=ir();if(ge){if(ge<70){var pe=u[0].flags;pe.dependsOn=2,pe.isNonSync=0}}else if(function(){if(void 0===Zt){var e=er.match(/Safari\/(\d+)/i);Zt=e?parseInt(e[1]):0}return Zt}()&&X-Y<z-W&&I/z<.025&&0===u[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");for(var me=a,ye=0,ke=u.length;ye<ke;ye++){var Ee=me+u[ye].duration,Se=me+u[ye].cts;if(ye<ke-1){var Te=Ee+u[ye+1].cts;u[ye].duration=Te-Se}else u[ye].duration=ye?u[ye-1].duration:I;u[ye].cts=0,me=Ee}}}var be=s+(g=q||!g?I:g);this.nextVideoTs=f=be-h,this.videoSampleDuration=g,this.isVideoContiguous=!0,n.iframe&&(1===u.length?(u[0].duration=g=n.duration*o,this.nextVideoTs=f=a+g-h):this.warn("Not adjusting IFrame duration (sample count ".concat(u.length,")")));var Ie={data1:Rs.moof(n.sn,a,Ae(e,{samples:u})),data2:K,startPTS:(p-h)/o,endPTS:(m+g-h)/o,startDTS:(a-h)/o,endDTS:f/o,type:"video",hasAudio:!1,hasVideo:!0,nb:u.length,dropped:e.dropped};return e.samples=[],e.dropped=0,Ie}},{key:"getSamplesPerFrame",value:function(e){switch(e.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}},{key:"remuxAudio",value:function(e,t,r,i,n,a){var s=e.inputTimeScale,o=s/(e.samplerate?e.samplerate:s),l=this.getSamplesPerFrame(e),u=l*o,c=this._initPTS,d="mp3"===e.segmentCodec&&this.typeSupported.mpeg,h=[],f=void 0!==n,v=e.samples,g=d?0:8,p=this.nextAudioTs||-1,m=c.baseTime*s/c.timescale,y=m+t*s;if(this.isAudioContiguous=r=r||v.length&&p>0&&(i&&Math.abs(y-(p+m))<9e3||Math.abs(Ms(v[0].pts,y)-(p+m))<20*u),v.forEach(function(e){e.pts=Ms(e.pts,y)}),!r||p<0){var k=v.length;if(v=v.filter(function(e){return e.pts>=0}),k!==v.length&&this.warn("Removed ".concat(v.length-k," of ").concat(k," samples (initPTS ").concat(m," / ").concat(s,")")),!v.length)return;p=0===n?0:i&&!f?Math.max(0,y-m):v[0].pts-m}if("aac"===e.segmentCodec)for(var E=this.config.maxAudioFramesDrift,S=0,T=p+m;S<v.length;S++){var A=v[S],b=A.pts,I=b-T,R=Math.abs(1e3*I/s);if(I<=-E*u&&f)0===S&&(this.warn("Audio frame @ ".concat((b/s).toFixed(3),"s overlaps marker by ").concat(Math.round(1e3*I/s)," ms.")),this.nextAudioTs=p=b-m,T=b);else if(I>=E*u&&R<1e4&&f){var L=Math.round(I/u);for(T=b-L*u;T<0&&L&&u;)L--,T+=u;0===S&&(this.nextAudioTs=p=T-m),this.warn("Injecting ".concat(L," audio frames @ ").concat(((T-m)/s).toFixed(3),"s due to ").concat(Math.round(1e3*I/s)," ms gap."));for(var P=0;P<L;P++){var w=ps.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=A.unit.subarray()),v.splice(S,0,{unit:w,pts:T}),T+=u,S++}}A.pts=T,T+=u}for(var C,D=null,_=null,M=0,x=v.length;x--;)M+=v[x].unit.byteLength;for(var O=0,F=v.length;O<F;O++){var N=v[O],B=N.unit,U=N.pts;if(null!==_){h[O-1].duration=Math.round((U-_)/o)}else{if(r&&"aac"===e.segmentCodec&&(U=p+m),D=U,!(M>0))return;M+=g;try{C=new Uint8Array(M)}catch(e){return void this.observer.emit(ne.ERROR,ne.ERROR,{type:re.MUX_ERROR,details:ie.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:a,error:e,bytes:M,reason:"fail allocating audio mdat ".concat(M)})}d||(Rt(C,0,M),Rt(C,4,kt.mdat))}C&&C.set(B,g);var V=B.byteLength;g+=V,h.push(Ds(!0,l,V,0)),_=U}var G=h.length;if(G){var H=h[h.length-1];p=_-m,this.nextAudioTs=p+o*H.duration;var K=d?new Uint8Array(0):Rs.moof(e.sequenceNumber++,D/o,Ae({},e,{samples:h}));e.samples=[];var j=(D-m)/s,q=this.nextAudioTs/s,W={data1:K,data2:C,startPTS:j,endPTS:q,startDTS:j,endDTS:q,type:"audio",hasAudio:!0,hasVideo:!1,nb:G};return this.isAudioContiguous=!0,W}}}])}(Be);function Ms(e,t){var r;if(null===t)return e;for(r=t<e?-8589934592:Cs;Math.abs(e-t)>4294967296;)e+=r;return e}function xs(e,t,r,i){var n=e.samples.length;if(n){for(var a=e.inputTimeScale,s=0;s<n;s++){var o=e.samples[s];o.pts=Ms(o.pts-r.baseTime*a/r.timescale,t*a)/a,o.dts=Ms(o.dts-i.baseTime*a/i.timescale,t*a)/a}var l=e.samples;return e.samples=[],{samples:l}}}function Os(e,t,r){var i=e.samples.length;if(i){for(var n=e.inputTimeScale,a=0;a<i;a++){var s=e.samples[a];s.pts=Ms(s.pts-r.baseTime*n/r.timescale,t*n)/n}e.samples.sort(function(e,t){return e.pts-t.pts});var o=e.samples;return e.samples=[],{samples:o}}}var Fs,Ns=function(e){function t(e,r,i,n){var o;return s(this,t),(o=a(this,t,["passthrough-remuxer",n])).observer=void 0,o.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.videoOnlyRemux=!1,o.decryptdata=null,o.pendingInitSegment=void 0,o.observer=e,o}return f(t,e),l(t,[{key:"destroy",value:function(){this.observer&&this.observer.removeAllListeners(),this.observer=null}},{key:"resetTimeStamp",value:function(e){this.lastEndTime=null;var t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}},{key:"resetNextTimestamp",value:function(){this.isVideoContiguous=!1,this.lastEndTime=null}},{key:"resetInitSegment",value:function(e,t,r,i){this.audioCodec=t,this.videoCodec=r,this.decryptdata=i,this.pendingInitSegment=e,this.videoOnlyRemux=!1,this.initTracks=void 0,this.initData=void 0,this.emitInitSegment=!0}},{key:"generateInitSegment",value:function(e,t,r){this.videoOnlyRemux=!1;var i=this.audioCodec,n=this.videoCodec;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);var a=this.initData=r||Mt(e),s=a.audio,o=a.video;if(t)!function(e,t){if(e&&t){var r=t.keyId;16===(null==r?void 0:r.byteLength)&&t.isCommonEncryption&&Ut(e,function(e,t){var i=e.subarray(8,24);i.some(function(e){return 0!==e})||(je.log("[eme] Patching keyId in 'enc".concat(t?"a":"v",">sinf>>tenc' box: ").concat(ft(i)," -> ").concat(ft(r))),e.set(r,8))})}}(e,t);else{var l=s||o;null!=l&&l.encrypted&&this.warn('Init segment with encrypted track with has no key ("'.concat(l.codec,'")!'))}s&&(i=Us(s,he,this)),o&&(n=Us(o,fe,this));var u={};s&&o?u.audiovideo={container:"video/mp4",codec:i+","+n,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:s?u.audio={container:"audio/mp4",codec:i,encrypted:s.encrypted,initSegment:e,id:"audio"}:o?u.video={container:"video/mp4",codec:n,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=u}},{key:"remux",value:function(e,t,r,i,n,a,s,o,l,u,c){var d,h,f=this.initPTS,v=this.lastEndTime,g={audio:void 0,video:void 0,text:void 0,id3:r,initSegment:void 0};Z(v)||(v=this.lastEndTime=n||0);var p=t.samples;if(!p.length)return g;var m=this.pendingInitSegment;m&&(this.pendingInitSegment=void 0,this.generateInitSegment(m,this.decryptdata,u));var y={initPTS:void 0,timescale:void 0,trackId:void 0},k=this.initData;if(null!=(d=k)&&d.length||(this.generateInitSegment(p),k=this.initData),null==(h=k)||!h.length)return this.warn("Failed to generate initSegment."),g;if(l.iframe&&k.audio&&k.video){var E,S,T=null==(E=this.initTracks)||null==(E=E.audiovideo)?void 0:E.initSegment,A=T?function(e){var t=Ct(e,["moov"]);if(1!==t.length||Ct(e,["moof"]).length)return null;for(var r=e.byteOffset,i=[],n=[],a=!1,s=Ct(t[0],["trak"]),o=0;o<s.length;o++){var l=s[o],u=Ct(l,["mdia","hdlr"])[0];if("vide"!==(u?pt(u.subarray(8,12)):"")){var c=Ct(l,["tkhd"])[0];if(!c)return null;var d=c[0];n.push(Tt(c,0===d?12:20)),i.push(Pt(l,r))}else a=!0}if(!a||!i.length)return null;var h=Ct(t[0],["mvex"])[0],f=0;if(h)for(var v=Ct(h,["trex"]),g=0;g<v.length;g++){var p=v[g];-1!==n.indexOf(Tt(p,4))&&(i.push(Pt(p,r)),f+=p.byteLength+8)}var m=wt(e,i),y=m.result,k=m.dropped,E=m.droppedBefore;if(Rt(y,t[0].byteOffset-r-8,t[0].byteLength+8-k),h&&f){var S=h.byteOffset-r-8;Rt(y,S-E(S),h.byteLength+8-f)}return y}(T):null;if(A)this.log("Converted muxed init segment to video-only for I-Frame playback"),this.generateInitSegment(A,this.decryptdata),null!=(S=this.initData)&&S.length&&(k=this.initData,this.emitInitSegment=!0,this.videoOnlyRemux=!0)}this.emitInitSegment&&(y.tracks=this.initTracks,g.initSegment=y,this.emitInitSegment=!1);var I=l.iframe,R=!c||I&&!c.includeSampleDetails?function(e,t,r,i){return Ht(e,t,i,!(arguments.length>4&&void 0!==arguments[4])||arguments[4])}(p,k,l,this,I):c.tracks,L=k.audio?R[k.audio.id]:null,P=k.video?R[k.video.id]:null,w=!!k.audio,C=!!k.video,D="";w&&(D+="audio"),C&&(D+="video");var _,M=Bs(P,1/0),x=Bs(L,1/0),O=Bs(P,0,!0),F=Bs(L,0,!0),N=0;P&&L&&k.audio&&(x>O||M>F)&&this.warn("audio and video track sample timestamps do not overlap. v: ".concat(M,"-").concat(O," a: ").concat(x,"-").concat(F,"}"),P,L);var B=!!L&&(!P||!f&&x<M||!!f&&f.trackId===k.audio.id),U=B?L:P;if(!U)return this.log("No media samples found in ".concat(o," ").concat(l.level," ").concat(-1===l.part?"":"part: ".concat(l.part," of")," sn: ").concat(l.sn," at playlist time: ").concat(n)),g;var V,G=p;if(P&&P.sampleCount>=1&&k.video&&l.iframe){var H,K=P.trun,j=P.start,q=1===K.length,W=K.length?q?K[0].samples:(H=K[0].samples).concat.apply(H,b(K.slice(1).map(function(e){return e.samples}))):[];if(W.length){for(var Y=K[0],z=Y,X=K.length;X--;)if(K[X].samples.length){z=K[X];break}var Q=z.lastSampleDurationOffset,$=Y.defaultSampleDurationOffset,J=Math.abs(l.duration-(O-M))>.05,ee=W.length<P.sampleCount;if(J||ee||this.videoOnlyRemux||!q){var te=ee?z.sampleOffset+z.samples.reduce(function(e,t){return e+t.size},0):void 0,re=J?l.duration:O-M,ie=function(e,t,r,i){if(void 0!==r){for(var n=e[e.length-1],a=t,s=0;s<e.length-1;s++)a-=e[s].duration;return a<=0&&(a=n.duration),n.duration=a,{durationOffset:r,value:a}}if(void 0===i)return;for(var o=Math.round(t/e.length),l=0;l<e.length;l++)e[l].duration=o;return{durationOffset:i,value:o}}(W,re*k.video.timescale,Q,$),ne=function(e,t,r,i,n){if(r<1)return null;var a=Ct(e,["moof"]);if(1!==a.length)return null;for(var s=a[0],o=e.byteOffset,l=[],u=[],c=Ct(s,["traf"]),d=!0,h=0;h<c.length;h++){var f=c[h],v=Ct(f,["tfhd"])[0];if(!v)return null;Tt(v,4)===t?(l.push(f),131072&Tt(v,0)||(d=!1)):u.push(Pt(f,o))}if(!l.length)return null;if(u.length&&!d)return null;if(void 0!==i){for(var g=r,p=0;p<l.length;p++){for(var m=l[p],y=0,k=Ct(m,["trun"]),E=0;E<k.length;E++){var S=k[E],T=Math.min(g,Tt(S,4));if(T){Rt(e,S.byteOffset-o+4,T);var A=16777215&Tt(S,0);Lt(e,S,8+(1&A?4:0)+(4&A?4:0)+T*((256&A?4:0)+(512&A?4:0)+(1024&A?4:0)+(2048&A?4:0)))}else Rt(e,S.byteOffset-o-4,kt.free);g-=T,y+=T}var b=Ct(m,["senc"])[0];b&&Rt(e,b.byteOffset-o+4,y);var I=Ct(m,["saiz"])[0];if(I){var R=4;1&(I[1]<<16|I[2]<<8|I[3])&&(R+=8);var L=I[R];R+=1,Rt(e,I.byteOffset-o+R,y),Lt(e,I,R+4+(0===L?y:0))}}var P=Ct(e,["mdat"]);if(1===P.length){var w=P[0].byteOffset-o-8;Rt(e,w,i-w)}}var C=e,D=0,_=function(){return 0};if(u.length){var M=wt(e,u);C=M.result,D=M.dropped,_=M.droppedBefore,Rt(C,s.byteOffset-o-8,s.byteLength+8-D);for(var x=0;x<l.length;x++){for(var O=l[x],F=_(O.byteOffset-o),N=Ct(O,["trun"]),B=0;B<N.length;B++){var U=N[B];1&Tt(U,0)&&Rt(C,U.byteOffset-o-F+8,Tt(U,8)-D)}if(F)for(var V=Ct(O,["saio"]),G=0;G<V.length;G++){var H=V[G],K=0===H[0]?4:8,j=1&Tt(H,0)?12:4,q=Tt(H,j);for(j+=4;q--;j+=K){var W=j+K-4;Rt(C,H.byteOffset-o-F+W,Tt(H,W)-F)}}}}if(n){var Y=n.durationOffset,z=n.value;Rt(C,Y-_(Y),z)}return void 0!==i?C.subarray(0,i-D):C}(p,k.video.id,W.length,te,ie);ne?(G=ne,V=function(e,t){for(var r=e,i=e,n=0;n<t.length;n++){var a=t[n],s=a.cts,o=a.duration;i=Math.max(i,r+(s||0)+o),r+=o}return i}(j,W)):this.warn("IFrame remux skipped (sn ".concat(l.sn,"); using native sample duration")),N=ne&&ie?re:O-M}else N=O-M}else this.warn("Could not remux IFrame track fragment (no samples in range, trun count ".concat(K.length,")")),N=O-M}else N=B?F-x:O-M;if(this.videoOnlyRemux&&G===p)return this.warn("Dropping muxed I-Frame fragment that could not be remuxed to video-only (sn: ".concat(l.sn,")")),g;var ae=U.timescale,se=U.start-n*ae,oe=B?k.audio.id:k.video.id;if(_=U.start/ae,(a||!f)&&(function(e,t,r,i){if(null===e)return!0;var n=Math.max(i,1),a=t-e.baseTime/e.timescale;return Math.abs(a-r)>=n}(f,_,n,N)||ae!==f.timescale)){var le=!1,ue=B?"audio":"video";if(f){var ce=0!==n?_/n:1+_/1;le=_>=0&&Math.abs(1-ce)<.001,this.log("".concat(ue," timestamps in track ").concat(oe," at playlist time: ").concat(a?"":"~").concat(n," maps to ").concat(_," with initPTS: ").concat(f.baseTime/f.timescale," (").concat(se/ae-f.baseTime/f.timescale,"s diff) (").concat(D,") drift estimate: ").concat(ce," ").concat(le?"(ignoring drift)":"remapping timestamps (initPTS)"))}le||(this.log("Found initPTS in ".concat(ue," track ").concat(oe," at playlist time: ").concat(n," offset: ").concat(_-n," (").concat(se,"/").concat(ae,")")),f=null,y.initPTS=se,y.timescale=ae,y.trackId=oe)}f?(y.initPTS=f.baseTime,y.timescale=f.timescale,y.trackId=f.trackId):(y.timescale&&void 0!==y.trackId&&void 0!==y.initPTS||(this.warn("Could not set initPTS"),y.initPTS=_,y.timescale=1,y.trackId=-1),this.initPTS=f={baseTime:y.initPTS,timescale:y.timescale,trackId:y.trackId});var de=_-f.baseTime/f.timescale,he=de+N,fe=C&&void 0!==(null==U?void 0:U.ptsMin)?U.ptsMin/U.timescale-f.baseTime/f.timescale:de,ve=void 0!==V&&P?V/P.timescale-f.baseTime/f.timescale:C&&null!=U&&U.ptsMax?U.ptsMax/U.timescale-f.baseTime/f.timescale:he;N>0?this.lastEndTime=he:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());var ge={data1:G,data2:void 0,startPTS:fe,startDTS:de,endPTS:ve,endDTS:he,type:D,hasAudio:w,hasVideo:C,nb:1,dropped:0,encrypted:!!k.audio&&k.audio.encrypted||!!k.video&&k.video.encrypted};g.audio=w&&!C?ge:void 0,g.video=C?ge:void 0;var pe=this.isVideoContiguous,me=null==P?void 0:P.sampleCount;if(me){var ye=P.keyFrameIndex,ke=-1!==ye;ge.nb=me,ge.dropped=0===ye||pe?0:ke?ye:me,ge.independent=ke,ge.firstKeyFrame=ye,ke&&P.keyFrameStart&&(ge.firstKeyFramePTS=(P.keyFrameStart-f.baseTime)/f.timescale),pe||(g.independent=ke),this.isVideoContiguous||(this.isVideoContiguous=ke),ge.dropped&&this.warn("fmp4 does not start with IDR: firstIDR ".concat(ye,"/").concat(me," dropped: ").concat(ge.dropped," start: ").concat(ge.firstKeyFramePTS||"NA"))}return g.initSegment=y,g.id3=xs(r,n,f,f),i.samples.length&&(g.text=Os(i,n,f)),g}}])}(Be);function Bs(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return void 0!==(null==e?void 0:e.start)?(e.start+(r?e.duration:0))/e.timescale:t}function Us(e,t,r){var i=e.codec;if(i&&i.length>4)return i;if(t===he){if("ec-3"===i||"ac-3"===i||"alac"===i)return i;if("fLaC"===i||"Opus"===i){return vr(i,!1)}return r.warn('Unhandled audio codec "'.concat(i,'" in mp4 MAP')),i||"mp4a"}return"mjpg"===i?i:(r.warn('Unhandled video codec "'.concat(i,'" in mp4 MAP')),i||"avc1")}try{Fs=self.performance.now.bind(self.performance)}catch(e){Fs=Date.now}var Vs=[{demux:es,remux:Ns},{demux:os,remux:_s},{demux:za,remux:_s},{demux:Ja,remux:_s}];Vs.splice(2,0,{demux:Qa,remux:_s});var Gs=function(){return l(function e(t,r,i,n,a,o){s(this,e),this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=t,this.typeSupported=r,this.config=i,this.id=a,this.logger=o},[{key:"configure",value:function(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}},{key:"push",value:function(e,t,r,i){var n=this;if(!this.observer)return Hs(r);var a=r.transmuxing;a.executeStart=Fs();var s=new Uint8Array(e),o=this.currentTransmuxState,l=this.transmuxConfig;i&&(this.currentTransmuxState=i);var u=i||o,c=u.contiguous,d=u.discontinuity,h=u.trackSwitch,f=u.accurateTimeOffset,v=u.timeOffset,g=u.initSegmentChange,p=l.audioCodec,m=l.videoCodec,y=l.defaultInitPts,k=l.duration,E=l.initSegmentData,S=function(e,t){var r=null;e.byteLength>0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(r=t);return r}(s,t);if(S&&Zi(S.method)){var T=this.getDecrypter(),A=en(S.method);return this.asyncResult=!0,this.decryptionPromise=T.decrypt(s,S.key.buffer,S.iv.buffer,A,r.decryptRange).then(function(e){var t=n.push(e,null,r);return n.decryptionPromise=null,t}),this.decryptionPromise}var b=this.needsProbing(d,h);if(b){var I=r.iframe&&E&&os.probe(E,this.logger)?E:s,R=this.configureTransmuxer(I);if(R)return this.logger.warn("[transmuxer] ".concat(R.message)),this.observer.emit(ne.ERROR,ne.ERROR,{type:re.MEDIA_ERROR,details:ie.FRAG_PARSING_ERROR,fatal:!1,error:R,reason:R.message}),a.executeEnd=Fs(),Hs(r)}(d||h||g||b)&&this.resetInitSegment(E,p,m,k,t,r),(d||g||b)&&this.resetInitialTimestamp(y),c||this.resetContiguity();var L=this.transmux(s,S,v,f,r);this.asyncResult=Ks(L);var P=this.currentTransmuxState;return P.contiguous=!0,P.discontinuity=!1,P.trackSwitch=!1,a.executeEnd=Fs(),L}},{key:"flush",value:function(e){var t=this,r=e.transmuxing;r.executeStart=Fs();var i=this.decrypter,n=this.currentTransmuxState,a=this.decryptionPromise;if(a)return this.asyncResult=!0,a.then(function(){return t.flush(e)});var s=[],o=n.timeOffset;if(i){var l=i.flush();l&&s.push(this.push(l.buffer,null,e))}var u=this.demuxer,c=this.remuxer;if(!u||!c){r.executeEnd=Fs();var d=[Hs(e)];return this.asyncResult?Promise.resolve(d):d}var h=u.flush(o,e);return Ks(h)?(this.asyncResult=!0,h.then(function(r){return t.flushRemux(s,r,e),s})):(this.flushRemux(s,h,e),this.asyncResult?Promise.resolve(s):s)}},{key:"flushRemux",value:function(e,t,r){if(this.remuxer){var i=t.audioTrack,n=t.videoTrack,a=t.id3Track,s=t.textTrack,o=this.currentTransmuxState,l=o.accurateTimeOffset,u=o.timeOffset;this.logger.log("[transmuxer.ts]: Flushed ".concat(this.id," sn: ").concat(r.sn).concat(r.part>-1?" part: "+r.part:""," of ").concat(this.id," playlist ").concat(r.level));var c=this.remuxer.remux(i,n,a,s,u,l,!0,this.id,r,t.initData,t.sampleData);e.push({remuxResult:c,chunkMeta:r}),r.transmuxing.executeEnd=Fs()}}},{key:"resetInitialTimestamp",value:function(e){var t=this.demuxer,r=this.remuxer;t&&r&&(t.resetTimeStamp(e),r.resetTimeStamp(e))}},{key:"resetContiguity",value:function(){var e=this.demuxer,t=this.remuxer;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())}},{key:"resetInitSegment",value:function(e,t,r,i,n,a){var s=this.demuxer,o=this.remuxer;s&&o&&(s.resetInitSegment(e,t,r,i,n,a),o.resetInitSegment(e,t,r,n))}},{key:"destroy",value:function(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0),this.observer&&this.observer.removeAllListeners(),this.decryptionPromise=null,this.decrypter=this.observer=void 0,this.logger=this.config=this.probe=void 0}},{key:"transmux",value:function(e,t,r,i,n){return"SAMPLE-AES"===(null==t?void 0:t.method)?this.transmuxSampleAes(e,t,r,i,n):this.transmuxUnencrypted(e,r,i,n)}},{key:"transmuxUnencrypted",value:function(e,t,r,i){var n=this.demuxer,a=this.remuxer;if(!n||!a)return Hs(i);var s=n.demux(e,t,i,!1,!this.config.progressive),o=s.audioTrack,l=s.videoTrack,u=s.id3Track,c=s.textTrack;return{remuxResult:a.remux(o,l,u,c,t,r,!1,this.id,i,s.initData,s.sampleData),chunkMeta:i}}},{key:"transmuxSampleAes",value:function(e,t,r,i,n){var a=this;return this.demuxer?this.demuxer.demuxSampleAes(e,t,r,n).then(function(e){return{remuxResult:a.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,r,i,!1,a.id,n,e.initData,e.sampleData),chunkMeta:n}}):Promise.reject(new Error("no demuxer"))}},{key:"configureTransmuxer",value:function(e){var t=this.config,r=this.observer,i=this.typeSupported;if(r){var n;try{for(var a=0,s=Vs.length;a<s;a++){var o;if(null!=(o=Vs[a].demux)&&o.probe(e,this.logger)){n=Vs[a];break}}}catch(e){return e}if(!n)return new Error("Failed to find demuxer by probing fragment data");var l=this.demuxer,u=this.remuxer,c=n.demux,d=n.remux;l&&l instanceof c||(this.logger.log("Using ".concat(c.name)),this.demuxer=new c(r,t,i,this.logger),this.probe=c.probe),u&&u instanceof d||(this.logger.log("Using ".concat(d.name)),this.remuxer=new d(r,t,i,this.logger))}}},{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 Pi(this.config)),e}}])}();var Hs=function(e){return{remuxResult:{},chunkMeta:e}};function Ks(e){return"then"in e&&e.then instanceof Function}var js=l(function e(t,r,i,n,a){s(this,e),this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=t,this.videoCodec=r,this.initSegmentData=i,this.duration=n,this.defaultInitPts=a||null}),qs=l(function e(t,r,i,n,a,o){s(this,e),this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=t,this.contiguous=r,this.accurateTimeOffset=i,this.trackSwitch=n,this.timeOffset=a,this.initSegmentChange=o}),Ws=0,Ys=function(){return l(function e(t,r,i,n){var a=this;s(this,e),this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Ws++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=function(e){var t=e.data,r=a.hls;if(r&&null!=t&&t.event&&t.instanceNo===a.instanceNo)switch(t.event){case"init":var i,n=null==(i=a.workerContext)?void 0:i.objectURL;n&&self.URL.revokeObjectURL(n);break;case"transmuxComplete":a.handleTransmuxComplete(t.data);break;case"flush":a.onFlush(t.data);break;case"workerLog":r.logger[t.data.logType]&&r.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=a.frag,t.data.part=a.part,t.data.id=a.id,r.trigger(t.event,t.data)}},this.onWorkerError=function(e){if(a.hls){var t=new Error("".concat(e.message," (").concat(e.filename,":").concat(e.lineno,")"));a.hls.config.enableWorker=!1,a.hls.logger.warn('Error in "'.concat(a.id,'" Web Worker, fallback to inline')),a.hls.trigger(ne.ERROR,{type:re.OTHER_ERROR,details:ie.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:t})}};var o=t.config;this.hls=t,this.id=r,this.useWorker=!!o.enableWorker,this.onTransmuxComplete=i,this.onFlush=n;var l=function(e,t){(t=t||{}).frag=a.frag||void 0,e===ne.ERROR&&(t.parent=a.id,t.part=a.part,a.error=t.error),a.hls.trigger(e,t)};this.observer=new Aa,this.observer.on(ne.FRAG_DECRYPTED,l),this.observer.on(ne.ERROR,l);var u=yr(o.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){var c=this.hls.logger;if(o.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{o.workerPath?(c.log("loading Web Worker ".concat(o.workerPath,' for "').concat(r,'"')),this.workerContext=function(e){var t=Ia[e];if(t)return t.clientCount++,t;var r=new self.URL(e,self.location.href).href,i={worker:new self.Worker(r),scriptURL:r,clientCount:1};return Ia[e]=i,i}(o.workerPath)):(c.log('injecting Web Worker for "'.concat(r,'"')),this.workerContext=function(){var e=Ia[ba];if(e)return e.clientCount++,e;var t=new self.Blob(["var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(".concat(__HLS_WORKER_BUNDLE__.toString(),")(true);")],{type:"text/javascript"}),r=self.URL.createObjectURL(t),i={worker:new self.Worker(r),objectURL:r,clientCount:1};return Ia[ba]=i,i}());var d=this.workerContext.worker;d.addEventListener("message",this.onWorkerMessage),d.addEventListener("error",this.onWorkerError),d.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:u,id:r,config:Nr(o)})}catch(e){c.warn('Error setting up "'.concat(r,'" Web Worker, fallback to inline'),e),this.terminateWorker(),this.error=null,this.transmuxer=new Gs(this.observer,u,o,"",r,t.logger)}return}}this.transmuxer=new Gs(this.observer,u,o,"",r,t.logger)},[{key:"reset",value:function(){if(this.frag=null,this.part=null,this.workerContext){var e=this.instanceNo;this.instanceNo=Ws++;var t=this.hls.config,r=yr(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:r,id:this.id,config:Nr(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=Ia[e||ba];if(t&&1===t.clientCount--){var r=t.worker,i=t.objectURL;delete Ia[e||ba],i&&self.URL.revokeObjectURL(i),r.terminate()}}(this.hls.config.workerPath)}}},{key:"destroy",value:function(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{var e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}var t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}},{key:"push",value:function(e,t,r,i,n,a,s,o,l,u){var c,d,h=this;l.transmuxing.start=self.performance.now();var f=this.instanceNo,v=this.transmuxer,g=a?a.start:n.start,p=n.decryptdata,m=this.frag,y=!m||n.cc!==m.cc,k=!m||l.level!==m.level,E=m?l.sn-m.sn:-1,S=this.part?l.part-this.part.index:-1,T=0===E&&l.id>1&&l.id===(null==m?void 0:m.stats.chunkCount),A=!k&&(1===E||0===E&&(1===S||T&&S<=0)),b=self.performance.now();(k||E||0===n.stats.parsing.start)&&(n.stats.parsing.start=b),!a||!S&&A||(a.stats.parsing.start=b);var I=!(m&&(null==(c=n.initSegment)?void 0:c.url)===(null==(d=m.initSegment)?void 0:d.url)),R=new qs(y,A,o,k,g,I);if(!A||y||I){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," playlist: ").concat(l.level," id: ").concat(l.id,"\n discontinuity: ").concat(y,"\n trackSwitch: ").concat(k,"\n contiguous: ").concat(A,"\n accurateTimeOffset: ").concat(o,"\n timeOffset: ").concat(g,"\n initSegmentChange: ").concat(I));var L=new js(r,i,t,s,u);this.configureTransmuxer(L)}if(this.frag=n,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:p,chunkMeta:l,state:R},e instanceof ArrayBuffer?[e]:[]);else if(v){var P=v.push(e,p,l,R);Ks(P)?P.then(function(e){h.handleTransmuxComplete(e)}).catch(function(e){h.transmuxerError(e,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(P)}}},{key:"flush",value:function(e){var t=this;e.transmuxing.start=self.performance.now();var r=this.instanceNo,i=this.transmuxer;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:r,cmd:"flush",chunkMeta:e});else if(i){var n=i.flush(e);Ks(n)?n.then(function(r){t.handleFlushResult(r,e)}).catch(function(r){t.transmuxerError(r,e,"transmuxer-interface flush error")}):this.handleFlushResult(n,e)}}},{key:"transmuxerError",value:function(e,t,r){this.hls&&(this.error=e,this.hls.trigger(ne.ERROR,{type:re.MEDIA_ERROR,details:ie.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:r}))}},{key:"handleFlushResult",value:function(e,t){var r=this;e.forEach(function(e){r.handleTransmuxComplete(e)}),this.onFlush(t)}},{key:"configureTransmuxer",value:function(e){var t=this.instanceNo,r=this.transmuxer;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):r&&r.configure(e)}},{key:"handleTransmuxComplete",value:function(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}])}(),zs=function(e){function t(e,r,i){var n;return s(this,t),(n=a(this,t,[e,r,i,"audio-stream-controller",de.AUDIO])).mainAnchor=null,n.mainFragLoading=null,n.audioOnly=!1,n.bufferedTrack=null,n.switchingTrack=null,n.trackId=-1,n.nextTrackId=-1,n.waitingData=null,n.mainDetails=null,n.flushing=!1,n.bufferFlushed=!1,n.cachedTrackLoadedData=null,n.registerListeners(),n}return f(t,e),l(t,[{key:"onHandlerDestroying",value:function(){this.unregisterListeners(),A(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(){A(t,"registerListeners",this,3)([]);var e=this.hls;e.on(ne.LEVEL_LOADED,this.onLevelLoaded,this),e.on(ne.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(ne.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(ne.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(ne.BUFFER_RESET,this.onBufferReset,this),e.on(ne.BUFFER_CREATED,this.onBufferCreated,this),e.on(ne.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(ne.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(ne.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(ne.FRAG_LOADING,this.onFragLoading,this),e.on(ne.FRAG_BUFFERED,this.onFragBuffered,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(A(t,"unregisterListeners",this,3)([]),e.off(ne.LEVEL_LOADED,this.onLevelLoaded,this),e.off(ne.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(ne.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(ne.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(ne.BUFFER_RESET,this.onBufferReset,this),e.off(ne.BUFFER_CREATED,this.onBufferCreated,this),e.off(ne.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(ne.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(ne.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(ne.FRAG_LOADING,this.onFragLoading,this),e.off(ne.FRAG_BUFFERED,this.onFragBuffered,this))}},{key:"onInitPtsFound",value:function(e,t){var r=t.frag,i=t.id,n=t.initPTS,a=t.timescale,s=t.trackId,o=t.timestampOffsets;if(i===de.MAIN){var l=r.cc,u=this.fragCurrent;if(this.initPTS=o,this.log("InitPTS for cc: ".concat(l," found from main: ").concat(n/a," (").concat(n,"/").concat(a,") trackId: ").concat(s)),this.mainAnchor=r,this.state===va){var c=this.waitingData;(!c&&!this.loadingParts||c&&c.frag.cc!==l)&&this.syncWithAnchor(r,null==c?void 0:c.frag)}else!this.hls.hasEnoughToStart&&u&&u.cc!==l?(u.abortRequests(),this.syncWithAnchor(r,u)):this.state===aa&&this.tick()}}},{key:"getLoadPosition",value:function(){var e;return!this.startFragRequested&&this.nextLoadPosition>=0&&!1!==(null==(e=this.switchingTrack)?void 0:e.flushImmediate)?this.nextLoadPosition:A(t,"getLoadPosition",this,3)([])}},{key:"syncWithAnchor",value:function(e,t){var r,i=(null==(r=this.mainFragLoading)?void 0:r.frag)||null;if(!t||(null==i?void 0:i.cc)!==t.cc){var n=(i||e).cc,a=Zr(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===aa&&this.doTickIdle())}}},{key:"startLoad",value:function(e,t){if(!this.levels)return this.startPosition=e,void(this.state=na);var r=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),r>0&&-1===e&&!t&&this.initPTS.length&&(this.log("Override startPosition with lastCurrentTime @".concat(r.toFixed(3))),e=r),this.state=aa,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,t||this.fragmentTracker.hasFragments(this.playlistType)||(this.startFragRequested=!1),this.tick()}},{key:"doTick",value:function(){switch(this.state){case aa:this.doTickIdle();break;case ua:var e=this.levels,r=this.trackId,i=null==e?void 0:e[r],n=null==i?void 0:i.details;if(n&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(n))break;this.state=va}break;case la:this.checkRetryDate();break;case va: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=oa;var d={frag:s,part:o,payload:l.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(d),u&&A(t,"_handleFragmentLoadComplete",this,3)([d])}else c&&c.cc!==a.frag.cc&&this.syncWithAnchor(c,a.frag)}else this.state=aa}this.onTickEnd()}},{key:"resetLoadingState",value:function(){var e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),A(t,"resetLoadingState",this,3)([])}},{key:"onTickEnd",value:function(){var e=this.media;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime,this.checkFragmentChanged())}},{key:"doTickIdle",value:function(){var e,t=this.hls,r=this.levels,i=this.media,n=this.trackId,a=t.config;if(this.buffering&&(i||this.primaryPrefetch||!this.startFragRequested&&a.startFragPrefetch)&&null!=r&&r[n]){var s=r[n],o=s.details;if(!o||this.waitForLive(s)||this.waitForCdnTuneIn(o))return this.state=ua,void(this.startFragRequested=!1);var l=this.getBufferOutput();this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,he));var u=this.getFwdBufferInfo();if(null!==u){if(!this.switchingTrack&&this._streamEnded(u,o))return t.trigger(ne.BUFFER_EOS,{type:"audio"}),void(this.state=ha);var c=u.len,d=t.maxBufferLength,h=o.fragments,f=h[0].start,v=this.getLoadPosition(),g=this.flushing||this.switchingTrack&&!this.switchingTrack.flushImmediate?v:u.end;if(this.switchingTrack&&i){var p=v;o.PTSKnown&&p<f&&p>=this.timelineOffset&&(u.end>f||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track ".concat(p," -> ").concat(f," + 0.05")),i.currentTime=f+.05)}if(!(c>=d&&!this.switchingTrack&&g<h[h.length-1].start)){var m=this.getNextFragment(g,o);if(m&&this.isLoopLoading(m,g)&&(m=this.getNextFragmentLoopLoading(m,o,u,de.MAIN,d)),m){if(!this.exceedsMaxBuffer(u,d,m)){var y=(null==(e=this.mainFragLoading)?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&y&&pe(m)&&!m.endList&&(!o.live||!this.loadingParts&&g<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(y)===yi&&(this.mainFragLoading=y=null),y&&pe(y))){if(m.start>y.end){var k=this.fragmentTracker.getFragAtPos(g,de.MAIN);k&&k.end>y.end&&(y=k,this.mainFragLoading={frag:k,targetBufferTime:null})}if(m.start>y.end)return}this.loadFragment(m,s,g)}}else this.bufferFlushed=!0}}}}},{key:"onMediaDetaching",value:function(e,r){this.bufferFlushed=this.flushing=!1,A(t,"onMediaDetaching",this,3)([e,r])}},{key:"onAudioTracksUpdated",value:function(e,t){var r=t.audioTracks;this.resetTransmuxer(),this.levels=r.map(function(e){return new xr(e)})}},{key:"onAudioTrackSwitching",value:function(e,t){var r=!!t.url;this.trackId=t.id;var i=this.fragCurrent;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),r?(this.switchingTrack=t,t.flushImmediate||(this.nextTrackId=t.id,this.nextLevelSwitch()),this.flushAudioIfNeeded(t),this.state!==na&&(this.setInterval(100),this.state=aa,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}},{key:"onManifestLoading",value:function(){A(t,"onManifestLoading",this,3)([]),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}},{key:"onLevelLoaded",value:function(e,t){this.mainDetails=t.details;var r=this.cachedTrackLoadedData;r&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(ne.AUDIO_TRACK_LOADED,r))}},{key:"onAudioTrackLoaded",value:function(e,t){var r,i=this.levels,n=t.details,a=t.id,s=t.groupId,o=t.track;if(i){var l=this.mainDetails;if(!l||n.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=t,void(this.state!==na&&(this.state=ua));this.cachedTrackLoadedData=null,this.log("Audio track ".concat(a,' "').concat(o.name,'" of "').concat(s,'" loaded [').concat(n.startSN,",").concat(n.endSN,"]").concat(n.lastPartSn?"[part-".concat(n.lastPartSn,"-").concat(n.lastPartIndex,"]"):"",",duration:").concat(n.totalduration));var u=i[a],c=0;if(n.live||null!=(r=u.details)&&r.live){if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;var d;if(u.details)c=this.alignPlaylists(n,u.details,null==(d=this.levelLastLoaded)?void 0:d.details);n.alignedSliding||(ea(l,n,this),c=n.fragmentStart)}u.details=n,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(l,c),this.hls.trigger(ne.AUDIO_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.state!==ua||this.waitForCdnTuneIn(n)||(this.state=aa),this.tick()}else this.warn("Audio tracks reset while loading track ".concat(a,' "').concat(o.name,'" of "').concat(s,'"'))}},{key:"_handleFragmentLoadProgress",value:function(e){var t,r=e.frag,i=e.part,n=e.payload,a=this.config,s=this.trackId,o=this.levels;if(o){var l=o[s];if(l){var u=l.details;if(!u)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(r.start);var c=a.defaultAudioCodec||l.audioCodec||"mp4a.40.2",d=this.transmuxer;d||(d=this.transmuxer=new Ys(this.hls,de.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));var h=this.initPTS[r.cc],f=null==(t=r.initSegment)?void 0:t.data;if(void 0!==h){var v=i?i.index:-1,g=-1!==v,p=new Fi(r.level,r.sn,r.stats.chunkCount,n.byteLength,v,g,r.duration);d.push(n,f,c,"",r,i,u.totalduration,!1,p,h)}else{this.log("Unknown video PTS for cc ".concat(r.cc,", waiting for video PTS before demuxing audio frag ").concat(r.sn," of [").concat(u.startSN," ,").concat(u.endSN,"],track ").concat(s)),(this.waitingData=this.waitingData||{frag:r,part:i,cache:new ka,complete:!1}).cache.push(new Uint8Array(n)),this.state!==na&&(this.state=va)}}else this.warn("Audio track is undefined on fragment load progress")}else this.warn("Audio tracks were reset while fragment load was in progress. Fragment ".concat(r.sn," of level ").concat(r.level," will not be buffered"))}},{key:"_handleFragmentLoadComplete",value:function(e){this.waitingData?this.waitingData.complete=!0:A(t,"_handleFragmentLoadComplete",this,3)([e])}},{key:"onBufferReset",value:function(){this.mediaBuffer=null}},{key:"onBufferCreated",value:function(e,t){this.bufferFlushed=this.flushing=!1;var r=t.tracks.audio;r&&(this.mediaBuffer=r.buffer||null)}},{key:"onFragLoading",value:function(e,t){!this.audioOnly&&t.frag.type===de.MAIN&&pe(t.frag)&&(this.mainFragLoading=t,this.state===aa&&this.tick())}},{key:"onFragBuffered",value:function(e,t){var r=t.frag,i=t.part;if(r.type===de.AUDIO)if(this.fragContextChanged(r))this.warn("Fragment ".concat(r.sn).concat(i?" p: "+i.index:""," of level ").concat(r.level," finished buffering, but was aborted. state: ").concat(this.state,", audioSwitch: ").concat(this.switchingTrack?this.switchingTrack.name:"false"));else{if(pe(r)){var n=this.switchingTrack;n&&(this.bufferedTrack=n)}this.fragBufferedComplete(r,i),this.media&&this.tick()}else this.audioOnly||r.type!==de.MAIN||r.elementaryStreams.video||r.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}},{key:"getFwdBufferInfo",value:function(){var e=this.getBufferOutput();return A(t,"getFwdBufferInfo",this,3)([e,de.AUDIO])}},{key:"getBufferOutput",value:function(){return this.mediaBuffer?this.mediaBuffer:this.media}},{key:"checkFragmentChanged",value:function(){var e=this.fragPlaying;if(!this.checkFragPlaying())return!1;var t=this.fragPlaying,r=null==e?void 0:e.level;return t&&t.level===r||(e&&this.cleanupBackBuffer(),this.switchingTrack&&this.completeAudioSwitch(this.switchingTrack)),!0}},{key:"onError",value:function(e,r){var i;if(r.fatal)this.state=fa;else switch(r.details){case ie.FRAG_GAP:case ie.FRAG_PARSING_ERROR:case ie.FRAG_DECRYPT_ERROR:case ie.FRAG_LOAD_ERROR:case ie.FRAG_LOAD_TIMEOUT:case ie.KEY_LOAD_ERROR:case ie.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(de.AUDIO,r);break;case ie.AUDIO_TRACK_LOAD_ERROR:case ie.AUDIO_TRACK_LOAD_TIMEOUT:case ie.LEVEL_PARSING_ERROR:r.levelRetry||this.state!==ua||(null==(i=r.context)?void 0:i.type)!==ce.AUDIO_TRACK||(this.state=aa);break;case ie.BUFFER_APPEND_NO_PROGRESS:if("audio"!==r.parent)return;r.frag&&(r.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn("Marking fragment ".concat(r.frag.sn," of track ").concat(r.frag.level," as a gap after ").concat(r.appendsWithoutProgress," appends without buffered range growth, to prevent loop loading")),this.fragmentTracker.addAsGap(r.frag));break;case ie.BUFFER_ADD_CODEC_ERROR:case ie.BUFFER_APPEND_ERROR:if("audio"!==r.parent)return;this.reduceLengthAndFlushBuffer(r)||this.resetLoadingState();break;case ie.BUFFER_FULL_ERROR:if("audio"!==r.parent)return;this.reduceLengthAndFlushBuffer(r)&&(this.bufferedTrack=null,A(t,"flushMainBuffer",this,3)([0,Number.POSITIVE_INFINITY,"audio"]));break;case ie.INTERNAL_EXCEPTION:this.recoverWorkerError(r)}}},{key:"onBufferFlushing",value:function(e,t){t.type!==fe&&(this.flushing=!0)}},{key:"onBufferFlushed",value:function(e,t){var r=t.type;if(r!==fe){this.flushing=!1,this.bufferFlushed=!0,this.state===ha&&(this.state=aa);var i=this.getBufferOutput();i&&(this.afterBufferFlushed(i,r),this.tick())}}},{key:"_handleTransmuxComplete",value:function(e){var r,i="audio",n=this.hls,a=e.remuxResult,s=e.chunkMeta,o=this.getCurrentContext(s);if(o){var l=o.frag,u=o.part,c=o.level,d=c.details,h=a.audio,f=a.text,v=a.id3,g=a.initSegment;if(this.fragContextChanged(l)||!d)return this.fragmentTracker.removeFragment(l),void(null!=g&&g.tracks&&this.resetTransmuxer());if(this.state=ca,h&&this.switchingTrack&&!this.switchingTrack.flushImmediate){var p=this.config.nextAudioTrackBufferFlushForwardOffset,m=Math.max(this.getLoadPosition()+p,l.start);A(t,"flushMainBuffer",this,3)([m,Number.POSITIVE_INFINITY,de.AUDIO])}if(null!=g&&g.tracks){var y=l.initSegment||l;if(this.unhandledEncryptionError(g,l))return;this._bufferInitSegment(c,g.tracks,y,s),n.trigger(ne.FRAG_PARSING_INIT_SEGMENT,{frag:y,id:i,tracks:g.tracks})}if(h){var k=h.startPTS,E=h.endPTS,S=h.startDTS,T=h.endDTS;u&&(u.elementaryStreams[he]={startPTS:k,endPTS:E,startDTS:S,endDTS:T}),l.setElementaryStreamInfo(he,k,E,S,T),this.bufferFragmentData(h,l,u,s)}if(null!=v&&null!=(r=v.samples)&&r.length){var b=Ae({id:i,frag:l,details:d},v);n.trigger(ne.FRAG_PARSING_METADATA,b)}if(f){var I=Ae({id:i,frag:l,details:d},f);n.trigger(ne.FRAG_PARSING_USERDATA,I)}}else this.resetWhenMissingContext(s)}},{key:"_bufferInitSegment",value:function(e,t,r,i){if(this.state===ca&&(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,t.audio)){var n=t.audio;n.id=de.AUDIO;var a=e.audioCodec;this.log("Init audio buffer, container:".concat(n.container,", codecs[level/parsed]=[").concat(a,"/").concat(n.codec,"]")),1===(null==a?void 0:a.split(",").length)&&(n.levelCodec=a),this.hls.trigger(ne.BUFFER_CODECS,t);var s=n.initSegment;if(null!=s&&s.byteLength){var o={type:"audio",frag:r,part:null,chunkMeta:i,parent:r.type,data:s};this.hls.trigger(ne.BUFFER_APPENDING,o)}this.tickImmediate()}}},{key:"loadFragment",value:function(e,r,i){var n,a=this.fragmentTracker.getState(e);if(this.switchingTrack||a===gi||a===mi)if(null!=(n=r.details)&&n.live&&!this.initPTS[e.cc]){this.log("Waiting for video PTS in continuity counter ".concat(e.cc," of live stream before loading audio fragment ").concat(e.sn," of level ").concat(this.trackId)),this.state=va;var s=this.mainDetails;s&&s.fragmentStart!==r.details.fragmentStart&&ea(s,r.details,this)}else A(t,"loadFragment",this,3)([e,r,i]);else this.clearTrackerIfNeeded(e)}},{key:"flushAudioIfNeeded",value:function(e){if(this.media&&this.bufferedTrack&&e.flushImmediate){var r=this.bufferedTrack;Hr({name:r.name,lang:r.lang,assocLang:r.assocLang,characteristics:r.characteristics,audioCodec:r.audioCodec,channels:r.channels},e,Kr)||(qr(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),A(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.bufferedTrack=e,this.switchingTrack=null,t.trigger(ne.AUDIO_TRACK_SWITCHED,Ie({},e))}},{key:"nextAudioTrack",get:function(){return this.nextTrackId}}])}(pa),Xs=function(e){function t(e,r){var i;return s(this,t),(i=a(this,t,[r,e.logger])).hls=void 0,i.canLoad=!1,i.timer=-1,i.loadingSync=!1,i.hls=e,i}return f(t,e),l(t,[{key:"destroy",value:function(){this.clearTimer(),this.hls=null}},{key:"clearTimer",value:function(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}},{key:"startLoad",value:function(){this.canLoad=!0,this.loadPlaylist()}},{key:"stopLoad",value:function(){this.canLoad=!1,this.clearTimer()}},{key:"switchParams",value:function(e,t,r){var i=null==t?void 0:t.renditionReports;if(i){for(var n=-1,a=0;a<i.length;a++){var s=i[a],o=void 0;try{o=new self.URL(s.URI,t.url).href}catch(e){this.warn("Could not construct new URL for Rendition Report: ".concat(e)),o=s.URI||""}if(o===e){n=a;break}o===e.substring(0,o.length)&&(n=a)}if(-1!==n){var l=i[n],u=parseInt(l["LAST-MSN"])||t.lastPartSn,c=parseInt(l["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){var d=Math.min(t.age-t.partTarget,t.targetduration);c>=0&&d>t.partTarget&&(c+=1)}var h=r&&_r(r);return new Mr(u,c>=0?c:void 0,h)}}}},{key:"loadPlaylist",value:function(e){this.clearTimer()}},{key:"loadingPlaylist",value:function(e,t){this.clearTimer()}},{key:"shouldLoadPlaylist",value:function(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}},{key:"getUrlWithDirectives",value:function(e,t){if(t)try{return t.addDirectives(e)}catch(e){this.warn("Could not construct new URL with HLS Delivery Directives: ".concat(e))}return e}},{key:"playlistLoaded",value:function(e,t,r){var i=t.details,n=t.stats,a=i.fragments,s=self.performance.now(),o=n.loading.first?Math.max(0,Math.floor(s-n.loading.first)):0;i.advancedDateTime=Date.now()-o;var l=this.hls.config.timelineOffset;if(l!==i.appliedTimelineOffset){var u=Math.max(l||0,0);i.appliedTimelineOffset=u,a.forEach(function(e){null==e||e.setStart(e.playlistOffset+u)})}if(i.live||null!=r&&r.live){var c,d="levelInfo"in t?t.levelInfo:t.track;i.reloaded(r);var h=null==(c=a[a.length-1])?void 0:c.type;if(i.misses>=this.hls.config.liveMaxUnchangedPlaylistRefresh){var f=new Error("".concat(h," playlist ").concat(d.id," hit max allowed unchanged reloads."));this.warn(f);var v=t.networkDetails,g=t.context;return void this.hls.trigger(ne.ERROR,{type:re.NETWORK_ERROR,details:ie.PLAYLIST_UNCHANGED_ERROR,fatal:!1,url:i.url,error:f,reason:f.message,level:t.level,parent:h,context:g,networkDetails:v,stats:n})}if(r){Gn(r,i,this);var p=i.playlistParsingError;if(p){this.warn(p);var m=this.hls;if(!m.config.ignorePlaylistParsingErrors){var y=t.networkDetails;return void m.trigger(ne.ERROR,{type:re.NETWORK_ERROR,details:ie.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:p,reason:p.message,level:t.level,parent:h,networkDetails:y,stats:n})}i.playlistParsingError=null}}-1===i.requestScheduled&&(i.requestScheduled=n.loading.start);var k=this.hls.mainForwardBufferInfo,E=k?k.end-k.len:0,S=jn(i,1e3*(i.edge-E));i.requestScheduled+S<s?i.requestScheduled=s:i.requestScheduled<=s&&(i.requestScheduled+=S);var T,A=t.deliveryDirectives;if(this.log("live playlist ".concat(e," ").concat(i.advanced?"REFRESHED ".concat(i.lastPartSn," - ").concat(i.lastPartIndex):i.updated?"UPDATED":"MISSED (received ".concat(i.lastPartSn," - ").concat(i.lastPartIndex).concat(A?" | requested ".concat(A.msn," - ").concat(A.part):"",")"))),!this.canLoad||!i.live)return;var b=void 0,I=void 0;if(i.canBlockReload&&i.advanced){var R=this.hls.config.lowLatencyMode,L=i.lastPartSn,P=i.endSN,w=i.lastPartIndex,C=L===P;-1!==w?C?(b=P+1,I=R?0:w):(b=L,I=R?w+1:i.maxPartIndex):b=P+1;var D=i.age,_=D+i.ageHeader,M=Math.min(_-i.partTarget,1.5*i.targetduration);if(M>0){if(_>3*i.targetduration)this.log("Playlist last advanced ".concat(D.toFixed(2),"s ago. Omitting segment and part directives.")),b=void 0,I=void 0;else if(null!=r&&r.tuneInGoal&&_-i.partTarget>r.tuneInGoal)this.warn("CDN Tune-in goal increased from: ".concat(r.tuneInGoal," to: ").concat(M," with playlist age: ").concat(i.age)),M=0;else{var x=Math.floor(M/i.targetduration);if(b+=x,void 0!==I)I+=Math.round(M%i.targetduration/i.partTarget);this.log("CDN Tune-in age: ".concat(i.ageHeader,"s last advanced ").concat(D.toFixed(2),"s goal: ").concat(M," skip sn ").concat(x," to part ").concat(I))}i.tuneInGoal=M}if(T=this.getDeliveryDirectives(i,t.deliveryDirectives,b,I),R||!C)return i.requestScheduled=s,void this.loadingPlaylist(d,T)}else(i.canBlockReload||i.canSkipUntil)&&(T=this.getDeliveryDirectives(i,t.deliveryDirectives,b,I));T&&void 0!==b&&i.canBlockReload&&(i.requestScheduled=n.loading.first+Math.max(S-2*o,S/2)),this.scheduleLoading(d,T,i)}else this.clearTimer()}},{key:"scheduleLoading",value:function(e,t,r){var i=this,n=r||e.details;if(n){var a=self.performance.now(),s=n.requestScheduled;if(a>=s&&!this.loadingSync)return this.loadingSync=!0,this.loadingPlaylist(e,t),void(this.loadingSync=!1);var o=Math.max(s-a,0);this.log("reload live playlist ".concat(e.name||e.bitrate+"bps"," in ").concat(Math.round(o)," ms")),this.clearTimer(),this.timer=self.setTimeout(function(){return i.loadingPlaylist(e,t)},o)}else this.loadingPlaylist(e,t)}},{key:"getDeliveryDirectives",value:function(e,t,r,i){var n=_r(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(r=t.msn,i=t.part,n=wr),new Mr(r,i,n)}},{key:"checkRetry",value:function(e){var t=this,r=e.details,i=Le(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===ni||!n.resolved&&s===ri);if(c){var d;if(l>=u.maxNumRetry)return!1;if(i&&null!=(d=e.context)&&d.deliveryDirectives)this.warn("Retrying playlist loading ".concat(l+1,"/").concat(u.maxNumRetry,' after "').concat(r,'" without delivery-directives')),this.loadPlaylist();else{var h,f=xe(null==(h=e.response)?void 0:h.code);if(this.clearTimer(),f)this.log("Waiting for connection (offline)"),e.reason="offline",this.timer=self.setTimeout(function(){return t.checkOfflineStatus()},1e3);else{var v=De(u,l);this.warn("Retrying playlist loading ".concat(l+1,"/").concat(u.maxNumRetry,' after "').concat(r,'" in ').concat(v,"ms")),this.timer=self.setTimeout(function(){return t.loadPlaylist()},v)}}e.levelRetry=!0,n.resolved=!0}return c}},{key:"checkOfflineStatus",value:function(){var e=this;this.clearTimer(),xe(0)?this.timer=self.setTimeout(function(){return e.checkOfflineStatus()},1e3):(this.log("Connection restored (online)"),this.loadPlaylist())}}])}(Be);function Qs(e,t){if(e.length!==t.length)return!1;for(var r=0;r<e.length;r++)if(!$s(e[r].attrs,t[r].attrs))return!1;return!0}function $s(e,t,r){var i=e["STABLE-RENDITION-ID"];return i&&!r?i===t["STABLE-RENDITION-ID"]:!(r||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(function(r){return e[r]!==t[r]})}var Js=function(e){function t(e){var r;return s(this,t),(r=a(this,t,[e,"audio-track-controller"])).tracks=[],r.groupIds=null,r.tracksInGroup=[],r.trackId=-1,r.currentTrack=null,r.selectDefaultTrack=!0,r.registerListeners(),r}return f(t,e),l(t,[{key:"registerListeners",value:function(){var e=this.hls;e.on(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ne.MANIFEST_PARSED,this.onManifestParsed,this),e.on(ne.LEVEL_LOADING,this.onLevelLoading,this),e.on(ne.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(ne.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(ne.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ne.MANIFEST_PARSED,this.onManifestParsed,this),e.off(ne.LEVEL_LOADING,this.onLevelLoading,this),e.off(ne.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(ne.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(ne.ERROR,this.onError,this)}},{key:"destroy",value:function(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,A(t,"destroy",this,3)([])}},{key:"onManifestLoading",value:function(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}},{key:"onManifestParsed",value:function(e,t){this.tracks=t.audioTracks||[]}},{key:"onAudioTrackLoaded",value:function(e,t){var r=t.id,i=t.groupId,n=t.details,a=this.tracksInGroup[r];if(a&&a.groupId===i){var s=a.details;a.details=t.details,this.log("Audio track ".concat(r,' "').concat(a.name,'" lang:').concat(a.lang," group:").concat(i," loaded [").concat(n.startSN,"-").concat(n.endSN,"]")),r===this.trackId&&this.playlistLoaded(r,t,s)}else this.warn("Audio track with id:".concat(r," and group:").concat(i," not found in active group ").concat(null==a?void 0:a.groupId))}},{key:"onLevelLoading",value:function(e,t){this.switchLevel(t.level)}},{key:"onLevelSwitching",value:function(e,t){this.switchLevel(t.level)}},{key:"switchLevel",value:function(e){var t=this.hls.levels[e];if(t){var r=t.audioGroups||null,i=this.groupIds,n=this.currentTrack;if(!r||(null==i?void 0:i.length)!==(null==r?void 0:r.length)||null!=r&&r.some(function(e){return-1===(null==i?void 0:i.indexOf(e))})){this.groupIds=r,this.trackId=-1,this.currentTrack=null;var a=this.tracks.filter(function(e){return Wr(e.groupId,r)});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=Gr(s,a,Kr);if(o>-1)n=a[o];else{var l=Gr(s,this.tracks);n=this.tracks[l]}}var u=this.findTrackId(n);-1===u&&n&&(u=this.findTrackId(null));var c={audioTracks:a};this.log("Updating audio tracks, ".concat(a.length," track(s) found in group(s): ").concat(null==r?void 0:r.join(","))),this.hls.trigger(ne.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(ne.ERROR,{type:re.MEDIA_ERROR,details:ie.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:f})}}}}},{key:"onError",value:function(e,t){!t.fatal&&t.context&&t.context.type===ce.AUDIO_TRACK&&t.context.id===this.trackId&&Wr(t.context.groupId,this.groupIds)&&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:"nextAudioTrack",get:function(){return this.trackId},set:function(e){this.selectDefaultTrack=!1,this.setAudioTrack(e,!1)}},{key:"setAudioOption",value:function(e){var t=this.hls;if(t.config.audioPreference=e,e){var r=this.allAudioTracks;if(this.selectDefaultTrack=!1,r.length){var i=this.currentTrack;if(i&&Hr(e,i,Kr))return i;var n=Gr(e,this.tracksInGroup,Kr);if(n>-1){var a=this.tracksInGroup[n];return this.setAudioTrack(n,"flushImmediate"in e&&e.flushImmediate),a}if(i){var s=t.loadLevel;-1===s&&(s=t.firstAutoLevel);var o=function(e,t,r,i,n){var a=t[i],s=t.reduce(function(e,t,r){var i=t.uri;return(e[i]||(e[i]=[])).push(r),e},{})[a.uri];s.length>1&&(i=Math.max.apply(Math,s));var o=a.videoRange,l=a.frameRate,u=a.codecSet.substring(0,4),c=jr(t,i,function(t){if(t.videoRange!==o||t.frameRate!==l||t.codecSet.substring(0,4)!==u)return!1;var i=t.audioGroups,a=r.filter(function(e){return Wr(e.groupId,i)});return Gr(e,a,n)>-1});return c>-1?c:jr(t,i,function(t){var i=t.audioGroups,a=r.filter(function(e){return Wr(e.groupId,i)});return Gr(e,a,n)>-1})}(e,t.levels,r,s,Kr);if(-1===o)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){var l=Gr(e,r);if(l>-1)return r[l]}}}return null}},{key:"setAudioTrack",value:function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],r=this.tracksInGroup;if(e<0||e>=r.length)this.warn("Invalid audio track id: ".concat(e));else{this.selectDefaultTrack=!1;var i=this.currentTrack,n=r[e],a=n.details&&!n.details.live;if(!(e===this.trackId&&n===i&&a||(this.log("Switching to audio-track ".concat(e,' "').concat(n.name,'" lang:').concat(n.lang," group:").concat(n.groupId," channels:").concat(n.channels)),this.trackId=e,this.currentTrack=n,this.hls.trigger(ne.AUDIO_TRACK_SWITCHING,Ie(Ie({},n),{},{flushImmediate:t})),a))){var s=this.switchParams(n.url,null==i?void 0:i.details,n.details);this.loadPlaylist(s)}}}},{key:"findTrackId",value:function(e){for(var t=this.tracksInGroup,r=0;r<t.length;r++){var i=t[r];if((!this.selectDefaultTrack||i.default)&&(!e||Hr(e,i,Kr)))return r}if(e){for(var n=e.name,a=e.lang,s=e.assocLang,o=e.characteristics,l=e.audioCodec,u=e.channels,c=0;c<t.length;c++){if(Hr({name:n,lang:a,assocLang:s,characteristics:o,audioCodec:l,channels:u},t[c],Kr))return c}for(var d=0;d<t.length;d++){var h=t[d];if($s(e.attrs,h.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return d}for(var f=0;f<t.length;f++){var v=t[f];if($s(e.attrs,v.attrs,["LANGUAGE"]))return f}}return-1}},{key:"loadPlaylist",value:function(e){A(t,"loadPlaylist",this,3)([]);var r=this.currentTrack;this.shouldLoadPlaylist(r)&&qr(r.url,this.hls)&&this.scheduleLoading(r,e)}},{key:"loadingPlaylist",value:function(e,r){A(t,"loadingPlaylist",this,3)([e,r]);var i=e.id,n=e.groupId,a=this.getUrlWithDirectives(e.url,r),s=e.details,o=null==s?void 0:s.age;this.log("Loading audio-track ".concat(i,' "').concat(e.name,'" lang:').concat(e.lang," group:").concat(n).concat(void 0!==(null==r?void 0:r.msn)?" at sn "+r.msn+" part "+r.part:"").concat(o&&s.live?" age "+o.toFixed(1)+(s.type&&" "+s.type||""):""," ").concat(a)),this.hls.trigger(ne.AUDIO_TRACK_LOADING,{url:a,id:i,groupId:n,deliveryDirectives:r||null,track:e})}}])}(Xs),Zs=function(){return l(function e(t){s(this,e),this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=t},[{key:"destroy",value:function(){this.tracks=this.queues=null}},{key:"append",value:function(e,t,r){if(null!==this.queues&&null!==this.tracks){var i=this.queues[t];i.push(e),1!==i.length||r||this.executeNext(t)}}},{key:"appendBlocker",value:function(e){var t=this;return new Promise(function(r){var i={label:"async-blocker",execute:r,onStart:function(){},onComplete:function(){},onError:function(){}};t.append(i,e)})}},{key:"prependBlocker",value:function(e){var t=this;return new Promise(function(r){if(t.queues){var i={label:"async-blocker-prepend",execute:r,onStart:function(){},onComplete:function(){},onError:function(){}};t.queues[e].unshift(i)}})}},{key:"removeBlockers",value:function(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(function(e){var t,r=null==(t=e[0])?void 0:t.label;"async-blocker"===r||"async-blocker-prepend"===r?(e[0].execute(),e.splice(0,1)):"block-audio"===r&&e.splice(0,1)})}},{key:"insertNext",value:function(e,t){var r;null!==this.queues&&(r=this.queues[t]).splice.apply(r,[1,0].concat(b(e)))}},{key:"unblockAudio",value:function(){var e;null!==this.queues&&"block-audio"===(null==(e=this.current("audio"))?void 0:e.label)&&this.shiftAndExecuteNext("audio")}},{key:"audioBlocking",value:function(){return null!==this.queues&&this.queues.audio.some(function(e){return"block-audio"===e.label})}},{key:"executeNext",value:function(e){if(null!==this.queues&&null!==this.tracks){var t=this.queues[e];if(t.length){var r=t[0];try{r.execute()}catch(t){var i;if(r.onError(t),null===this.queues||null===this.tracks)return;var n=null==(i=this.tracks[e])?void 0:i.buffer;null!=n&&n.updating||this.shiftAndExecuteNext(e)}}}}},{key:"shiftAndExecuteNext",value:function(e){null!==this.queues&&(this.queues[e].shift(),this.executeNext(e))}},{key:"current",value:function(e){var t;return(null==(t=this.queues)?void 0:t[e][0])||null}},{key:"toString",value:function(){var e=this.queues,t=this.tracks;return null===e||null===t?"<destroyed>":"\n".concat(this.list("video"),"\n").concat(this.list("audio"),"\n").concat(this.list("audiovideo"),"}")}},{key:"list",value:function(e){var t,r;return null!=(t=this.queues)&&t[e]||null!=(r=this.tracks)&&r[e]?"".concat(e,": (").concat(this.listSbInfo(e),") ").concat(this.listOps(e)):""}},{key:"listSbInfo",value:function(e){var t,r=null==(t=this.tracks)?void 0:t[e],i=null==r?void 0:r.buffer;return i?"SourceBuffer".concat(i.updating?" updating":"").concat(r.ended?" ended":"").concat(r.ending?" ending":""):"none"}},{key:"listOps",value:function(e){var t;return(null==(t=this.queues)?void 0:t[e].map(function(e){return e.label}).join(", "))||""}}])}(),eo=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,to="HlsJsTrackRemovedError",ro=function(e){function t(e){var r;return s(this,t),(r=a(this,t,[e])).name=to,r}return f(t,e),l(t)}(w(Error)),io=function(e){function t(e,r){var i,n;return s(this,t),(i=a(this,t,["buffer-controller",e.logger])).hls=void 0,i.fragmentTracker=void 0,i.fragmentAppendProgress=Object.create(null),i.appendsWithoutProgress=Object.create(null),i.details=null,i._objectUrl=null,i.operationQueue=null,i.bufferCodecEventsTotal=0,i.media=null,i.mediaSource=null,i.lastMpegAudioChunk=null,i.lastVideoAppendEnd=0,i.appendSource=void 0,i.transferData=void 0,i.overrides=void 0,i.appendErrors={audio:0,video:0,audiovideo:0},i.appendError=void 0,i._quotaEvictionPending={},i.tracks={},i.sourceBuffers=[[null,null],[null,null]],i._onEndStreaming=function(e){var t;i.hls&&"open"===(null==(t=i.mediaSource)?void 0:t.readyState)&&i.media&&!i.media.seeking&&i.hls.pauseBuffering()},i._onStartStreaming=function(e){i.hls&&i.hls.resumeBuffering()},i._onMediaSourceOpen=function(e){var t=i,r=t.media,n=t.mediaSource;e&&i.log("Media source opened"),r&&n&&(ra(n,"sourceopen",i._onMediaSourceOpen),ra(r,"emptied",i._onMediaEmptied),i.updateDuration(),i.hls.trigger(ne.MEDIA_ATTACHED,{media:r,mediaSource:n}),null!==i.mediaSource&&i.checkPendingTracks())},i._onMediaSourceClose=function(){if(i.log("Media source closed"),i.media){var e=i.media.error,t=i,r=t.appendError,n=t.appendErrors,a=!1;if(!r&&e)a=Math.max(++n.audio,++n.video,++n.audiovideo)>=i.hls.config.appendErrorMaxRetry;var s=new Error("MediaSource closed while media attached".concat(so(a,e)));i.warn(s),i.hls.trigger(ne.ERROR,Ae({fatal:a},r,{type:re.MEDIA_ERROR,details:ie.MEDIA_SOURCE_REQUIRES_RESET,error:s}))}},i._onMediaSourceEnded=function(){i.log("Media source ended")},i._onMediaEmptied=function(){var e=i,t=e.mediaSrc,r=e._objectUrl;t!==r&&i.error("Media element src was set while attaching MediaSource (".concat(r," > ").concat(t,")"))},i._onMediaError=function(){var e,t,r=i.media;r&&i.log("Media error (code: ".concat(null==(e=r.error)?void 0:e.code,"): ").concat(null==(t=r.error)?void 0:t.message))},i.hls=e,i.fragmentTracker=r,i.appendSource=(n=qe(e.config.preferManagedMediaSource),"undefined"!=typeof self&&n===self.ManagedMediaSource),i.initTracks(),i.registerListeners(),i}return f(t,e),l(t,[{key:"hasSourceTypes",value:function(){return Object.keys(this.tracks).length>0}},{key:"destroy",value:function(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=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,this._onMediaEmptied=this._onMediaError=null}},{key:"registerListeners",value:function(){var e=this.hls;e.on(ne.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(ne.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ne.MANIFEST_PARSED,this.onManifestParsed,this),e.on(ne.BUFFER_RESET,this.onBufferReset,this),e.on(ne.BUFFER_APPENDING,this.onBufferAppending,this),e.on(ne.BUFFER_CODECS,this.onBufferCodecs,this),e.on(ne.BUFFER_EOS,this.onBufferEos,this),e.on(ne.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(ne.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(ne.FRAG_PARSED,this.onFragParsed,this),e.on(ne.FRAG_CHANGED,this.onFragChanged,this),e.on(ne.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(ne.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(ne.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ne.MANIFEST_PARSED,this.onManifestParsed,this),e.off(ne.BUFFER_RESET,this.onBufferReset,this),e.off(ne.BUFFER_APPENDING,this.onBufferAppending,this),e.off(ne.BUFFER_CODECS,this.onBufferCodecs,this),e.off(ne.BUFFER_EOS,this.onBufferEos,this),e.off(ne.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(ne.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(ne.FRAG_PARSED,this.onFragParsed,this),e.off(ne.FRAG_CHANGED,this.onFragChanged,this),e.off(ne.ERROR,this.onError,this)}},{key:"transferMedia",value:function(){var e=this,t=this.media,r=this.mediaSource;if(!t)return null;var i={};if(this.operationQueue){var n=this.isUpdating();n||this.operationQueue.removeBlockers();var a=this.isQueued();(n||a)&&this.warn("Transfering MediaSource with".concat(a?" operations in queue":"").concat(n?" updating SourceBuffer(s)":""," ").concat(this.operationQueue)),this.operationQueue.destroy()}var s=this.transferData;return s&&!this.sourceBufferCount&&s.mediaSource===r?Ae(i,s.tracks):this.sourceBuffers.forEach(function(t){var r=S(t,1)[0];r&&(i[r]=Ae({},e.tracks[r]),e.removeBuffer(r)),t[0]=t[1]=null}),{media:t,mediaSource:r,tracks:i}}},{key:"initTracks",value:function(){this.resetAppendProgress(),this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0}},{key:"onManifestLoading",value:function(){this.bufferCodecEventsTotal=0,this.details=null,this.resetAppendErrors(),this.resetAppendProgress()}},{key:"onManifestParsed",value:function(e,t){var r,i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log("".concat(i," bufferCodec event(s) expected.")),null!=(r=this.transferData)&&r.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}},{key:"onMediaAttaching",value:function(e,t){var r=this.media=t.media;this.transferData=this.overrides=void 0;var i=qe(this.appendSource);if(i){var n=!!t.mediaSource;(n||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);var a=this.mediaSource=t.mediaSource||new i;if(this.assignMediaSource(a),n)this._objectUrl=r.src,this.attachTransferred();else{var s=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{r.removeAttribute("src");var o=self.ManagedMediaSource;r.disableRemotePlayback=r.disableRemotePlayback||o&&a instanceof o,no(r),function(e,t){var r=self.document.createElement("source");r.type="video/mp4",r.src=t,e.appendChild(r)}(r,s),r.load()}catch(e){r.src=s}else r.src=s}ta(r,"emptied",this._onMediaEmptied),ta(r,"error",this._onMediaError),this.appendSource&&ta(r,"seeking",this._onStartStreaming)}}},{key:"assignMediaSource",value:function(e){var t,r;this.log("".concat((null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created"," media source: ").concat(null==(r=e.constructor)?void 0:r.name)),ta(e,"sourceopen",this._onMediaSourceOpen),ta(e,"sourceended",this._onMediaSourceEnded),ta(e,"sourceclose",this._onMediaSourceClose),this.appendSource&&(ta(e,"startstreaming",this._onStartStreaming),ta(e,"endstreaming",this._onEndStreaming))}},{key:"attachTransferred",value:function(){var e=this,t=this.media,r=this.transferData;if(r&&t){var i=this.tracks,n=r.tracks,a=n?Object.keys(n):null,s=a?a.length:0,o=function(){Promise.resolve().then(function(){e.media&&e.mediaSourceOpenOrEnded&&e._onMediaSourceOpen()})};if(n&&a&&s){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log("attachTransferred: (bufferCodecEventsTotal ".concat(this.bufferCodecEventsTotal,")\nrequired tracks: ").concat(Nr(i,function(e,t){return"initSegment"===e?void 0:t}),";\ntransfer tracks: ").concat(Nr(n,function(e,t){return"initSegment"===e?void 0:t}),"}")),!We(n,i)){r.mediaSource=null,r.tracks=void 0;var l=t.currentTime,u=this.details,c=Math.max(l,(null==u?void 0:u.fragments[0].start)||0);return c-l>1?void this.log("attachTransferred: waiting for playback to reach new tracks start time ".concat(l," -> ").concat(c)):(this.warn('attachTransferred: resetting MediaSource for incompatible tracks ("'.concat(Object.keys(n),'"->"').concat(Object.keys(i),'") start time: ').concat(c," currentTime: ").concat(l)),this.onMediaDetaching(ne.MEDIA_DETACHING,{}),this.onMediaAttaching(ne.MEDIA_ATTACHING,r),void(t.currentTime=c))}this.transferData=void 0,a.forEach(function(t){var r=t,i=n[r];if(i){var a=i.buffer;if(a){var s=e.fragmentTracker,o=i.id;if(s.hasFragments(o)||s.hasParts(o)){var l=Bi.getBuffered(a);s.detectEvictedFragments(r,l,o,null,null,!0)}var u=ao(r),c=[r,a];e.sourceBuffers[u]=c,a.updating&&e.operationQueue&&e.operationQueue.prependBlocker(r),e.trackSourceBuffer(r,i)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}}},{key:"mediaSourceOpenOrEnded",get:function(){var e,t=null==(e=this.mediaSource)?void 0:e.readyState;return"open"===t||"ended"===t}},{key:"onMediaDetaching",value:function(e,t){var r=this,i=!!t.transferMedia;this.transferData=this.overrides=void 0;var n=this.media,a=this.mediaSource,s=this._objectUrl;if(a){if(this.log("media source ".concat(i?"transferring":"detaching")),i)this.sourceBuffers.forEach(function(e){var t=S(e,1)[0];t&&r.removeBuffer(t)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){var o="open"===a.readyState;try{for(var l=a.sourceBuffers,u=l.length;u--;)o&&l[u].abort(),a.removeSourceBuffer(l[u]);o&&a.endOfStream()}catch(e){this.warn("onMediaDetaching: ".concat(e.message," while calling endOfStream"))}}this.sourceBufferCount&&this.onBufferReset()}ra(a,"sourceopen",this._onMediaSourceOpen),ra(a,"sourceended",this._onMediaSourceEnded),ra(a,"sourceclose",this._onMediaSourceClose),this.appendSource&&(ra(a,"startstreaming",this._onStartStreaming),ra(a,"endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}n&&(ra(n,"emptied",this._onMediaEmptied),ra(n,"error",this._onMediaError),ra(n,"seeking",this._onStartStreaming),i||(s&&self.URL.revokeObjectURL(s),this.mediaSrc===s?(n.removeAttribute("src"),this.appendSource&&no(n),n.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null)}},{key:"onBufferReset",value:function(){var e=this;this.sourceBuffers.forEach(function(t){var r=S(t,1)[0];r&&e.resetBuffer(r)}),this.initTracks()}},{key:"resetBuffer",value:function(e){var t,r=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),r)try{var i;null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(r)}catch(t){this.warn("onBufferReset ".concat(e),t)}delete this.tracks[e]}},{key:"removeBuffer",value:function(e){this.removeBufferListeners(e),this.sourceBuffers[ao(e)]=[null,null];var t=this.tracks[e];t&&(this.clearBufferAppendTimeoutId(t),t.buffer=void 0)}},{key:"resetQueue",value:function(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Zs(this.tracks)}},{key:"onBufferCodecs",value:function(e,t){var r,i=this,n=this.tracks,a=Object.keys(t);this.log('BUFFER_CODECS: "'.concat(a,'" (current SB count ').concat(this.sourceBufferCount,")"));var s="audiovideo"in t&&(n.audio||n.video)||n.audiovideo&&("audio"in t||"video"in t),o=!s&&this.sourceBufferCount&&this.media&&a.some(function(e){return!n[e]});s||o?this.warn('Unsupported transition between "'.concat(Object.keys(n),'" and "').concat(a,'" SourceBuffers')):(a.forEach(function(e){var r,a,s=t[e],o=s.id,l=s.codec,u=s.levelCodec,c=s.container,d=s.metadata,h=s.supplemental,f=n[e],v=null==(r=i.transferData)||null==(r=r.tracks)?void 0:r[e],g=null!=v&&v.buffer?v:f,p=(null==g?void 0:g.pendingCodec)||(null==g?void 0:g.codec),m=null==g?void 0:g.levelCodec;f||(f=n[e]={buffer:void 0,listeners:[],codec:l,supplemental:h,container:c,levelCodec:u,metadata:d,id:o});var y=gr(p,m),k=null==y?void 0:y.replace(eo,"$1"),E=gr(l,u),S=null==(a=E)?void 0:a.replace(eo,"$1");E&&y&&k!==S&&("audio"===e.slice(0,5)&&(E=vr(E,i.appendSource)),i.log("switching codec ".concat(p," to ").concat(E)),E!==(f.pendingCodec||f.codec)&&(f.pendingCodec=E),f.container=c,i.appendChangeType(e,c,E))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&"main"===(null==(r=t.audio)?void 0:r.id)&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks()))}},{key:"sourceBufferTracks",get:function(){var e=this;return Object.keys(this.tracks).reduce(function(t,r){var i=e.tracks[r];return t[r]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},t},{})}},{key:"appendChangeType",value:function(e,t,r){var i=this,n="".concat(t,";codecs=").concat(r),a={label:"change-type=".concat(n),execute:function(){var a=i.tracks[e];if(a){var s=a.buffer;null!=s&&s.changeType&&(i.log("changing ".concat(e," sourceBuffer type to ").concat(n)),s.changeType(n),a.codec=r,a.container=t)}i.shiftAndExecuteNext(e)},onStart:function(){},onComplete:function(){},onError:function(t){i.warn("Failed to change ".concat(e," SourceBuffer type"),t)}};this.append(a,e,this.isPending(this.tracks[e]))}},{key:"blockAudio",value:function(e){var t,r=this,i=e.start,n=i+.05*e.duration;if(!(!0===(null==(t=this.fragmentTracker.getAppendedFrag(i,de.MAIN))?void 0:t.gap))){var a={label:"block-audio",execute:function(){var e,t;(r.lastVideoAppendEnd>n||Bi.isBuffered(null==(e=r.tracks.video)?void 0:e.buffer,n)||!0===(null==(t=r.fragmentTracker.getAppendedFrag(n,de.MAIN))?void 0:t.gap))&&r.unblockAudio()},onStart:function(){},onComplete:function(){},onError:function(e){r.warn("Error executing block-audio operation",e)}};this.append(a,"audio",!0)}}},{key:"unblockAudio",value:function(){this.operationQueue&&this.operationQueue.unblockAudio()}},{key:"onBufferAppending",value:function(e,t){var r=this,i=this.tracks,n=t.data,a=t.type,s=t.parent,o=t.frag,l=t.part,u=t.chunkMeta,c=t.offset,d=u.buffering[a],h=pe(o)&&!l&&!o.gap&&!u.partial&&!u.iframe,f=null,v=!1,g=o.sn,p=o.cc,m=self.performance.now();d.start=m;var y=o.stats.buffering,k=l?l.stats.buffering:null;0===y.start&&(y.start=m),0===(null==k?void 0:k.start)&&(k.start=m);var E=i.audio,T=!1;"audio"===a&&"audio/mpeg"===(null==E?void 0:E.container)&&(T=!this.lastMpegAudioChunk||1===u.id||this.lastMpegAudioChunk.sn!==u.sn,this.lastMpegAudioChunk=u);var A=i.video,b=null==A?void 0:A.buffer;if(b&&"initSegment"!==g&&void 0!==c){var I=null==E?void 0:E.buffer,R=l||o;if("audio"===a&&"main"!==s&&!A.ending&&!A.ended&&I&&Bi.getBuffered(I).length){var L=R.start+.05*R.duration,P=Bi.getBuffered(b),w=this.currentOp("video");P.length||w?!Bi.isBuffered(b,L)&&this.lastVideoAppendEnd<L&&this.blockAudio(R):this.blockAudio(R)}else if("video"===a){var C=R.end,D=this.lastVideoAppendEnd-C;this.lastVideoAppendEnd=C,D<0||D>R.duration?this.unblockAudio():this.isAudioBlocked()&&this.executeNext("audio")}}var _=(l||o).start,M={label:"append-".concat(a),execute:function(){var e;d.executeStart=self.performance.now();var t=null==(e=r.tracks[a])?void 0:e.buffer;t&&(h&&(f=Bi.timeRangesToArray(Bi.getBuffered(t)),v=uo(lo(f,o),o)),T?r.updateTimestampOffset(t,_,.1,a,g,p):void 0!==c&&Z(c)&&r.updateTimestampOffset(t,c,1e-6,a,g,p)),r.appendExecutor(n,a)},onStart:function(){},onComplete:function(){r.clearBufferAppendTimeoutId(r.tracks[a]);var e=self.performance.now();d.executeEnd=d.end=e,0===y.first&&(y.first=e),0===(null==k?void 0:k.first)&&(k.first=e);var t={};if(r.sourceBuffers.forEach(function(e){var r=S(e,2),i=r[0],n=r[1];i&&(t[i]=Bi.getBuffered(n))}),h){var i=r.getFragmentAppendProgress(o),n=t[a];if(n&&f){var c=lo(Bi.timeRangesToArray(n),o);i.progressed||(i.progressed=c-lo(f,o)>.001);var g=v&&uo(c,o);i.fullyBuffered[a]=(void 0===i.fullyBuffered[a]||i.fullyBuffered[a])&&g}}r.hls.trigger(ne.BUFFER_APPENDED,{type:a,frag:o,part:l,chunkMeta:u,parent:s,timeRanges:t})},onError:function(e){var t;r.clearBufferAppendTimeoutId(r.tracks[a]);var i=e.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==e.name||"quota"in e;if(i&&!r._quotaEvictionPending[a]){var c=r.getBackBufferEvictionTarget(a,n.byteLength,o.type);if(c>0){r._quotaEvictionPending[a]=!0,r.log('QuotaExceededError on "'.concat(a,'" append sn: ').concat(g," - evicting back buffer to ").concat(c.toFixed(3),"s and retrying"));var d=r.getFlushOp(a,0,c),f=r.getClearEvictionPendingOp(a);return void r.insertNext([d,M,f],a)}r.warn('QuotaExceededError on "'.concat(a,'" sn: ').concat(g," - no back buffer available to evict"))}h&&(r.getFragmentAppendProgress(o).errored=!0);var v={type:re.MEDIA_ERROR,parent:s,details:ie.BUFFER_APPEND_ERROR,sourceBufferName:a,frag:o,part:l,chunkMeta:u,error:e,err:e,fatal:!1},p=null==(t=r.media)?void 0:t.error;if(e.name!==to||0!==r.sourceBufferCount||r.media&&0!==r.pendingTrackCount){var m;i&&(v.details=ie.BUFFER_FULL_ERROR);var y=++r.appendErrors[a],k=r.hls.config.appendErrorMaxRetry;r.warn("Failed ".concat(y,"/").concat(k+1,' times to append segment in "').concat(a,'" sourceBuffer with error: ').concat(e.message)),y>=k&&(v.fatal=!i);var E=null==(m=r.mediaSource)?void 0:m.readyState;("ended"===E||"closed"===E||p)&&(r.warn('MediaSource readyState "'.concat(E,'" during SourceBuffer').concat(so(v.fatal,p))),v.details=ie.MEDIA_SOURCE_REQUIRES_RESET)}else v.errorAction=vi(!0);r.appendError=v,r.hls.trigger(ne.ERROR,v),i&&r.hls&&r.trimBuffers(o.start,1)}};this.log('queuing "'.concat(a,'" append sn: ').concat(g).concat(l?" p: "+l.index:""," of ").concat(s," playlist ").concat(o.level," cc: ").concat(p," offset: ").concat(c," bytes: ").concat(n.byteLength)),this.append(M,a,this.isPending(this.tracks[a]))}},{key:"getClearEvictionPendingOp",value:function(e){var t=this;return{label:"clear",execute:function(){t._quotaEvictionPending[e]=!1,t.shiftAndExecuteNext(e)},onStart:function(){},onComplete:function(){},onError:function(){}}}},{key:"getFlushOp",value:function(e,t,r){var i=this;return this.log('queuing "'.concat(e,'" remove ').concat(t,"-").concat(r)),{label:"remove",execute:function(){i.removeExecutor(e,t,r)},onStart:function(){},onComplete:function(){var n,a=null==(n=i.tracks[e])?void 0:n.buffer;i.log("Remove request ".concat(t,"-").concat(r," from ").concat(e," Source Buffer complete > buffer: ").concat(a?ia(Bi.getBuffered(a)):"(detached)")),i.hls.trigger(ne.BUFFER_FLUSHED,{type:e,start:t,end:r})},onError:function(n){i.warn("Failed to remove ".concat(t,"-").concat(r,' from "').concat(e,'" SourceBuffer'),n),i.hls.trigger(ne.BUFFER_FLUSHED,{type:e,start:0,end:0,error:n})}}}},{key:"onBufferFlushing",value:function(e,t){var r=this,i=t.type,n=t.startOffset,a=t.endOffset;i&&"audio"!==i||this.unblockAudio(),i?this.append(this.getFlushOp(i,n,a),i):this.sourceBuffers.forEach(function(e){var t=S(e,1)[0];t&&r.append(r.getFlushOp(t,n,a),t)})}},{key:"onFragParsed",value:function(e,t){var r=this,i=t.frag,n=t.part,a=t.chunkMeta,s=[],o=n?n.elementaryStreams:i.elementaryStreams;o[ve]?s.push("audiovideo"):(o[he]&&s.push("audio"),o[fe]&&s.push("video"));0===s.length&&this.log("Fragments must have at least one ElementaryStreamType set. ".concat(i.type," ").concat(i.level," ").concat(n?"part: ".concat(n.index," of "):"","sn: ").concat(i.sn)),this.blockBuffers(function(){var e=self.performance.now();i.stats.buffering.end=e,n&&(n.stats.buffering.end=e);var t=n?n.stats:i.stats;r.checkAppendProgress(i,n,a,s),r.hls&&(r.hls.trigger(ne.FRAG_BUFFERED,{frag:i,part:n,stats:t,id:i.type,chunkMeta:a}),!n&&i.gap&&t.retry&&r.log("Nothing buffered for ".concat(i.type," level: ").concat(i.level," sn: ").concat(i.sn," retries ").concat(t.retry)))},s).catch(function(e){r.warn("Fragment buffered callback ".concat(e.message)),r.stepOperationQueue(r.sourceBufferTypes)})}},{key:"onFragChanged",value:function(e,t){var r,i,n=this,a=null==(r=this.hls)?void 0:r.config;if(a){var s=a.backBufferLength,o=a.frontBufferFlushThreshold;this.trimBuffers(o,s,t.frag,t.previousFrag);var l=t.frag.elementaryStreams,u=this.appendErrors,c=null==(i=this.appendError)?void 0:i.sourceBufferName;Object.keys(l).forEach(function(e){l[e]&&(u[e]=0,e===c&&(n.appendError=void 0),"audio"===e||"video"===e?(u.audiovideo=0,"audiovideo"===c&&(n.appendError=void 0)):(u.audio=0,u.video=0,"audiovideo"!==c&&(n.appendError=void 0)))})}}},{key:"bufferedToEnd",get:function(){var e=this;return this.sourceBufferCount>0&&!this.sourceBuffers.some(function(t){var r=S(t,1)[0];if(r){var i=e.tracks[r];if(i)return!i.ended||i.ending}return!1})}},{key:"onBufferEos",value:function(e,t){var r,i=this;this.sourceBuffers.forEach(function(e){var r=S(e,1)[0];if(r){var n=i.tracks[r];t.type&&t.type!==r||(n.ending=!0,n.ended||(n.ended=!0,i.log("".concat(r," buffer reached EOS"))))}});var n=!1!==(null==(r=this.overrides)?void 0:r.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some(function(e){var t,r=S(e,1)[0];return r&&!(null!=(t=i.tracks[r])&&t.ended)})?(this.unblockAudio(),n?(this.log("Queueing EOS"),this.blockUntilOpen(function(){i.tracksEnded();var e=i.mediaSource;"open"===(null==e?void 0:e.readyState)?(i.log("Calling mediaSource.endOfStream()"),e.endOfStream(),i.hls.trigger(ne.BUFFERED_TO_END,void 0)):e&&i.log("Could not call mediaSource.endOfStream(). mediaSource.readyState: ".concat(e.readyState))})):(this.tracksEnded(),this.hls.trigger(ne.BUFFERED_TO_END,void 0))):"video"===t.type&&this.unblockAudio()}},{key:"tracksEnded",value:function(){var e=this;this.sourceBuffers.forEach(function(t){var r=S(t,1)[0];if(null!==r){var i=e.tracks[r];i&&(i.ending=!1)}})}},{key:"onLevelUpdated",value:function(e,t){var r=t.details;r.fragments.length&&(this.details=r,this.updateDuration())}},{key:"updateDuration",value:function(){var e=this;this.blockUntilOpen(function(){var t=e.getDurationAndRange();t&&e.updateMediaSource(t)})}},{key:"onError",value:function(e,t){if(t.details===ie.BUFFER_APPEND_ERROR&&t.frag){var r,i=null==(r=t.errorAction)?void 0:r.nextAutoLevel;Z(i)&&i!==t.frag.level&&this.resetAppendErrors()}}},{key:"getBackBufferEvictionTarget",value:function(e,t,r){var i=this.media;return i?this.fragmentTracker.getBackBufferEvictionEnd(i.currentTime,r,t):0}},{key:"getFragmentAppendProgress",value:function(e){var t,r=oo(e),i=this.fragmentAppendProgress[r];return(null==(t=i)?void 0:t.stats)!==e.stats&&(i={stats:e.stats,progressed:!1,errored:!1,fullyBuffered:Object.create(null)},this.fragmentAppendProgress[r]=i),i}},{key:"checkAppendProgress",value:function(e,t,r,i){if(!(t||!pe(e)||e.gap||r.iframe||r.partial)){var n=oo(e),a=this.fragmentAppendProgress[n];delete this.fragmentAppendProgress[n];var s=e.stats.buffering;if(!s.start||s.first){var o=(null==a?void 0:a.stats)===e.stats?a:void 0;if(null==o||!o.errored){var l=i.length>0&&i.every(function(e){return!0===(null==o?void 0:o.fullyBuffered[e])});if(null!=o&&o.progressed||l)delete this.appendsWithoutProgress[n];else if(o||0!==i.length){var u=(this.appendsWithoutProgress[n]||0)+1,c=this.hls;u>=c.config.appendErrorMaxRetry?delete this.appendsWithoutProgress[n]:this.appendsWithoutProgress[n]=u,this.warn("Fragment ".concat(e.sn," of ").concat(e.type," playlist ").concat(e.level," appended ").concat(u," time").concat(u>1?"s":""," without buffered range growth")),c.trigger(ne.ERROR,{type:re.MEDIA_ERROR,details:ie.BUFFER_APPEND_NO_PROGRESS,fatal:!1,frag:e,chunkMeta:r,parent:e.type,appendsWithoutProgress:u,error:new Error("Fragment append did not increase buffered coverage (".concat(u,")"))})}}}}}},{key:"resetAppendProgress",value:function(){this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null)}},{key:"resetAppendErrors",value:function(){this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0}},{key:"trimBuffers",value:function(e,t,r,i){var n=this.hls,a=this.details,s=this.media;if(s&&null!==a&&this.sourceBufferCount){var o=n.config,l=s.currentTime,u=a.levelTargetDuration;t=a.live&&null!==o.liveBackBufferLength?o.liveBackBufferLength:t;var c=-1/0;if(Z(t)&&t>=0){var d=Math.max(t,u);c=Math.floor(l/u)*u-d}if(r){var h=this.getLoopBackBufferFlushEnd(r,null!=i?i:null);h>0&&(c=Math.max(c,h))}if(c>0&&this.flushBackBuffer(l,u,c),Z(e)&&e>0){var f=Math.max(o.maxBufferLength,e),v=Math.max(f,u),g=Math.floor(l/u)*u+v;this.flushFrontBuffer(l,u,g)}}}},{key:"getLoopBackBufferFlushEnd",value:function(e,t){var r,i=this.media;if(!1===(null==(r=this.hls)?void 0:r.config.loopBackBufferFlush)||null==i||!i.loop||!t||e.level<=t.level)return 0;var n=e.elementaryStreams,a=n.video,s=n.audiovideo;if(null!=a&&a.partial||null!=s&&s.partial)return 0;var o=this.getEarliestElementaryStreamStart(e)-.25;return o<=0?0:(this.log("Flushing lower quality back buffer for loop: level ".concat(e.level,", range [0-").concat(o.toFixed(3),"]")),o)}},{key:"getEarliestElementaryStreamStart",value:function(e){var t=e.elementaryStreams,r=t.audio,i=t.video,n=t.audiovideo,a=e.start;return n?a=Math.min(a,n.startDTS):(r&&(a=Math.min(a,r.startDTS)),i&&(a=Math.min(a,i.startDTS))),a}},{key:"flushBackBuffer",value:function(e,t,r){var i=this;this.sourceBuffers.forEach(function(e){var t=S(e,2),n=t[0],a=t[1];if(a){var s=Bi.getBuffered(a);if(s.length>0&&r>s.start(0)){var o,l,u;i.hls.trigger(ne.BACK_BUFFER_REACHED,{bufferEnd:r});var c=i.tracks[n];if(null!=(o=i.details)&&o.live)i.hls.trigger(ne.LIVE_BACK_BUFFER_REACHED,{bufferEnd:r});else if(null!=c&&c.ended&&(null==(l=i.media)||!l.loop||!1===(null==(u=i.hls)?void 0:u.config.loopBackBufferFlush)))return void i.log("Cannot flush ".concat(n," back buffer while SourceBuffer is in ended state"));i.hls.trigger(ne.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:n})}}})}},{key:"flushFrontBuffer",value:function(e,t,r){var i=this;this.sourceBuffers.forEach(function(t){var n=S(t,2),a=n[0],s=n[1];if(s){var o=Bi.getBuffered(s),l=o.length;if(l<2)return;var u=o.start(l-1),c=o.end(l-1);if(r>u||e>=u&&e<=c)return;i.hls.trigger(ne.BUFFER_FLUSHING,{startOffset:u,endOffset:1/0,type:a})}})}},{key:"getDurationAndRange",value:function(){var e,t=this.details,r=this.mediaSource;if(!t||!this.media||"open"!==(null==r?void 0:r.readyState))return null;var i=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&r.setLiveSeekableRange){var n=Math.max(0,t.fragmentStart);return{duration:1/0,start:n,end:Math.max(n,i)}}return{duration:1/0}}var a=null==(e=this.overrides)?void 0:e.duration;if(a)return Z(a)?{duration:a}:null;var s=this.media.duration;return i>(Z(r.duration)?r.duration:0)&&i>s||!Z(s)?{duration:i}:null}},{key:"updateMediaSource",value:function(e){var t=e.duration,r=e.start,i=e.end,n=this.mediaSource;n&&this.media&&"open"===n.readyState&&(n.duration!==t&&(Z(t)&&this.log("Updating MediaSource duration to ".concat(t.toFixed(3))),n.duration=t),void 0!==r&&void 0!==i&&(this.log("MediaSource duration is set to ".concat(n.duration,". Setting seekable range to ").concat(r,"-").concat(i,".")),n.setLiveSeekableRange(r,i)))}},{key:"tracksReady",get:function(){var e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}},{key:"checkPendingTracks",value:function(){var e=this.bufferCodecEventsTotal,t=this.pendingTrackCount,r=this.tracks;if(this.log("checkPendingTracks (pending: ".concat(t," codec events expected: ").concat(e,") ").concat(Nr(r))),this.tracksReady){var i,n=null==(i=this.transferData)?void 0:i.tracks;n&&Object.keys(n).length?this.attachTransferred():this.createSourceBuffers()}}},{key:"bufferCreated",value:function(){var e=this;if(this.sourceBufferCount){var t={};this.sourceBuffers.forEach(function(r){var i=S(r,2),n=i[0],a=i[1];if(n){var s=e.tracks[n];t[n]={buffer:a,container:s.container,codec:s.codec,supplemental:s.supplemental,levelCodec:s.levelCodec,id:s.id,metadata:s.metadata}}}),this.hls.trigger(ne.BUFFER_CREATED,{tracks:t}),this.log("SourceBuffers created. Running queue: ".concat(this.operationQueue)),this.sourceBuffers.forEach(function(t){var r=S(t,1)[0];e.executeNext(r)})}else{var r=new Error("could not create source buffer for media codec(s)");this.hls.trigger(ne.ERROR,{type:re.MEDIA_ERROR,details:ie.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:r,reason:r.message})}}},{key:"createSourceBuffers",value:function(){var e=this.tracks,t=this.sourceBuffers,r=this.mediaSource;if(!r)throw new Error("createSourceBuffers called when mediaSource was null");for(var i in e){var n=i,a=e[n];if(this.isPending(a)){var s=this.getTrackCodec(a,n),o="".concat(a.container,";codecs=").concat(s);a.codec=s,this.log("creating sourceBuffer(".concat(o,")").concat(this.currentOp(n)?" Queued":""," ").concat(Nr(a)));try{var l=r.addSourceBuffer(o),u=ao(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(ne.ERROR,{type:re.MEDIA_ERROR,details:ie.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:n,mimeType:o,parent:a.id})}this.trackSourceBuffer(n,a)}}this.bufferCreated()}},{key:"clearBufferAppendTimeoutId",value:function(e){e&&(self.clearTimeout(e.bufferAppendTimeoutId),e.bufferAppendTimeoutId=void 0)}},{key:"getTrackCodec",value:function(e,t){var r=e.supplemental,i=e.codec;r&&("video"===t||"audiovideo"===t)&&or(r,"video")&&(i=function(e,t){var r=[];if(e)for(var i=e.split(","),n=0;n<i.length;n++)sr(i[n],"video")||r.push(i[n]);return t&&r.push(t),r.join(",")}(i,r));var n=gr(i,e.levelCodec);return n?"audio"===t.slice(0,5)?vr(n,this.appendSource):n:""}},{key:"trackSourceBuffer",value:function(e,t){var r=this,i=t.buffer;if(i){var n=this.getTrackCodec(t,e);this.tracks[e]={buffer:i,codec:n,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",function(e,t){var i=t.removedRanges;null!=i&&i.length&&(r.log("".concat(e," buffer removed ").concat(ia(i))),r.hls.trigger(ne.BUFFER_FLUSHED,{type:e,start:i.start(0),end:i.end(i.length-1)}))})}}},{key:"mediaSrc",get:function(){var e,t,r=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==r?void 0:r.src}},{key:"onSBUpdateStart",value:function(e){var t=this.currentOp(e);t&&t.onStart()}},{key:"onSBUpdateEnd",value:function(e){var t,r,i=this;if("closed"!==(null==(t=this.mediaSource)?void 0:t.readyState)){var n=this.currentOp(e);if(n){if(n.onComplete(),null==(r=this.tracks[e])||null==(r=r.buffer)?void 0:r.updating)return this.log("".concat(e,' SourceBuffer updating on "updateend"')),void this.blockUntilOpen(function(){i.shiftAndExecuteNext(e)});this.shiftAndExecuteNext(e)}}else this.resetBuffer(e)}},{key:"onSBUpdateError",value:function(e,t){var r,i=null==(r=this.mediaSource)?void 0:r.readyState,n=new Error("".concat(e," SourceBuffer error. MediaSource readyState: ").concat(i));this.error("".concat(n.message),t),this.hls.trigger(ne.ERROR,{type:re.MEDIA_ERROR,details:ie.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:n,fatal:!1});var a=this.currentOp(e);a&&a.onError(n)}},{key:"updateTimestampOffset",value:function(e,t,r,i,n,a){var s=t-e.timestampOffset;Math.abs(s)>=r&&(this.log("Updating ".concat(i," SourceBuffer timestampOffset to ").concat(t," (sn: ").concat(n," cc: ").concat(a,")")),e.timestampOffset=t)}},{key:"removeExecutor",value:function(e,t,r){var i=this.media,n=this.mediaSource,a=this.tracks[e],s=null==a?void 0:a.buffer;if(!i||!n||!s)throw new Error("Attempting to remove from the ".concat(e," SourceBuffer, but it does not exist"));var o,l=Z(i.duration)?i.duration:1/0,u=Z(n.duration)?n.duration:1/0,c=Math.max(0,t);if(c>=u)return null==(o=this.currentOp(e))||o.onComplete(),void this.shiftAndExecuteNext(e);var d=Math.min(r,l,u);if(!(d>c)||a.ending&&!a.ended)throw new Error("Cannot remove ".concat(d<=c?"invalid range (".concat(c," >= ").concat(d,") "):"","from the ").concat(e," SourceBuffer").concat(a.ending?" while track ending":""));a.ended=!1,this.log("Removing [".concat(c,",").concat(d,"] from the ").concat(e," SourceBuffer")),s.remove(c,d)}},{key:"appendExecutor",value:function(e,t){var r=this,i=this.tracks[t],n=null==i?void 0:i.buffer;if(!n)throw new ro("Attempting to append to the ".concat(t," SourceBuffer, but it does not exist"));if(i.ending=!1,i.ended=!1,this.hls.config.appendTimeout!==1/0){var a=this.calculateAppendTimeoutTime(n);i.bufferAppendTimeoutId=self.setTimeout(function(){return r.appendTimeoutHandler(t,n,a)},a)}n.appendBuffer(e)}},{key:"appendTimeoutHandler",value:function(e,t,r){this.log("Received timeout after ".concat(r,"ms for append on ").concat(e," source buffer. Aborting and triggering error."));try{t.abort()}catch(t){this.log("Failed to abort append on ".concat(e," source buffer after timeout."))}var i=this.currentOp(e);i&&i.onError(new Error("".concat(e,"-append-timeout")))}},{key:"calculateAppendTimeoutTime",value:function(e){var t=10;this.details&&(t=this.details.levelTargetDuration);var r=2*t*1e3;if(null===this.media)return r;var i=Bi.bufferInfo(e,this.media.currentTime,0);return i.len?(r=Math.max(1e3*i.len,r),Math.max(this.hls.config.appendTimeout,r)):r}},{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=S(e,2),r=t[0],i=t[1];return r&&i.updating})}},{key:"isQueued",value:function(){var e=this;return this.sourceBuffers.some(function(t){var r=S(t,1)[0];return r&&!!e.currentOp(r)})}},{key:"isPending",value:function(e){return!!e&&!e.buffer}},{key:"isAudioBlocked",value:function(){var e;return"block-audio"===(null==(e=this.currentOp("audio"))?void 0:e.label)}},{key:"isAudioBlocking",value:function(){return!!this.operationQueue&&this.operationQueue.audioBlocking()}},{key:"blockBuffers",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.sourceBufferTypes;if(!r.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);var i=this.operationQueue,n=2===r.length&&this.isAudioBlocking()?[this.appendBlocker("video")]:r.map(function(e){return t.appendBlocker(e)});return Promise.all(n).then(function(r){i===t.operationQueue&&(e(),t.stepOperationQueue(t.sourceBufferTypes))})}},{key:"stepOperationQueue",value:function(e){var t=this;e.forEach(function(e){var r,i=null==(r=t.tracks[e])?void 0:r.buffer;!i||i.updating||"audio"===e&&t.isAudioBlocked()||t.shiftAndExecuteNext(e)})}},{key:"append",value:function(e,t,r){this.operationQueue&&this.operationQueue.append(e,t,r)}},{key:"insertNext",value:function(e,t){this.operationQueue&&this.operationQueue.insertNext(e,t)}},{key:"appendBlocker",value:function(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}},{key:"currentOp",value:function(e){return this.operationQueue?this.operationQueue.current(e):null}},{key:"executeNext",value:function(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}},{key:"shiftAndExecuteNext",value:function(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}},{key:"pendingTrackCount",get:function(){var e=this;return Object.keys(this.tracks).reduce(function(t,r){return t+(e.isPending(e.tracks[r])?1:0)},0)}},{key:"sourceBufferCount",get:function(){return this.sourceBuffers.reduce(function(e,t){return e+(S(t,1)[0]?1:0)},0)}},{key:"sourceBufferTypes",get:function(){return this.sourceBuffers.map(function(e){return S(e,1)[0]}).filter(function(e){return!!e})}},{key:"addBufferListener",value:function(e,t,r){var i=this.tracks[e];if(i){var n=i.buffer;if(n){var a=r.bind(this,e);i.listeners.push({event:t,listener:a}),ta(n,t,a)}}}},{key:"removeBufferListeners",value:function(e){var t=this.tracks[e];if(t){var r=t.buffer;r&&(t.listeners.forEach(function(e){ra(r,e.event,e.listener)}),t.listeners.length=0)}}}])}(Be);function no(e){var t=e.querySelectorAll("source");[].slice.call(t).forEach(function(t){e.removeChild(t)})}function ao(e){return"audio"===e?1:0}function so(e,t){return"".concat(e?"":" - triggering recovery").concat(t?" with HTMLMediaElement Error: "+t.message:"")}function oo(e){return"".concat(e.type,"_").concat(e.sn,"_").concat(e.level)}function lo(e,t){for(var r=t.start,i=t.end,n=0,a=0;a<e.length;a++){var s=e[a];if(s.start>=i)break;var o=Math.max(r,s.start),l=Math.min(i,s.end);l>o&&(n+=l-o)}return n}function uo(e,t){return t.duration-e<=.05}var co=function(){function e(t){s(this,e),this.hls=null,this.autoLevelCapping=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.observer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.media=null,this.restrictedLevels=[],this.clientRect=null,this.registerListeners()}return l(e,[{key:"setStreamController",value:function(e){this.streamController=e}},{key:"destroy",value:function(){this.hls&&this.unregisterListener(),(this.timer||this.observer)&&this.stopCapping(),this.media=this.clientRect=this.hls=null,this.streamController=void 0}},{key:"registerListeners",value:function(){var e=this.hls;e&&(e.on(ne.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(ne.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(ne.MANIFEST_PARSED,this.onManifestParsed,this),e.on(ne.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(ne.BUFFER_CODECS,this.onBufferCodecs,this),e.on(ne.MEDIA_DETACHING,this.onMediaDetaching,this))}},{key:"unregisterListener",value:function(){var e=this.hls;e&&(e.off(ne.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(ne.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(ne.MANIFEST_PARSED,this.onManifestParsed,this),e.off(ne.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(ne.BUFFER_CODECS,this.onBufferCodecs,this),e.off(ne.MEDIA_DETACHING,this.onMediaDetaching,this))}},{key:"onFpsDropLevelCapping",value:function(e,t){if(this.hls){var r=this.hls.levels[t.droppedLevel];this.isLevelAllowed(r)&&this.restrictedLevels.push({bitrate:r.bitrate,height:r.height,width:r.width})}}},{key:"onMediaAttaching",value:function(e,t){var r=t.media;this.clientRect=null,this.hls&&(r instanceof HTMLVideoElement?(this.media=r,this.hls.config.capLevelToPlayerSize&&this.observe()):this.media=null,(this.timer||this.observer)&&this.hls.levels.length>1&&this.detectPlayerSize())}},{key:"onManifestParsed",value:function(e,t){this.restrictedLevels=[],t.video&&this.startCapping(),this.onLevelsUpdated()}},{key:"onLevelsUpdated",value:function(){if(this.hls)if((this.timer||this.observer)&&(Z(this.autoLevelCapping)||this.clientRect))this.detectPlayerSize();else if(void 0===this.observer&&void 0===this.timer){var e=this.hls.levels;e.length>1&&e.some(function(e){return!!e.videoCodec})&&this.startCapping()}}},{key:"onBufferCodecs",value:function(e,t){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||!this.hls)return void(this.clientRect=null);var e=this.hls.levels;if(e.length>1){var t=this.hls,r=this.getMaxLevel(e.length-1);r!==this.autoLevelCapping&&t.logger.log("Setting autoLevelCapping to ".concat(r,": ").concat(e[r].height,"p@").concat(e[r].bitrate," for media ").concat(this.mediaWidth,"x").concat(this.mediaHeight)),t.autoLevelCapping=r,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}else 1===e.length&&this.stopCapping()}}},{key:"getMaxLevel",value:function(t){var r=this;if(!this.hls)return-1;var i=this.hls.levels;if(!i.length)return-1;var n=i.filter(function(e,i){return r.isLevelAllowed(e)&&i<=t});return this.observer||(this.clientRect=null),e.getMaxLevelByMediaSize(n,this.mediaWidth,this.mediaHeight)}},{key:"observe",value:function(){var e=this,t=self.ResizeObserver;t&&(this.observer=new t(function(t){var r,i=null==(r=t[0])?void 0:r.contentRect;i&&(e.clientRect=i,e.detectPlayerSize())})),this.observer&&this.media&&this.observer.observe(this.media)}},{key:"startCapping",value:function(){var e;this.timer||this.observer||null==(e=this.hls)||!e.config.capLevelToPlayerSize||(self.clearInterval(this.timer),this.timer=void 0,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.observe(),this.observer||(this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3)),this.detectPlayerSize())}},{key:"stopCapping",value:function(){this.restrictedLevels=[],this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0),this.observer&&(this.observer.disconnect(),this.observer=void 0)}},{key:"getDimensions",value:function(){if(this.clientRect)return this.clientRect;var e=this.media,t={width:0,height:0};if(e){var r=e.getBoundingClientRect();t.width=r.width,t.height=r.height,t.width||t.height||(t.width=r.right-r.left||e.width||0,t.height=r.bottom-r.top||e.height||0)}return this.clientRect=t,t}},{key:"mediaWidth",get:function(){return this.getDimensions().width*this.contentScaleFactor}},{key:"mediaHeight",get:function(){return this.getDimensions().height*this.contentScaleFactor}},{key:"contentScaleFactor",get:function(){var e=1;if(!this.hls)return e;var t=this.hls.config,r=t.ignoreDevicePixelRatio,i=t.maxDevicePixelRatio;if(!r)try{e=self.devicePixelRatio}catch(e){}return Math.min(e,i)}},{key:"isLevelAllowed",value:function(e){return!this.restrictedLevels.some(function(t){return e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height})}}],[{key:"getMaxLevelByMediaSize",value:function(e,t,r){if(null==e||!e.length)return-1;for(var i=function(e,t){return!t||(e.width!==t.width||e.height!==t.height)},n=e.length-1,a=Math.max(t,r),s=0;s<e.length;s+=1){var o=e[s];if((o.width>=a||o.height>=a)&&i(o,e[s+1])){n=s;break}}return n}}])}(),ho=l(function e(t,r){s(this,e),Array.isArray(t)&&(t=t.map(function(t){return t instanceof e?t:new e(t)})),this.value=t,this.params=r});function fo(e,t,r,i){return new Error("failed to ".concat(e,' "').concat((n=t,Array.isArray(n)?JSON.stringify(n):n instanceof Map?"Map{}":n instanceof Set?"Set{}":"object"===R(n)?JSON.stringify(n):String(n)),'" as ').concat(r),{cause:i});var n}var vo="Bare Item";var go=/[\x00-\x1f\x7f]+/,po=l(function e(t){s(this,e),this.description=t});function mo(e,t,r){return fo("serialize",e,t,r)}function yo(e){if(!1===ArrayBuffer.isView(e))throw mo(e,"Byte Sequence");return":".concat((t=e,btoa(String.fromCharCode.apply(String,b(t)))),":");var t}function ko(e){if(function(e){return e<-999999999999999||999999999999999<e}(e))throw mo(e,"Integer");return e.toString()}function Eo(e){var t=$e(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw mo(e,"Decimal");var r=t.toString();return r.includes(".")?r:"".concat(r,".0")}function So(e){var t,r=(t=e).description||t.toString().slice(7,-1);if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(r))throw mo(r,"Token");return r}function To(e){switch(R(e)){case"number":if(!Z(e))throw mo(e,vo);return Number.isInteger(e)?ko(e):Eo(e);case"string":return function(e){if(go.test(e))throw mo(e,"String");return'"'.concat(e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),'"')}(e);case"symbol":return So(e);case"boolean":return function(e){if("boolean"!=typeof e)throw mo(e,"Boolean");return e?"?1":"?0"}(e);case"object":if(e instanceof Date)return function(e){return"@".concat(ko(e.getTime()/1e3))}(e);if(e instanceof Uint8Array)return yo(e);if(e instanceof po)return So(e);default:throw mo(e,vo)}}function Ao(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw mo(e,"Key");return e}function bo(e){return null==e?"":Object.entries(e).map(function(e){var t=S(e,2),r=t[0],i=t[1];return!0===i?";".concat(Ao(r)):";".concat(Ao(r),"=").concat(To(i))}).join("")}function Io(e){return e instanceof ho?"".concat(To(e.value)).concat(bo(e.params)):To(e)}function Ro(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{whitespace:!0};if("object"!==R(e)||null==e)throw mo(e,"Dict");var r=e instanceof Map?e.entries():Object.entries(e),i=null!=t&&t.whitespace?" ":"";return Array.from(r).map(function(e){var t=S(e,2),r=t[0],i=t[1];i instanceof ho==!1&&(i=new ho(i));var n,a=Ao(r);return!0===i.value?a+=bo(i.params):(a+="=",Array.isArray(i.value)?a+="(".concat((n=i).value.map(Io).join(" "),")").concat(bo(n.params)):a+=Io(i)),a}).join(",".concat(i))}function Lo(e,t){return Ro(e,t)}var Po=["url"],wo=["version","eventTargets","sid","transmissionMode"],Co=["customData","headers"],Do=function(e){return e instanceof ho?new ho(Math.round(e.value),e.params):Math.round(e)},_o=function(e){return Array.isArray(e)?e.map(Do):Do(e)},Mo=function(e,t){return Array.isArray(e)?e.map(function(e){return Mo(e,t)}):e instanceof ho&&"string"==typeof e.value?new ho(Mo(e.value,t),e.params):(t.baseUrl&&(e=function(e,t){var r;try{r=new URL(e)}catch(t){return e}var i=new URL(t);if(r.origin!==i.origin)return e;for(var n=r.pathname.split("/").slice(1),a=i.pathname.split("/").slice(1,-1),s=Math.min(n.length,a.length),o=0;o<s&&n[o]===a[o];o++)n.shift(),a.shift();for(;a.length;)a.shift(),n.unshift("..");return n.join("/")+r.search+r.hash}(e,(r=t.baseUrl,(i="string"==typeof r?new URL(r):r).origin+i.pathname.substring(0,i.pathname.lastIndexOf("/")+1)))),1===t.version?encodeURIComponent(e):e);var r,i},xo=function(e){return e instanceof ho?new ho(100*Math.round(e.value/100),e.params):100*Math.round(e/100)},Oo=function(e){return Array.isArray(e)?e.map(xo):xo(e)},Fo={br:_o,d:_o,bl:Oo,dl:Oo,mtp:Oo,nor:function(e,t){var r=e;return t.version>=2&&(e instanceof ho&&"string"==typeof e.value?r=new ho([e]):"string"==typeof e&&(r=[e])),Mo(r,t)},rtp:Oo,tb:_o},No="rr",Bo="bc",Uo="e",Vo=No,Go="ce",Ho=new Map([["ps","sta"],["pr","pr"],["c","cid"],["b","bg"],["bc","br"]]),Ko="event",jo="request",qo=["cen","e","h","ts"],Wo=["ab","bg","bl","br","bs","bsa","bsd","bsda","cdn","cid","cs","d","dfa","dl","ec","lab","lb","ltc","msd","mtp","nor","nr","ot","pb","pr","pt","rtp","sf","sid","sn","st","sta","su","tab","tb","tbl","tpb","v"],Yo=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function zo(e){return Yo.test(e)}var Xo=new Set(Wo);function Qo(e){return Xo.has(e)||zo(e)}var $o=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],Jo=new Set($o);function Zo(e){return Jo.has(e)}var el=new Set(qo);var tl=new Set(["ab","bl","br","bsa","bsd","bsda","lab","lb","mtp","pb","tab","tb","tbl","tpb"]),rl=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"],il=new Set(rl);function nl(e){return il.has(e)||zo(e)}var al=new Set(["ot","sf","st","e","sta"]);function sl(e){return al.has(e)}function ol(e){return"number"==typeof e?Z(e):null!=e&&""!==e&&!1!==e}var ll=c(c({},Ko,function(e){return Qo(e)||Zo(e)||el.has(e)}),jo,Qo);function ul(e,t){var r;return Array.isArray(e)?(t&&(r=e.find(function(e){var r;return(null==(r=e.params)?void 0:r.ot)===t})),r||(r=e[0]),ul(r)):e instanceof ho?e.value:e}function cl(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r={};if(null==e||"object"!==R(e))return r;var i=t.version||e.v||2,n=t.reportingMode||jo,a=1===i?function(e){for(var t={},r=0,i=Object.entries(e);r<i.length;r++){var n=S(i[r],2),a=n[0],s=n[1];if(null!=s)if("nor"===a){var o,l=(Array.isArray(s)?s:[s])[0];l instanceof ho?(t.nor=l.value,null!=(o=l.params)&&o.r&&(t.nrr=l.params.r)):t.nor=l}else tl.has(a)?t[a]=ul(s,e.ot):t[a]=s;else t[a]=s}return t}(e):e,s=1===i?nl:ll[n],o=Object.keys(a).filter(s);a.e&&a.e!==No&&(o=o.filter(function(e){return!Zo(e)}));var l=t.filter;"function"==typeof l&&(o=o.filter(l));var c=n===Ko;if(c){var d=a.e;o.includes("e")||null==d||o.push("e"),o.includes("ts")||o.push("ts"),o.includes("cen")||null==a.cen||"ce"!==d||o.push("cen");var h=d?Ho.get(d):void 0;h&&null!=a[h]&&!o.includes(h)&&o.push(h)}if(0===o.length)return r;i>1&&!o.includes("v")&&o.push("v");var f={version:i,reportingMode:n,baseUrl:t.baseUrl};o.sort();var v,g=u(o);try{for(g.s();!(v=g.n()).done;){var p,m,y=v.value,k=a[y],E=null!=(p=null==(m=t.formatters)?void 0:m[y])?p:Fo[y];if("function"==typeof E&&(k=E(k,f)),"v"===y){if(1===i)continue;k=i}if("pr"!==y||1!==k||c&&"pr"===a.e){c&&"ts"===y&&!Z(k)&&(k=Date.now());var T=c&&!1===k&&"bg"===y&&"b"===a.e;(ol(k)||T)&&(sl(y)&&"string"==typeof k&&(k=new po(k)),r[y]=k)}}}catch(e){g.e(e)}finally{g.f()}return r}var dl="CMCD-Object",hl="CMCD-Request",fl="CMCD-Session",vl="CMCD-Status",gl=hl,pl={ab:dl,br:dl,d:dl,lab:dl,lb:dl,ot:dl,tab:dl,tb:dl,tpb:dl,bl:hl,cs:hl,dfa:hl,dl:hl,ltc:hl,mtp:hl,nor:hl,nrr:hl,pb:hl,sn:hl,sta:hl,su:hl,tbl:hl,cid:fl,msd:fl,sf:fl,sid:fl,st:fl,v:fl,bg:vl,bs:vl,bsa:vl,bsd:vl,bsda:vl,cdn:vl,ec:vl,nr:vl,pr:vl,pt:vl,rtp:vl};function ml(e,t){var r={};if(!e)return r;for(var i,n=Object.keys(e),a=t?(i=t,Object.keys(i).reduce(function(e,t){var r;return null==(r=i[t])||r.forEach(function(r){return e[r]=t}),e},{})):{},s=0,o=n;s<o.length;s++){var l,u=o[s],c=pl[u]||a[u]||gl;(null!=(l=r[c])?l:r[c]={})[u]=e[u]}return r}var yl="CMCD";function kl(e){return Lo(e,{whitespace:!1})}function El(e){return e?kl(cl(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})):""}var Sl=[].concat(rl,Wo,$o,qo).filter(function(e,t,r){return r.indexOf(e)===t}),Tl="m",Al="a",bl="v",Il="av",Rl="i",Ll="tt",Pl="s",wl="p",Cl="k",Dl="r",_l="a",Ml="e",xl="f",Ol="d",Fl="query",Nl="headers";function Bl(e,t,r){var i,n=new Set(null!=(i=t.enabledKeys)?i:[]);return{version:t.version||2,reportingMode:e,filter:function(e){return n.has(e)},baseUrl:r}}var Ul=Object.is,Vl=function(e){return e},Gl=Array.from(Ho,function(e){var t=S(e,2),r=t[0],i=t[1];return"br"===i?{event:r,field:i,equal:function(e,t){return void 0===e||void 0===t?e===t:function(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(var r=0;r<e.length;r++){var i=e[r],n=t[r];if(i!==n){if("number"==typeof i||"number"==typeof n)return!1;if(i.value!==n.value)return!1;var a=i.params,s=n.params,o=a&&Object.keys(a)[0],l=s&&Object.keys(s)[0];if(o!==l)return!1;if(void 0!==o&&void 0!==l&&a&&s&&a[o]!==s[l])return!1}}return!0}(e,t)},snapshot:function(e){return e.slice()}}:{event:r,field:i,equal:Ul,snapshot:Vl}}),Hl=new Map(Gl.map(function(e){return[e.event,e]}));function Kl(e){var t=e.url,r=Re(e,Po);return fetch(t,r)}var jl=function(){return l(function e(t){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Kl;s(this,e),this.timeOrigin=performance.timeOrigin||(null==(r=performance.timing)?void 0:r.fetchStart)||Date.now()-performance.now(),this.data={},this.msd=NaN,this.eventTargets=new Map,this.lastEmitted={},this.requestTarget={sn:0,msdSent:!1},this.config=function(e){var t=e.version,r=void 0===t?2:t,i=e.eventTargets,n=void 0===i?[]:i,a=e.sid,s=void 0===a?Je():a,o=e.transmissionMode,l=void 0===o?Fl:o;return Ie(Ie({},Re(e,wo)),{},{version:r,transmissionMode:l,sid:s,eventTargets:n.reduce(function(e,t){var r,i,n;return null!=t&&t.url&&null!=(r=t.events)&&r.length&&e.push({version:t.version||2,enabledKeys:(null==(i=t.enabledKeys)?void 0:i.slice())||[],url:t.url,events:t.events.slice(),interval:null!=(n=t.interval)?n:30,batchSize:t.batchSize||1}),e},[])})}(t),this.data={cid:this.config.cid,sid:this.config.sid,v:this.config.version},this.requester=i;var n,a=u(this.config.eventTargets);try{for(a.s();!(n=a.n()).done;){var o=n.value;this.eventTargets.set(o,{intervalId:void 0,sn:0,msdSent:!1,queue:[]})}}catch(e){a.e(e)}finally{a.f()}},[{key:"start",value:function(){var e=this;this.eventTargets.forEach(function(t,r){if(e.disarmInterval(t),0!==r.interval&&r.events.includes("t")){var i=function(){e.recordTargetEvent(t,r,"t"),e.processEventTargets()};t.intervalId=setInterval(i,1e3*r.interval),i()}})}},{key:"stop",value:function(){var e=this;arguments.length>0&&void 0!==arguments[0]&&arguments[0]&&this.flush(),this.eventTargets.forEach(function(t){e.disarmInterval(t)})}},{key:"flush",value:function(){this.processEventTargets(!0)}},{key:"update",value:function(e){e.sid&&e.sid!==this.data.sid&&this.resetSession(),e.msd&&!isNaN(e.msd)&&(this.msd=e.msd),this.data=Ie(Ie(Ie({},this.data),e),{},{msd:void 0});for(var t=0,r=Gl;t<r.length;t++){var i=r[t];i.field in e&&!i.equal(this.data[i.field],this.lastEmitted[i.field])&&this.recordEvent(i.event)}}},{key:"recordEvent",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=Hl.get(e);if(i){var n=i.field,a=r[n];void 0!==a&&Ae(this.data,c({},n,a));var s=this.data[n];if(void 0===s)return;if(i.equal(s,this.lastEmitted[n]))return;Ae(this.lastEmitted,c({},n,i.snapshot(s)))}this.eventTargets.forEach(function(i,n){t.recordTargetEvent(i,n,e,r)}),this.processEventTargets()}},{key:"recordTargetEvent",value:function(e,t,r){var i,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};if(t.events.includes(r)){var a=Ie(Ie(Ie({},this.data),n),{},{e:r,ts:null!=(i=n.ts)?i:Date.now(),sn:e.sn++});isNaN(this.msd)||e.msdSent||(a.msd=this.msd,e.msdSent=!0),e.queue.push(a)}}},{key:"recordResponseReceived",value:function(e){var t,r,i,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=e.request,s=null!=(t=n.url)?t:null==a?void 0:a.url;if(s){var o=new URL(s);o.searchParams.delete(yl);var l={url:o.toString(),rc:e.status},u=e.resourceTiming;u&&(null!=u.startTime&&(l.ts=Math.round(this.timeOrigin+u.startTime),null!=u.responseStart&&(l.ttfb=Math.round(u.responseStart-u.startTime))),null!=u.duration&&(l.ttlb=Math.round(u.duration)));var c=null!=(r=null==(i=a.customData)?void 0:i.cmcd)?r:{};this.recordEvent(No,Ie(Ie(Ie({},c),l),n))}}},{key:"applyRequestReport",value:function(e){var t;return null!=(t=this.createRequestReport(e))?t:e}},{key:"isRequestReportingEnabled",value:function(){var e;return!(null==(e=this.config.enabledKeys)||!e.length)}},{key:"createRequestReport",value:function(e,t){var r,i=e.customData,n=void 0===i?{}:i,a=e.headers,s=void 0===a?{}:a,o=Ie(Ie({},Re(e,Co)),{},{headers:Ie({},s),customData:Ie(Ie({},n),{},{cmcd:{}})});if(null==(r=this.config.enabledKeys)||!r.length||!o.url)return o;var l=new URL(o.url),u=Ie(Ie(Ie({},this.data),t),{},{sn:this.requestTarget.sn++}),c=Bl(jo,this.config,o.url);isNaN(this.msd)||this.requestTarget.msdSent||(u.msd=this.msd,this.requestTarget.msdSent=!0);var d=o.customData.cmcd=cl(u,c);switch(this.config.transmissionMode){case Fl:var h=kl(d);h&&(l.searchParams.set(yl,h),o.url=l.toString());break;case Nl:Ae(o.headers,function(e,t){for(var r={},i=ml(e,t),n=0,a=Object.entries(i);n<a.length;n++){var s=S(a[n],2),o=s[0],l=Lo(s[1],{whitespace:!1});l&&(r[o]=l)}return r}(d,c.customHeaderMap))}return o}},{key:"processEventTargets",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],r=!1;this.eventTargets.forEach(function(i,n){var a=i.queue;if(a.length&&(!(a.length<n.batchSize)||t)){var s=t?a.length:n.batchSize,o=a.splice(0,s);e.sendEventReport(n,o).catch(function(){var e;(e=i.queue).unshift.apply(e,b(o))}),r||(r=a.length>0)}}),r&&this.processEventTargets()}},{key:"sendEventReport",value:(e=y().m(function e(t,r){var i,n,a;return y().w(function(e){for(;;)switch(e.n){case 0:return i=Bl(Ko,t),e.n=1,this.requester({url:t.url,method:"POST",headers:{"Content-Type":"application/cmcd"},body:r.map(function(e){return El(e,i)}).join("\n")+"\n"});case 1:if(n=e.v,410!==(a=n.status)){e.n=2;break}this.disposeEventTarget(t),e.n=3;break;case 2:if(!(429===a||a>499&&a<600)){e.n=3;break}throw new Error("Event report failed with status ".concat(a));case 3:return e.a(2)}},e,this)}),t=function(){var t=this,r=arguments;return new Promise(function(i,a){var s=e.apply(t,r);function o(e){n(s,i,a,o,l,"next",e)}function l(e){n(s,i,a,o,l,"throw",e)}o(void 0)})},function(e,r){return t.apply(this,arguments)})},{key:"disarmInterval",value:function(e){clearInterval(e.intervalId),e.intervalId=void 0}},{key:"disposeEventTarget",value:function(e){var t=this.eventTargets.get(e);t&&(this.disarmInterval(t),this.eventTargets.delete(e))}},{key:"resetSession",value:function(){this.eventTargets.forEach(function(e){return e.sn=0}),this.requestTarget.sn=0,this.lastEmitted={}}}]);var e,t}(),ql="h",Wl="v",Yl="l",zl="ll";new Set(rl),new Set(Sl);var Xl=["includeKeys"];function Ql(e){return Object.keys(e).every(zo)}var $l=function(){return l(function e(t){var r=this;s(this,e),this.hls=void 0,this.config=void 0,this.media=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.playerState=void 0,this.reporter=void 0,this.playheadLevel=void 0,this.onWaiting=function(){r.initialized&&(r.starved=!0,r.setPlayerState(Dl)),r.buffering=!0},this.onPlay=function(){r.initialized||r.setPlayerState(Pl)},this.onPlaying=function(){r.initialized||(r.initialized=!0),r.buffering=!1,r.setPlayerState(wl)},this.onPause=function(){r.media&&!r.media.ended&&r.setPlayerState(_l)},this.onSeeking=function(){r.initialized&&r.setPlayerState(Cl)},this.onSeeked=function(){var e;r.initialized&&null!=(e=r.media)&&e.paused&&r.setPlayerState(_l)},this.onRateChange=function(){r.reporter&&r.media&&r.reporter.update({pr:r.media.playbackRate})},this.applyPlaylistData=function(e){try{r.apply(e,{ot:Tl,su:!r.initialized})}catch(e){r.hls.logger.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=function(e){try{var t=e.frag,i=e.part,n=r.hls.levels[t.level],a=r.getObjectType(t,n),s={d:1e3*(i||t).duration,ot:a};if(a===bl||a===Al||a===Il||null==a&&("main"===t.type||"audio"===t.type)){var o,l=n.bitrate/1e3;s.br=[l];var u=r.config.cmcd,c=null!=(o=null==u?void 0:u.rtpSafetyFactor)?o:5;if(s.rtp=100*Math.round(l*c/100),a===Il||null==a&&"main"===t.type){var d=r.getTopBandwidth()/1e3;Z(d)&&(s.tb=[d]);var h=r.getLowestBandwidth()/1e3;Z(h)&&(s.lb=[h])}var f=r.getBufferLength(t);if(Z(f)){var v;s.bl=[f];var g=(null==(v=r.media)?void 0:v.playbackRate)||1;s.dl=100*Math.round(f/g/100)}r.playheadLevel&&(s.pb=[r.playheadLevel.bitrate/1e3]);var p=r.hls.maxAutoLevel;if(p>=0){var m=r.hls.levels[p];m&&(s.tpb=[m.bitrate/1e3])}}var y=i?r.getNextPart(i):r.getNextFrag(t);null!=y&&y.url&&y.url!==t.url&&(y.byteRange.length>0?s.nor=[(k=y.url,E={r:"".concat(y.byteRange[0],"-").concat(y.byteRange[1])},new ho(k,E))]:s.nor=[y.url]),r.apply(e,s)}catch(e){r.hls.logger.warn("Could not generate segment CMCD data.",e)}var k,E},this.recordFragmentResponse=function(e,t,i){var n,a=r.config.cmcd,s=null==a||null==(n=a.eventTargets)?void 0:n.some(function(e){var t;return null==(t=e.events)?void 0:t.includes(Vo)});if(r.reporter&&i.loading.first>0&&s)try{r.reporter.recordResponseReceived({request:{url:e},status:t.code,resourceTiming:{startTime:i.loading.start,responseStart:i.loading.first,duration:i.loading.end-i.loading.start,encodedBodySize:i.total}})}catch(e){r.hls.logger.warn("Could not record fragment response CMCD data.",e)}},this.hls=t;var i=this.config=t.config;null!=i.cmcd&&(i.pLoader=this.createPlaylistLoader(),i.fLoader=this.createFragmentLoader(),this.registerListeners())},[{key:"createReporter",value:function(){var e,t,r=this.config.cmcd;if(null!=r){var i=r.version||1;if(this.reporter=new jl({sid:r.sessionId||this.hls.sessionId,cid:r.contentId,version:i,transmissionMode:!0===r.useHeaders?Nl:Fl,enabledKeys:null!=(e=r.includeKeys)?e:b(i>=2?Sl:rl),eventTargets:(null!=(t=r.eventTargets)?t:[]).map(function(e){var t=e.includeKeys;return Ie(Ie({},Re(e,Xl)),{},{enabledKeys:null!=t?t:Sl})})},r.loader),this.reporter.update({sf:ql,sta:this.playerState}),r.reporterCallback){var n=this.reporter,a={updateCustomData:function(e){Ql(e)&&n.update(e)},recordCustomEvent:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};Ql(t)&&n.recordEvent(Go,Ie({cen:e},t))}};r.reporterCallback(a)}this.reporter.start()}}},{key:"registerListeners",value:function(){var e=this.hls;e.on(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ne.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(ne.MEDIA_DETACHED,this.onMediaDetached,this),e.on(ne.MEDIA_ENDED,this.onMediaEnded,this),e.on(ne.ERROR,this.onError,this),e.on(ne.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(ne.LEVEL_SWITCHED,this.onLevelSwitched,this),e.on(ne.BUFFER_APPENDED,this.onBufferInfoChange,this),e.on(ne.BUFFER_FLUSHED,this.onBufferInfoChange,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ne.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(ne.MEDIA_DETACHED,this.onMediaDetached,this),e.off(ne.MEDIA_ENDED,this.onMediaEnded,this),e.off(ne.ERROR,this.onError,this),e.off(ne.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(ne.LEVEL_SWITCHED,this.onLevelSwitched,this),e.off(ne.BUFFER_APPENDED,this.onBufferInfoChange,this),e.off(ne.BUFFER_FLUSHED,this.onBufferInfoChange,this)}},{key:"destroy",value:function(){this.unregisterListeners(),this.onMediaDetached(),this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.hls=this.config=null,this.onWaiting=this.onPlay=this.onPlaying=this.onPause=null,this.onSeeking=this.onSeeked=this.onRateChange=this.media=null}},{key:"onMediaAttaching",value:function(e,t){var r=this.media=t.media;this.setPlayerState(this.media.autoplay?Pl:Ol),ta(r,"waiting",this.onWaiting),ta(r,"play",this.onPlay),ta(r,"playing",this.onPlaying),ta(r,"pause",this.onPause),ta(r,"seeking",this.onSeeking),ta(r,"seeked",this.onSeeked),ta(r,"ratechange",this.onRateChange)}},{key:"onMediaDetached",value:function(){var e=this.media;e&&(ra(e,"waiting",this.onWaiting),ra(e,"play",this.onPlay),ra(e,"playing",this.onPlaying),ra(e,"pause",this.onPause),ra(e,"seeking",this.onSeeking),ra(e,"seeked",this.onSeeked),ra(e,"ratechange",this.onRateChange),this.media=null)}},{key:"onMediaEnded",value:function(e,t){this.setPlayerState(Ml)}},{key:"onManifestLoading",value:function(e,t){this.initialized=!1,this.starved=!1,this.buffering=!0,this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.createReporter(),this.media||this.setPlayerState(Ol)}},{key:"onError",value:function(e,t){t.fatal&&(this.setPlayerState(xl),this.reporter&&this.reporter.recordEvent(Uo,{ec:[t.details]}))}},{key:"onLevelSwitching",value:function(e,t){var r;if(this.reporter){var i={br:[t.bitrate/1e3]},n=null==(r=t.details)?void 0:r.fragments[0];n&&(i.ot=this.getObjectType(n,t)),this.reporter.recordEvent(Bo,i)}}},{key:"onLevelSwitched",value:function(e,t){var r=this.hls.levels[t.level];r&&(this.playheadLevel=r)}},{key:"setPlayerState",value:function(e){this.playerState=e,this.reporter&&this.reporter.update({sta:e})}},{key:"getStreamType",value:function(){var e=this.hls.latestLevelDetails;if(e)return e.live?e.partList&&e.canBlockReload?zl:Yl:Wl}},{key:"apply",value:function(e){var t,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.reporter){this.reporter.update({mtp:[this.hls.bandwidthEstimate/1e3],pr:null==(t=this.media)?void 0:t.playbackRate,st:this.getStreamType()});var i=r.ot===Rl||r.ot===bl||r.ot===Il;this.starved&&i&&(r.bs=!0,r.su=!0,this.starved=!1),null==r.su&&(r.su=this.buffering);var n=this.reporter.createRequestReport({url:e.url,headers:e.headers},r);e.url=n.url,e.headers=n.headers}}},{key:"getNextFrag",value:function(e){var t,r=null==(t=this.hls.levels[e.level])?void 0:t.details;if(r){var i=e.sn-r.startSN;return r.fragments[i+1]}}},{key:"getNextPart",value:function(e){var t,r=e.index,i=e.fragment,n=null==(t=this.hls.levels[i.level])||null==(t=t.details)?void 0:t.partList;if(n)for(var a=i.sn,s=n.length-1;s>=0;s--){var o=n[s];if(o.index===r&&o.fragment.sn===a)return n[s+1]}}},{key:"getObjectType",value:function(e,t){var r=e.type;if("subtitle"===r)return Ll;if("initSegment"===e.sn)return Rl;if("audio"===r)return Al;if("main"===r){if(e.hasStreams){var i=e.elementaryStreams;if(i.audiovideo)return Il;if(i.video)return bl;if(i.audio)return Al}if(t){var n=t.audioCodec,a=t.videoCodec;if(!this.hls.audioTracks.length){if(n&&a)return Il;if(n)return Al}if(a)return bl}}}},{key:"getTopBandwidth",value:function(){var e=0,t=this.hls,r=t.maxAutoLevel,i=r>-1?r+1:t.levels.length;return t.levels.slice(0,i).forEach(function(t){t.bitrate>e&&(e=t.bitrate)}),e>0?e:NaN}},{key:"getLowestBandwidth",value:function(){var e=1/0,t=this.hls,r=t.maxAutoLevel,i=r>-1?r+1:t.levels.length;return t.levels.slice(0,i).forEach(function(t){t.bitrate<e&&(e=t.bitrate)}),Z(e)?e:NaN}},{key:"getBufferLength",value:function(e){if(!this.media)return NaN;var t="audio"===e.type?this.hls.audioForwardBufferInfo:this.hls.mainForwardBufferInfo;return t?1e3*t.len:NaN}},{key:"getEventBufferLength",value:function(){if(!this.media)return NaN;var e=this.hls.mainForwardBufferInfo,t=this.hls.audioForwardBufferInfo;if(e&&t)return 1e3*Math.min(e.len,t.len);var r=e||t;return r?1e3*r.len:NaN}},{key:"onBufferInfoChange",value:function(e,t){if(this.reporter){var r=this.getEventBufferLength();Z(r)&&this.reporter.update({bl:[r]})}}},{key:"createPlaylistLoader",value:function(){var e=this.config.pLoader,t=this.applyPlaylistData,r=e||this.config.loader;return function(){return l(function e(t){s(this,e),this.loader=void 0,this.loader=new r(t)},[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}},{key:"destroy",value:function(){this.loader.destroy()}},{key:"abort",value:function(){this.loader.abort()}},{key:"load",value:function(e,r,i){t(e),this.loader.load(e,r,i)}}])}()}},{key:"createFragmentLoader",value:function(){var e=this.config.fLoader,t=this.applyFragmentData,r=this.recordFragmentResponse,i=e||this.config.loader;return function(){return l(function e(t){s(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,n){t(e);var a=n.onSuccess;this.loader.load(e,i,Ie(Ie({},n),{},{onSuccess:function(t,i,n,s){a(t,i,n,s),r(e.url,t,i)}}))}}])}()}}])}(),Jl=function(e){function t(e){var r;return s(this,t),(r=a(this,t,["content-steering",e.logger])).hls=void 0,r.loader=null,r.uri=null,r.pathwayId=".",r._pathwayPriority=null,r.timeToLoad=300,r.reloadTimer=-1,r.updated=0,r.started=!1,r.enabled=!0,r.levels=null,r.audioTracks=null,r.subtitleTracks=null,r.penalizedPathways={},r.hls=e,r.registerListeners(),r}return f(t,e),l(t,[{key:"registerListeners",value:function(){var e=this.hls;e.on(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ne.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(ne.MANIFEST_PARSED,this.onManifestParsed,this),e.on(ne.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ne.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(ne.MANIFEST_PARSED,this.onManifestParsed,this),e.off(ne.ERROR,this.onError,this))}},{key:"pathways",value:function(){return(this.levels||[]).reduce(function(e,t){return-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e},[])}},{key:"pathwayPriority",get:function(){return this._pathwayPriority},set:function(e){this.updatePathwayPriority(e)}},{key:"startLoad",value:function(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){var e=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}}},{key:"stopLoad",value:function(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}},{key:"clearTimeout",value:function(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}},{key:"destroy",value:function(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}},{key:"removeLevel",value:function(e){var t=this.levels;t&&(this.levels=t.filter(function(t){return t!==e}))}},{key:"onManifestLoading",value:function(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}},{key:"onManifestLoaded",value:function(e,t){var r=t.contentSteering;null!==r&&(this.pathwayId=r.pathwayId,this.uri=r.uri,this.started&&this.startLoad())}},{key:"onManifestParsed",value:function(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}},{key:"onError",value:function(e,t){var r=t.errorAction;if((null==r?void 0:r.action)===ri&&r.flags&si){var i=this.levels,n=this._pathwayPriority,a=this.pathwayId;if(t.context){var s=t.context,o=s.groupId,l=s.pathwayId,u=s.type;o&&i?a=this.getPathwayForGroupId(o,u,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!n&&i&&(n=this.pathways()),n&&n.length>1&&(this.updatePathwayPriority(n),r.resolved=this.pathwayId!==a,r.resolved||t.details===ie.BUFFER_APPEND_ERROR&&!t.fatal||this.warn("Could not resolve ".concat(t.details,' ("').concat(t.error.message,'") with content-steering for Pathway: ').concat(a," levels: ").concat(i?i.length:i," priorities: ").concat(Nr(n)," penalized: ").concat(Nr(this.penalizedPathways))))}}},{key:"filterParsedLevels",value:function(e){this.levels=e;var t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){var r=e[0].pathwayId;this.log("No levels found in Pathway ".concat(this.pathwayId,'. Setting initial Pathway to "').concat(r,'"')),t=this.getLevelsForPathway(r),this.pathwayId=r}return t.length!==e.length&&this.log("Found ".concat(t.length,"/").concat(e.length,' levels in Pathway "').concat(this.pathwayId,'"')),t}},{key:"getLevelsForPathway",value:function(e){return null===this.levels?[]:this.levels.filter(function(t){return e===t.pathwayId})}},{key:"updatePathwayPriority",value:function(e){var t;this._pathwayPriority=e;var r=this.penalizedPathways,i=performance.now();Object.keys(r).forEach(function(e){i-r[e]>3e5&&delete r[e]});for(var n=0;n<e.length;n++){var a=e[n];if(!(a in r)){if(a===this.pathwayId)return;var s=this.hls.nextLoadLevel,o=this.hls.levels[s];if((t=this.getLevelsForPathway(a)).length>0){this.log('Setting Pathway to "'.concat(a,'"')),this.pathwayId=a,zn(t),this.hls.trigger(ne.LEVELS_UPDATED,{levels:t});var l=this.hls.levels[s];o&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==o.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==o.bitrate&&this.log("Unstable Pathways change from bitrate ".concat(o.bitrate," to ").concat(l.bitrate)),this.hls.nextLoadLevel=s);break}}}}},{key:"getPathwayForGroupId",value:function(e,t,r){for(var i=this.getLevelsForPathway(r).concat(this.levels||[]),n=0;n<i.length;n++)if(t===ce.AUDIO_TRACK&&i[n].hasAudioGroup(e)||t===ce.SUBTITLE_TRACK&&i[n].hasSubtitleGroup(e))return i[n].pathwayId;return r}},{key:"clonePathways",value:function(e){var t=this,r=this.levels;if(r){var i={},n={};e.forEach(function(e){var a=e.ID,s=e["BASE-ID"],o=e["URI-REPLACEMENT"];if(!r.some(function(e){return e.pathwayId===a})){var l=t.getLevelsForPathway(s).map(function(e){var t=new Wi(e.attrs);t["PATHWAY-ID"]=a;var r=t.AUDIO&&"".concat(t.AUDIO,"_clone_").concat(a),s=t.SUBTITLES&&"".concat(t.SUBTITLES,"_clone_").concat(a);r&&(i[t.AUDIO]=r,t.AUDIO=r),s&&(n[t.SUBTITLES]=s,t.SUBTITLES=s);var l=eu(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",o),u=new xr({attrs:t,audioCodec:e.audioCodec,bitrate:e.bitrate,height:e.height,name:e.name,url:l,videoCodec:e.videoCodec,width:e.width});if(e.audioGroups)for(var c=1;c<e.audioGroups.length;c++)u.addGroupId("audio","".concat(e.audioGroups[c],"_clone_").concat(a));if(e.subtitleGroups)for(var d=1;d<e.subtitleGroups.length;d++)u.addGroupId("text","".concat(e.subtitleGroups[d],"_clone_").concat(a));return u});r.push.apply(r,b(l)),Zl(t.audioTracks,i,o,a),Zl(t.subtitleTracks,n,o,a)}})}}},{key:"loadSteeringManifest",value:function(e){var t,r=this,i=this.hls.config,n=i.loader;this.loader&&this.loader.destroy(),this.loader=new n(i);try{t=new self.URL(e)}catch(t){return this.enabled=!1,void this.log("Failed to parse Steering Manifest URI: ".concat(e))}if("data:"!==t.protocol){var a=0|(this.hls.bandwidthEstimate||i.abrEwmaDefaultEstimate);Rr(t,"_HLS_pathway",this.pathwayId),Rr(t,"_HLS_throughput",""+a)}var s={type:ce.STEERING_MANIFEST,responseType:"json",url:t.href},o=i.steeringManifestLoadPolicy.default,l=o.errorRetry||o.timeoutRetry||{},u={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:l.maxNumRetry||0,retryDelay:l.retryDelayMs||0,maxRetryDelay:l.maxRetryDelayMs||0},c={onSuccess:function(e,i,n,a){r.log('Loaded steering manifest: "'.concat(t,'"'));var s=e.data;if(1===(null==s?void 0:s.VERSION)){r.updated=performance.now(),r.timeToLoad=s.TTL;var o=s["RELOAD-URI"],l=s["PATHWAY-CLONES"],u=s["PATHWAY-PRIORITY"];if(o)try{r.uri=new self.URL(o,t).href}catch(e){return r.enabled=!1,void r.log("Failed to parse Steering Manifest RELOAD-URI: ".concat(o))}r.scheduleRefresh(r.uri||n.url),l&&r.clonePathways(l);var c={steeringManifest:s,url:t.toString()};r.hls.trigger(ne.STEERING_MANIFEST_LOADED,c),u&&r.updatePathwayPriority(u)}else r.log("Steering VERSION ".concat(s.VERSION," not supported!"))},onError:function(e,t,i,n){if(r.log("Error loading steering manifest: ".concat(e.code," ").concat(e.text," (").concat(t.url,")")),r.stopLoad(),410===e.code)return r.enabled=!1,void r.log("Steering manifest ".concat(t.url," no longer available"));var a=1e3*r.timeToLoad;if(429!==e.code)r.scheduleRefresh(r.uri||t.url,a);else{var s=r.loader;if("function"==typeof(null==s?void 0:s.getResponseHeader)){var o=s.getResponseHeader("Retry-After");o&&(a=1e3*parseFloat(o))}r.log("Steering manifest ".concat(t.url," rate limited"))}},onTimeout:function(e,t,i){r.log("Timeout loading steering manifest (".concat(t.url,")")),r.scheduleRefresh(r.uri||t.url)}};this.log("Requesting steering manifest: ".concat(t)),this.loader.load(s,u,c)}},{key:"scheduleRefresh",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1e3*this.timeToLoad;this.clearTimeout(),this.reloadTimer=self.setTimeout(function(){var r,i=null==(r=t.hls)?void 0:r.media;!i||i.ended?t.scheduleRefresh(e,1e3*t.timeToLoad):t.loadSteeringManifest(e)},r)}}])}(Be);function Zl(e,t,r,i){e&&Object.keys(t).forEach(function(n){var a=e.filter(function(e){return e.groupId===n}).map(function(e){var a=Ae({},e);return a.details=void 0,a.attrs=new Wi(a.attrs),a.url=a.attrs.URI=eu(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",r),a.groupId=a.attrs["GROUP-ID"]=t[n],a.attrs["PATHWAY-ID"]=i,a});e.push.apply(e,b(a))})}function eu(e,t,r,i){if(t){var n=i[r];if(n){var a=n[t];if(a)return a}}var s=i.HOST,o=i.PARAMS,l=new self.URL(e);return s&&(l.hostname=s),o&&Object.keys(o).sort().forEach(function(e){e&&Rr(l,e,o[e])}),l.href}var tu=function(){return l(function e(){s(this,e),this.status="initialized",this.requestErrors=[],this.licenseXhr=void 0,this.onmessage=void 0,this.onkeystatuseschange=void 0,this.emitter=new Aa,this.error=void 0,this.ok=void 0},[{key:"errored",get:function(){return this.error},set:function(e){this.error=e,this.emitter.eventNames().length&&this.emitter.emit("error",e)}},{key:"hasListeners",get:function(){return this.emitter.eventNames().length>0}},{key:"resolved",get:function(){return this.ok}},{key:"resolve",value:function(){this.ok=!0,this.emitter.emit("resolved")}},{key:"useable",get:function(){var e=this;return this.ok?Promise.resolve():this.error?Promise.reject(this.error):new Promise(function(t,r){e.emitter.on("error",r),e.emitter.on("resolved",t)})}},{key:"reset",value:function(){this.emitter.removeAllListeners();var e=this.licenseXhr;e&&(e.readyState!==XMLHttpRequest.DONE&&e.abort(),this.licenseXhr=void 0),this.onmessage=this.onkeystatuseschange=void 0}}])}(),ru=function(e){function t(e,r){var i;return s(this,t),(i=a(this,t,[r])).data=void 0,e.error||(e.error=new Error(r)),i.data=e,e.err=e.error,i}return f(t,e),l(t)}(w(Error)),iu=function(e){function t(e){var r;return s(this,t),(r=a(this,t,["eme",e.logger])).hls=void 0,r.config=void 0,r.media=null,r.mediaResolved=void 0,r.keyFormatPromise=null,r.keySystemAccessPromises={},r.sessionSetupByUri={},r.mediaKeySessions=[],r.activeKeys={},r.mediaKeys=null,r.setMediaKeysQueue=t.CDMCleanupPromise?[t.CDMCleanupPromise]:[],r.onMediaEncrypted=function(e){var t=e.initDataType,i=e.initData,n='"'.concat(e.type,'" event: init data type: "').concat(t,'"');if(r.log(n),null!==i){if(!r.keyFormatPromise){var a=Object.keys(r.keySystemAccessPromises);a.length||(a=vn(r.config));var s=a.map(fn).filter(function(e){return!!e});r.keyFormatPromise=r.getKeyFormatPromise(s)}r.keyFormatPromise.then(function(a){var s,o,l=dn(a),u=r.activeLevelKeys();if(l===sn.FAIRPLAY&&"sinf"===t)try{var c=pt(new Uint8Array(i)),d=Vt(gt(JSON.parse(c).sinf));if(!d)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");s=new Uint8Array(d.subarray(8,24))}catch(e){return void r.warn("".concat(n," Failed to parse sinf: ").concat(e))}else if(l===sn.PLAYREADY)s=mn(new Uint8Array(i));else if(l===sn.WIDEVINE){var h=Xt(i).filter(function(e){return e.systemId===hn});if(h.length){var f,v=h[0];s=null!=(f=v.kids)&&f.length?v.kids[0]:null}}if(s)for(var g=ft(s),p=0;p<u.length;p++){var m=u[p];if(m.keyId&&($i(s,m.keyId)||-1!==m.uri.replace(/-/g,"").indexOf(g))){m.pssh||(m.scheme=t,m.pssh=new Uint8Array(i),m.keyId=s,kn.setKeyIdForUri(m.uri,s)),o=r.getSessionForKey(m,"encrypted-event-key-match");break}}if(!o){var y,k;if(u.length)return(y=u[0]).scheme||(y.scheme=t),(k=u[0]).pssh||(k.pssh=new Uint8Array(i)),r.getSessionForKey(u[0],"encrypted-event-no-match");if(s)throw new Error("Key ID ".concat(ft(s)," not encountered in playlist"));r.log('Ignoring "'.concat(e.type,'" event - could not determine keyId'))}return o}).catch(function(e){return r.handleError(e)})}},r.onWaitingForKey=function(e){r.log('"'.concat(e.type,'" event'))},r.hls=e,r.config=e.config,r.registerListeners(),r}return f(t,e),l(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=null,this.onMediaEncrypted=this.onWaitingForKey=null}},{key:"registerListeners",value:function(){var e=this.hls;e&&(e.on(ne.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ne.MEDIA_DETACHED,this.onMediaDetached,this),e.on(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ne.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(ne.DESTROYING,this.onDestroying,this))}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ne.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ne.MEDIA_DETACHED,this.onMediaDetached,this),e.off(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ne.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(ne.DESTROYING,this.onDestroying,this))}},{key:"attemptKeySystemAccess",value:function(e){var t=this;if(!this.hls)return Promise.reject(new Error("destroyed"));var r=this.hls.levels,i=function(e,t,r){return!!e&&r.indexOf(e)===t},n=r.map(function(e){return e.audioCodec}).filter(i),a=r.map(function(e){return e.videoCodec}).filter(i);return n.length+a.length===0&&a.push("avc1.42e01e"),new Promise(function(r,i){var s=function(e){var o=e.shift();t.getMediaKeysPromise(o,n,a).then(function(e){return r({keySystem:o,mediaKeys:e})}).catch(function(t){e.length?s(e):i(t instanceof ru?t:new ru({type:re.KEY_SYSTEM_ERROR,details:ie.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))})};s(e)})}},{key:"requestMediaKeySystemAccess",value:function(e,t){var r=this.config.requestMediaKeySystemAccessFunc;if("function"!=typeof r){var i="Configured requestMediaKeySystemAccess is not a function ".concat(r);return null===pn&&"http:"===self.location.protocol&&(i="navigator.requestMediaKeySystemAccess is not available over insecure protocol ".concat(location.protocol)),Promise.reject(new Error(i))}return r(e,t)}},{key:"getMediaKeysPromise",value:function(e,t,r){var i,n=this,a=function(e,t,r,i){var n;switch(e){case sn.FAIRPLAY:n=["cenc","sinf"];break;case sn.WIDEVINE:case sn.PLAYREADY:n=["cenc"];break;case sn.CLEARKEY:n=["cenc","keyids"];break;default:throw new Error("Unknown key-system: ".concat(e))}return function(e,t,r,i){return[{initDataTypes:e,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:t.map(function(e){return{contentType:"audio/mp4; codecs=".concat(e),robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null}}),videoCapabilities:r.map(function(e){return{contentType:"video/mp4; codecs=".concat(e),robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}})}]}(n,t,r,i)}(e,t,r,this.config.drmSystemOptions||{}),s=this.keySystemAccessPromises[e],o=null==(i=s)?void 0:i.keySystemAccess;if(!o){this.log('Requesting encrypted media "'.concat(e,'" key-system access with config: ').concat(Nr(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.throwIfDestroyed(),n.log('Access for key-system "'.concat(t.keySystem,'" obtained'));var r=n.fetchServerCertificate(e);n.log('Create media-keys for "'.concat(e,'"'));var i=l.mediaKeys=t.createMediaKeys().then(function(t){return n.log('Media-keys created for "'.concat(e,'"')),l.hasMediaKeys=!0,r.then(function(r){return r?n.setMediaKeysServerCertificate(t,e,r):t})});return i.catch(function(t){n.error('Failed to create media-keys for "'.concat(e,'"}: ').concat(t))}),i})}return o.then(function(){return s.mediaKeys})}},{key:"getMediaKeySessionContext",value:function(e,t,r,i){for(var n=this.mediaKeySessions,a=' key-session "'.concat(e,'" keyId: ').concat(ft(r.keyId||[])," keyUri: ").concat(r.uri,' for "').concat(i,'"'),s=0;s<n.length;s++){var o=n[s];if(!o.initialized&&o.createdFor.levelKey.uri===r.uri)return this.log("Reusing".concat(a)),o}this.log("Creating".concat(a));var l=t.createSession(),u={keySystem:e,mediaKeys:t,mediaKeysSession:l,keyRequests:{},keyStatuses:{},createdFor:{levelKey:r,reason:i},initialized:!1};return n.push(u),u}},{key:"resetMediaKeys",value:function(){var e,t=null==(e=this.mediaKeySessions[0])?void 0:e.keySystem,r=this.keySystemAccessPromises[t];r&&(this.log("reset mediaKeys"),this.mediaKeys=null,r.hasMediaKeys=!1,delete r.mediaKeys,delete this.keySystemAccessPromises[t])}},{key:"updateKeySession",value:function(e,t,r){var i=e.mediaKeysSession;return this.log('Updating key-session "'.concat(i.sessionId,'" for keyId ').concat(ft(t.keyId||[]),"\n } (data length: ").concat(r.byteLength,")")),i.update(r)}},{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 fn(e.keySystem)}).filter(function(e){return!!e})}},{key:"getKeySystemAccess",value:function(e){var t=this;return this.getKeySystemSelectionPromise(e).then(function(e){var r=e.keySystem,i=e.mediaKeys;return t.attemptSetMediaKeys(r,i)})}},{key:"selectKeySystem",value:function(e){return this.getKeySystemSelectionPromise(e).then(function(e){var t=e.keySystem,r=fn(t);if(!r)throw new Error('Unable to find format for key-system "'.concat(t,'"'));return 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=vn(this.config),r=e.map(dn).filter(function(e){return!!e&&-1!==t.indexOf(e)});return this.selectKeySystem(r)}},{key:"loadClear",value:function(e,t,r){var i=this;if(this.config.emeEnabled&&!this.getSelectedKeySystemFormats().length){if(t.length)for(var n,a=function(){var n=t[s];if(e.cc<=n.cc&&(!pe(e)||!pe(n)||e.sn<n.sn)||!r&&s==o-1)return{v:i.selectKeySystemFormat(n).then(function(e){if(i.hls){n.setKeyFormat(e);var t=dn(e);return t?i.getKeySystemAccess([t]):void 0}})}},s=0,o=t.length;s<o;s++)if(n=a())return n.v;if(this.config.requireKeySystemAccessOnStart){var l=vn(this.config);if(l.length)return this.getKeySystemAccess(l)}}return null}},{key:"getKeyStatus",value:function(e){for(var t=this.mediaKeySessions,r=0;r<t.length;r++){var i=nu(e,t[r]);if(i)return i}}},{key:"loadKey",value:function(e){var t=e.decryptdata,r=this.getKeyStatus(t);if("internal-error"===r){var i=au(r,t);return i.data.frag=e,this.error("".concat(i.message," (").concat(ft(t.keyId||[]),")")),Promise.reject(i)}var n=e.type,a=this.activeKeys,s=a[n];s&&!t.matches(s.decryptdata)&&(a.previous||(a.previous=[]),a.previous.push(s),delete a[n]),a[n]||(a[n]=e);for(var o=this.mediaKeySessions.length;o--;){var l=this.mediaKeySessions[o];if(t.keyId&&"expired"===l.keyStatuses[ft(t.keyId)])return this.renewKeySession(t,l)}return this.updateUsablePromise(t,"playlist-key",e)}},{key:"renewKeySession",value:function(e,t){var r=this;return this.resetMediaKeys(),this.removeSession(t).then(function(){return r.throwIfDestroyed(),r.updateUsablePromise(e,"expired")})}},{key:"updateUsablePromise",value:function(e,t,r){var i=this,n=this.getSessionForKey(e,t);return n.catch(function(e){return i.handleError(e,r)}),n.then(function(t){return e})}},{key:"getSessionForKey",value:function(e,t){var r=this,i=this.findContextForKey(e);if(void 0!==i)return Promise.resolve(i);var n,a=e.uri,s=this.sessionSetupByUri[a];n=void 0===s?this.resolveSessionForKey(e,t):s.catch(function(){}).then(function(){return r.throwIfDestroyed(),r.resolveSessionForKey(e,t)}),this.sessionSetupByUri[a]=n;var o=function(){r.sessionSetupByUri[a]===n&&delete r.sessionSetupByUri[a]};return n.then(o,o),n}},{key:"findContextForKey",value:function(e){for(var t=this.mediaKeySessions,r=t.length;r--;){var i=t[r];if(nu(e,i))return i}}},{key:"resolveSessionForKey",value:function(e,t){var r=this;return this.getKeySystemForKeyPromise(e).then(function(i){var n=i.keySystem,a=i.mediaKeys;r.throwIfDestroyed();for(var s=r.mediaKeySessions.length;s--;){var o=r.mediaKeySessions[s];if(nu(e,o))return o;var l=r.getUsableKeyPromise(o,e,t);if(l)return l}return r.attemptSetMediaKeys(n,a).then(function(){return r.throwIfDestroyed(),r.getMediaKeySessionContext(n,a,e,t)}).then(function(i){r.throwIfDestroyed();var n=e.scheme||"cenc",a=e.pssh?e.pssh.buffer:null;return r.generateRequestWithPreferredKeySession(i,e,n,a,t)})})}},{key:"getUsableKeyPromise",value:function(e,t,r){var i=e.keyRequests[t.uri];if(i)return this.log("Waiting for usable key (".concat(r," keyId: ").concat(function(e){if(e.keyFormat===ln)return e.uri;if(null===e.keyId)throw new Error("keyId is null");return ft(e.keyId)}(t),' format: "').concat(t.keyFormat,'" URI: ').concat(t.uri,")")),i.useable.then(function(){return e})}},{key:"throwIfDestroyed",value:function(){if(!this.hls)throw new Error("invalid state")}},{key:"handleError",value:function(e,t){if(this.hls)if(e instanceof ru){t&&(e.data.frag=t);var r=e.data.decryptdata;this.error("".concat(e.message).concat(r?" (".concat(ft(r.keyId||[]),")"):"")),this.hls.trigger(ne.ERROR,e.data)}else this.error(e.message),this.hls.trigger(ne.ERROR,{type:re.KEY_SYSTEM_ERROR,details:ie.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}},{key:"getKeySystemForKeyPromise",value:function(e){var t=dn(e.keyFormat),r=t?[t]:vn(this.config);return this.attemptKeySystemAccess(r)}},{key:"getKeySystemSelectionPromise",value:function(e){if(e.length||(e=vn(this.config)),0===e.length)throw new ru({type:re.KEY_SYSTEM_ERROR,details:ie.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},"Missing key-system license configuration options ".concat(Nr({drmSystems:this.config.drmSystems})));return this.attemptKeySystemAccess(e)}},{key:"activeLevelKeys",value:function(){var e=this.activeKeys,t=(e.previous||[]).map(function(e){return e.decryptdata});return e.audio&&t.unshift(e.audio.decryptdata),e.main&&t.unshift(e.main.decryptdata),t}},{key:"attemptSetMediaKeys",value:function(e,t){var r=this;if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();var i=this.setMediaKeysQueue.slice();this.log('Setting media-keys for "'.concat(e,'"'));var n=Promise.all(i).then(function(){return r.media?r.media.setMediaKeys(t):new Promise(function(e,i){r.mediaResolved=function(){if(r.mediaResolved=void 0,!r.media)return i(new Error("Attempted to set mediaKeys without media element attached"));r.mediaKeys=t,r.media.setMediaKeys(t).then(e).catch(i)}})});return this.mediaKeys=t,this.setMediaKeysQueue.push(n),n.then(function(){r.log('Media-keys set for "'.concat(e,'"')),i.push(n),r.setMediaKeysQueue=r.setMediaKeysQueue.filter(function(e){return-1===i.indexOf(e)})})}},{key:"filterInitData",value:function(e,t,r,i,n){var a,s=null==(a=this.config.drmSystems)||null==(a=a[e.keySystem])?void 0:a.generateRequest;if(s)try{var o=s.call(this.hls,r,i,Ae({},e,{decryptdata:t,reason:n}),n);if(!o)throw new Error("Invalid response from configured generateRequest filter");t.scheme=o.initDataType?o.initDataType:"cenc";var l=o.initData?o.initData:null;return t.pssh=l?new Uint8Array(l):null,o}catch(e){var u;if(this.warn(e.message),null!=(u=this.hls)&&u.config.debug)throw e}return{initDataType:r,initData:i}}},{key:"generateRequestWithPreferredKeySession",value:function(e,t,r,i,n){var a=this,s=this.getUsableKeyPromise(e,t,n);if(s)return s;var o=this.filterInitData(e,t,r,i,n);if(o&&(i=o.initData?o.initData:null,r=o.initDataType),null===i)return n.startsWith("encrypted-event")?Promise.reject(new Error('missing initialization data for "'.concat(n,'"'))):(this.log('Skipping key-session request for "'.concat(n,'" (no initData)')),Promise.resolve(e));var l=t.uri,u=new tu;e.keyRequests[l]=u;var c=function(r){var i=e.mediaKeysSession;if(i){var n=r.messageType,s=r.message;u.status=n,a.log('"'.concat(n,'" message event for session "').concat(i.sessionId,'" message size: ').concat(s.byteLength)),"license-request"===n||"license-renewal"===n?a.renewLicense(e,t,s).catch(function(t){u.errored=t,u.hasListeners||a.handleError(t),a.removeSession(e)}):"license-release"===n?e.keySystem===sn.FAIRPLAY&&a.updateKeySession(e,t,tn("acknowledged")).then(function(){return a.removeSession(e)}).catch(function(e){return a.handleError(e)}):a.warn('unhandled media key message type "'.concat(n,'"'))}else{var o=new Error("invalid state");u.errored=o}};u.onmessage=c,ta(e.mediaKeysSession,"message",c);return this.generateRequest(e,t,r,i,n,!1)}},{key:"generateRequest",value:function(e,t,r,i,n,a){var s=this;if(a){var o=this.filterInitData(e,t,r,i,n);o&&(i=o.initData?o.initData:i,r=o.initDataType)}var l=t.uri,u=e.keyRequests[l],c=ft(t.keyId||[]),d=function(e){var r;e.startsWith("usable")?u.resolve():"internal-error"===e||"output-restricted"===e||"output-downscaled"===e?r=au(e,t):"expired"===e?r=new Error("key expired (keyId: ".concat(c,")")):"released"===e?r=new Error("key released"):"status-pending"===e||s.warn('unhandled key status change "'.concat(e,'" (keyId: ').concat(c,")")),r&&(u.errored=r,u.hasListeners||s.handleError(r))},h=function(r){if(e.mediaKeysSession){var i=e.keyStatuses=s.getKeyStatuses(e);if(Object.keys(i).some(function(e){return"status-pending"!==i[e]})){for(var n=s.activeLevelKeys(),a=0;a<n.length;a++){var o=ft(n[a].keyId||[]);if("expired"===i[o]){var l;s.log("Expired key ".concat(Nr(i),' in key-session "').concat(null==(l=e.mediaKeysSession)?void 0:l.sessionId,'"')),s.renewKeySession(t,e).catch(function(e){return s.handleError(e)});break}}var h=i[c];if(h)d(h);else{var f;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(f=e.keyStatusTimeouts)[c]||(f[c]=self.setTimeout(function(){var r;if(e.mediaKeysSession){var i,n=s.getKeyStatus(t);if(n&&"status-pending"!==n)return s.log("No status for keyId ".concat(c,' in key-session "').concat(null==(i=e.mediaKeysSession)?void 0:i.sessionId,'". Using session key-status ').concat(n," from other session.")),d(n);s.log("key status for ".concat(c,' in key-session "').concat(null==(r=e.mediaKeysSession)?void 0:r.sessionId,'" timed out after ').concat(1e3,"ms")),d(h="internal-error")}},1e3)),s.log("No status for keyId ".concat(c," (").concat(Nr(i),")."))}}}else{var v=new Error("invalid state");u.errored=v}};u.onkeystatuseschange=h,ta(e.mediaKeysSession,"keystatuseschange",h);var f=u.useable;return this.log('Generating key-session request for "'.concat(n,'" keyId: ').concat(c," URI: ").concat(l," (init data type: ").concat(r," length: ").concat(i.byteLength,")")),u.status="started",e.initialized=!0,e.mediaKeysSession.generateRequest(r,i).then(function(){var t;u.status="generated",s.log('Request generated for key-session "'.concat(null==(t=e.mediaKeysSession)?void 0:t.sessionId,'" keyId: ').concat(c," URI: ").concat(l))}).catch(function(e){throw s.log("mediaKeysSession.generateRequest failed: ".concat(e)),new ru({type:re.KEY_SYSTEM_ERROR,details:ie.KEY_SYSTEM_NO_SESSION,error:e,decryptdata:t,fatal:!1},"Error generating key-session request: ".concat(e))}).then(function(){return f}).catch(function(t){var r;s.log("mediaKeysSession.generateRequest failed: ".concat(t));var i=null==(r=t.data)?void 0:r.details;return i!==ie.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED&&i!==ie.KEY_SYSTEM_STATUS_INTERNAL_ERROR||!Object.keys(e.keyStatuses).some(function(t){return"usable"===e.keyStatuses[t]})?s.removeSession(e).then(function(){throw t}):(s.handleError(t),e)}).then(function(){return e})}},{key:"getKeyStatuses",value:function(e){var t=this,r={},i=e.mediaKeysSession.sessionId;return e.mediaKeysSession.keyStatuses.forEach(function(n,a){if("string"==typeof a&&"object"===R(n)){var s=a;a=n,n=s}var o="buffer"in a?new Uint8Array(a.buffer,a.byteOffset,a.byteLength):new Uint8Array(a);if(e.keySystem===sn.PLAYREADY&&16===o.length){var l=ft(o);r[l]=n,rn(o)}var u=ft(o);t.log('key status change "'.concat(n,'" for keyStatuses keyId: ').concat(u,' key-session "').concat(i,'"')),r[u]=n}),r}},{key:"fetchServerCertificate",value:function(e){var t=this.config,r=new(0,t.loader)(t),i=function(e,t){var r=t.drmSystems,i=null==r?void 0:r[e];if(i)return i.serverCertificateUrl}(e,t);return i?(this.log('Fetching server certificate for "'.concat(e,'"')),new Promise(function(n,a){var s={type:ce.SERVER_CERTIFICATE,responseType:"arraybuffer",url:i},o=t.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:function(e,t,r,i){n(e.data)},onError:function(t,r,n,o){a(new ru({type:re.KEY_SYSTEM_ERROR,details:ie.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:n,response:Ie({url:s.url,data:void 0},t)},'"'.concat(e,'" certificate request failed (').concat(i,"). Status: ").concat(t.code," (").concat(t.text,")")))},onTimeout:function(t,r,n){a(new ru({type:re.KEY_SYSTEM_ERROR,details:ie.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:n,response:{url:s.url,data:void 0}},'"'.concat(e,'" certificate request timed out (').concat(i,")")))},onAbort:function(e,t,r){a(new Error("aborted"))}};r.load(s,l,u)})):(this.log('No Server Certificate in config.drmSystems["'.concat(e,'"]')),Promise.resolve())}},{key:"setMediaKeysServerCertificate",value:function(e,t,r){var i=this;return new Promise(function(n,a){e.setServerCertificate(r).then(function(a){i.log("setServerCertificate ".concat(a?"success":"not supported by CDM"," (").concat(r.byteLength,') on "').concat(t,'"')),n(e)}).catch(function(e){a(new ru({type:re.KEY_SYSTEM_ERROR,details:ie.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))})})}},{key:"renewLicense",value:function(e,t,r){var i=this;return this.requestLicense(e,t,new Uint8Array(r)).then(function(r){return i.updateKeySession(e,t,new Uint8Array(r)).catch(function(e){throw new ru({type:re.KEY_SYSTEM_ERROR,details:ie.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t,error:e,fatal:!1},e.message)})})}},{key:"unpackPlayReadyKeyMessage",value:function(e,t){var r=pt(new Uint16Array(t.buffer));if(!r.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;var i=(new DOMParser).parseFromString(r,"application/xml"),n=i.querySelectorAll("HttpHeader");if(n.length>0)for(var a,s=0,o=n.length;s<o;s++){var l,u,c=null==(l=(a=n[s]).querySelector("name"))?void 0:l.textContent,d=null==(u=a.querySelector("value"))?void 0:u.textContent;c&&d&&e.setRequestHeader(c,d)}var h=i.querySelector("Challenge"),f=null==h?void 0:h.textContent;if(!f)throw new Error("Cannot find <Challenge> in key message");return tn(atob(f))}},{key:"setupLicenseXHR",value:function(e,t,r,i,n){var a=this,s=this.config.licenseXhrSetup;return s?Promise.resolve().then(function(){return a.throwIfDestroyed(),s.call(a.hls,e,t,Ie(Ie({},r),{},{decryptdata:i}),n)}).catch(function(o){if(!r.mediaKeysSession)throw o;return e.open("POST",t,!0),s.call(a.hls,e,t,Ie(Ie({},r),{},{decryptdata:i}),n)}).then(function(r){return e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:r||n}}):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:n}))}},{key:"requestLicense",value:function(e,t,r){var i=this;return new Promise(function(n,a){var s=function(e,t){var r=t.drmSystems,i=t.widevineLicenseUrl,n=null==r?void 0:r[e];if(n)return n.licenseUrl;if(e===sn.WIDEVINE&&i)return i}(e.keySystem,i.config);if(!s)return a(new Error('no license server URL configured for key-system "'.concat(e.keySystem,'"')));var o=e.keyRequests[t.uri];if(!o)return a(new Error("License emitter removed"));i.log("Sending license request to URL: ".concat(s));var l=i.config.keyLoadPolicy.default,u=new XMLHttpRequest;u.responseType="arraybuffer",u.onreadystatechange=function(){if(!i.hls||!e.mediaKeysSession)return a(new Error("invalid state"));if(4===u.readyState)if(200===u.status){o.requestErrors=[];var c=u.response;i.log("License received ".concat(c instanceof ArrayBuffer?c.byteLength:c));var d=i.config.licenseResponseCallback;if(d)try{c=d.call(i.hls,u,s,Ie(Ie({},e),{},{decryptdata:t}))}catch(e){i.error(e)}n(c)}else{var h=l.errorRetry,f=h?h.maxNumRetry:0;if(o.requestErrors.push({status:u.status,message:u.statusText}),o.requestErrors.length>f||u.status>=400&&u.status<500)a(new ru({type:re.KEY_SYSTEM_ERROR,details:ie.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:t,fatal:!0,networkDetails:u,response:{url:s,data:void 0,code:u.status,text:u.statusText}},"License Request XHR failed (".concat(s,"). Status: ").concat(u.status," (").concat(u.statusText,")")));else{var v=f-o.requestErrors.length;i.warn("Retrying license request, ".concat(v," attempts left")),i.requestLicense(e,t,r).then(n,a)}}},o.licenseXhr&&o.licenseXhr.readyState!==XMLHttpRequest.DONE&&o.licenseXhr.abort(),o.licenseXhr=u,i.setupLicenseXHR(u,s,e,t,r).then(function(t){var r=t.xhr,n=t.licenseChallenge;e.keySystem==sn.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 r=t.media;this.media=r,ta(r,"encrypted",this.onMediaEncrypted),ta(r,"waitingforkey",this.onWaitingForKey);var i=this.mediaResolved;i?i():this.mediaKeys=r.mediaKeys}}},{key:"onMediaDetached",value:function(){var e=this.media;e&&(ra(e,"encrypted",this.onMediaEncrypted),ra(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}},{key:"_clear",value:function(){var e,r=this;this.keyFormatPromise=null,this.keySystemAccessPromises={},this.activeKeys={},this.sessionSetupByUri={};var i=this.mediaResolved;if(i&&i(),this.mediaKeys||this.mediaKeySessions.length){var n=this.media,a=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,kn.clearKeyUriToKeyIdMap();var s=a.length;t.CDMCleanupPromise=Promise.all(a.map(function(e){return r.removeSession(e)}).concat((null==n||null==(e=n.setMediaKeys(null))?void 0:e.catch(function(e){r.log("Could not clear media keys: ".concat(e)),r.hls&&r.hls.trigger(ne.ERROR,{type:re.OTHER_ERROR,details:ie.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error("Could not clear media keys: ".concat(e))})}))||Promise.resolve())).catch(function(e){r.log("Could not close sessions and clear media keys: ".concat(e)),r.hls&&r.hls.trigger(ne.ERROR,{type:re.OTHER_ERROR,details:ie.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error("Could not close sessions and clear media keys: ".concat(e))})}).then(function(){s&&r.log("finished closing key sessions and clearing media keys")})}}},{key:"onManifestLoading",value:function(){this._clear(),this.keyFormatPromise=null}},{key:"onManifestLoaded",value:function(e,t){var r=t.sessionKeys;if(r&&this.config.emeEnabled&&!this.keyFormatPromise){var i=r.reduce(function(e,t){return-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e},[]);this.log("Selecting key-system from session-keys ".concat(i.join(", "))),this.keyFormatPromise=this.getKeyFormatPromise(i),this.keyFormatPromise.catch(function(){})}}},{key:"removeSession",value:function(e){var t=this,r=e.mediaKeysSession;if(r){this.log('Remove licenses and keys and close session "'.concat(r.sessionId,'"')),Object.keys(e.keyRequests).forEach(function(t){var i=e.keyRequests[t];i.onmessage&&r.removeEventListener("message",i.onmessage),i.onkeystatuseschange&&r.removeEventListener("keystatuseschange",i.onkeystatuseschange),i.reset(),e.keyRequests[t]=void 0}),e.mediaKeysSession=void 0;var i=this.mediaKeySessions.indexOf(e);i>-1&&this.mediaKeySessions.splice(i,1);var n=e.keyStatusTimeouts;n&&Object.keys(n).forEach(function(e){return self.clearTimeout(n[e])});var a=function(e){var t;return!(!e||"persistent-license"!==e.sessionType&&(null==(t=e.sessionTypes)||!t.some(function(e){return"persistent-license"===e})))}(this.config.drmSystemOptions)?new Promise(function(e,t){self.setTimeout(function(){return t(new Error("MediaKeySession.remove() timeout"))},8e3),r.remove().then(e).catch(t)}):Promise.resolve();return a.catch(function(e){t.log("Could not remove session: ".concat(e)),t.hls&&t.hls.trigger(ne.ERROR,{type:re.OTHER_ERROR,details:ie.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error("Could not remove session: ".concat(e))})}).then(function(){return r.close()}).then(function(){return r.closed}).catch(function(e){t.log("Could not close session: ".concat(e)),t.hls&&t.hls.trigger(ne.ERROR,{type:re.OTHER_ERROR,details:ie.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error("Could not close session: ".concat(e))})})}return Promise.resolve()}}])}(Be);function nu(e,t){var r=e.keyId,i=t.mediaKeysSession;if(r&&i){var n=t.mediaKeysSession.keyStatuses;if(n.size)return n.has(r)?n.get(r):t.keyStatuses[ft(r)]}}function au(e,t){var r="output-restricted"===e,i=r?ie.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:ie.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new ru({type:re.KEY_SYSTEM_ERROR,details:i,fatal:!1,decryptdata:t},r?"HDCP level output restricted":'key status changed to "'.concat(e,'"'))}iu.CDMCleanupPromise=void 0;var su=function(){return l(function e(t){s(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(ne.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(ne.MEDIA_DETACHING,this.onMediaDetaching,this)}},{key:"unregisterListeners",value:function(){this.hls.off(ne.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(ne.MEDIA_DETACHING,this.onMediaDetaching,this)}},{key:"destroy",value:function(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}},{key:"onMediaAttaching",value:function(e,t){var r=this.hls.config;if(r.capLevelOnFPSDrop){var i=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=i,i&&"function"==typeof i.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}}},{key:"onMediaDetaching",value:function(){this.media=null}},{key:"checkFPS",value:function(e,t,r){var i=performance.now();if(t){if(this.lastTime){var n=i-this.lastTime,a=r-this.lastDroppedFrames,s=t-this.lastDecodedFrames,o=1e3*a/n,l=this.hls;if(l.trigger(ne.FPS_DROP,{currentDropped:a,currentDecoded:s,totalDroppedFrames:r}),o>0&&a>l.config.fpsDroppedMonitoringThreshold*s){var u=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(-1===l.autoLevelCapping||l.autoLevelCapping>=u)&&(u-=1,l.trigger(ne.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:l.currentLevel}),l.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=r,this.lastDecodedFrames=t}}},{key:"checkFPSInterval",value:function(){var e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){var t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}])}(),ou=function(){if(null!=an&&an.VTTCue)return self.VTTCue;var e=["","lr","rl"],t=["start","middle","end","left","right"];function r(e,t){if("string"!=typeof t)return!1;if(!Array.isArray(e))return!1;var r=t.toLowerCase();return!!~e.indexOf(r)&&r}function i(e){return r(t,e)}function n(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];for(var n=1;n<arguments.length;n++){var a=arguments[n];for(var s in a)e[s]=a[s]}return e}function a(t,a,s){var o=this,l={enumerable:!0};o.hasBeenReset=!1;var u="",c=!1,d=t,h=a,f=s,v=null,g="",p=!0,m="auto",y="start",k=50,E="middle",S=50,T="middle";Object.defineProperty(o,"id",n({},l,{get:function(){return u},set:function(e){u=""+e}})),Object.defineProperty(o,"pauseOnExit",n({},l,{get:function(){return c},set:function(e){c=!!e}})),Object.defineProperty(o,"startTime",n({},l,{get:function(){return d},set:function(e){if("number"!=typeof e)throw new TypeError("Start time must be set to a number.");d=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",n({},l,{get:function(){return h},set:function(e){if("number"!=typeof e)throw new TypeError("End time must be set to a number.");h=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",n({},l,{get:function(){return f},set:function(e){f=""+e,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",n({},l,{get:function(){return v},set:function(e){v=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",n({},l,{get:function(){return g},set:function(t){var i=function(t){return r(e,t)}(t);if(!1===i)throw new SyntaxError("An invalid or illegal string was specified.");g=i,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",n({},l,{get:function(){return p},set:function(e){p=!!e,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",n({},l,{get:function(){return m},set:function(e){if("number"!=typeof e&&"auto"!==e)throw new SyntaxError("An invalid number or illegal string was specified.");m=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",n({},l,{get:function(){return y},set:function(e){var t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");y=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",n({},l,{get:function(){return k},set:function(e){if(e<0||e>100)throw new Error("Position must be between 0 and 100.");k=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",n({},l,{get:function(){return E},set:function(e){var t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");E=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",n({},l,{get:function(){return S},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");S=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",n({},l,{get:function(){return T},set:function(e){var t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");T=t,this.hasBeenReset=!0}})),o.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}(),lu=function(){return l(function e(){s(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 uu(e){function t(e,t,r,i){return 3600*(0|e)+60*(0|t)+(0|r)+parseFloat(i||0)}var r=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return r?parseFloat(r[2])>59?t(r[2],r[3],0,r[4]):t(r[1],r[2],r[3],r[4]):null}var cu=function(){return l(function e(){s(this,e),this.values=Object.create(null)},[{key:"set",value:function(e,t){this.get(e)||""===t||(this.values[e]=t)}},{key:"get",value:function(e,t,r){return r?this.has(e)?this.values[e]:t[r]:this.has(e)?this.values[e]:t}},{key:"has",value:function(e){return e in this.values}},{key:"alt",value:function(e,t,r){for(var i=0;i<r.length;++i)if(t===r[i]){this.set(e,t);break}}},{key:"integer",value:function(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}},{key:"percent",value:function(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){var r=parseFloat(t);if(r>=0&&r<=100)return this.set(e,r),!0}return!1}}])}();function du(e,t,r,i){var n=i?e.split(i):[e];for(var a in n)if("string"==typeof n[a]){var s=n[a].split(r);if(2===s.length)t(s[0],s[1])}}var hu=new ou(0,0,""),fu="middle"===hu.align?"middle":"center";function vu(e,t,r){var i=e;function n(){var t=uu(e);if(null===t)throw new Error("Malformed timestamp: "+i);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function a(){e=e.replace(/^\s+/,"")}if(a(),t.startTime=n(),a(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+i);e=e.slice(3),a(),t.endTime=n(),a(),function(e,t){var i=new cu;du(e,function(e,t){var n;switch(e){case"region":for(var a=r.length-1;a>=0;a--)if(r[a].id===t){i.set(e,r[a].region);break}break;case"vertical":i.alt(e,t,["rl","lr"]);break;case"line":n=t.split(","),i.integer(e,n[0]),i.percent(e,n[0])&&i.set("snapToLines",!1),i.alt(e,n[0],["auto"]),2===n.length&&i.alt("lineAlign",n[1],["start",fu,"end"]);break;case"position":n=t.split(","),i.percent(e,n[0]),2===n.length&&i.alt("positionAlign",n[1],["start",fu,"end","line-left","line-right","auto"]);break;case"size":i.percent(e,t);break;case"align":i.alt(e,t,["start",fu,"end","left","right"])}},/:/,/\s/),t.region=i.get("region",null),t.vertical=i.get("vertical","");var n=i.get("line","auto");"auto"===n&&-1===hu.line&&(n=-1),t.line=n,t.lineAlign=i.get("lineAlign","start"),t.snapToLines=i.get("snapToLines",!0),t.size=i.get("size",100),t.align=i.get("align",fu);var a=i.get("position","auto");"auto"===a&&50===hu.position&&(a="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=a}(e,t)}function gu(e){return e.replace(/<br(?: \/)?>/gi,"\n")}var pu=function(){return l(function e(){s(this,e),this.state="INITIAL",this.buffer="",this.decoder=new lu,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0},[{key:"parse",value:function(e){var t=this;function r(){var e=t.buffer,r=0;for(e=gu(e);r<e.length&&"\r"!==e[r]&&"\n"!==e[r];)++r;var i=e.slice(0,r);return"\r"===e[r]&&++r,"\n"===e[r]&&++r,t.buffer=e.slice(r),i}function i(e){du(e,function(e,t){},/:/)}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{var n="";if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;var a=(n=r()).match(/^()?WEBVTT([ \t].*)?$/);if(null==a||!a[0])throw new Error("Malformed WebVTT signature.");t.state="HEADER"}for(var s=!1;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(s?s=!1:n=r(),t.state){case"HEADER":/:/.test(n)?i(n):n||(t.state="ID");continue;case"NOTE":n||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(n)){t.state="NOTE";break}if(!n)continue;if(t.cue=new ou(0,0,""),t.state="CUE",-1===n.indexOf("--\x3e")){t.cue.id=n;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{vu(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}}])}();function mu(e){for(var t=5381,r=e.length;r;)t=33*t^e.charCodeAt(--r);return(t>>>0).toString()}var yu=/\r\n|\n\r|\n|\r/g,ku="Missing initPTS for VTT ";function Eu(e,t,r){return mu(e.toString())+mu(t.toString())+mu(r)}function Su(e,t,r,i,n,a,s){var o,l=new pu,u=at(new Uint8Array(e)).trim().replace(yu,"\n").split("\n"),c=[],d=t?function(e){return Ls(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=!1,p=!0;l.oncue=function(e){var a=r[i],s=r.ccOffset,l=(f-d)/9e4;if(g){if(null!=a&&a.new&&(s=r.ccOffset=a.start),l){if(!t)return void(o=new Error(ku+"MPEGTS"));s=l-r.presentationOffset}}else{if(!t)return void(o=new Error(ku+"without X-TIMESTAMP-MAP"));s=-t.baseTime/t.timescale}var u=e.endTime-e.startTime,h=Ms(9e4*(e.startTime+s-v),9e4*n)/9e4;e.startTime=Math.max(h,0),e.endTime=Math.max(h+u,0);var p=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(p)),e.id?i&&(e.id="hlsjscc".concat(i,"_").concat(e.id)):e.id=Eu(e.startTime,e.endTime,p),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(p){if(e.startsWith("X-TIMESTAMP-MAP=")){p=!1,g=!0,e.slice(16).split(",").forEach(function(e){e.startsWith("LOCAL:")?h=e.slice(6):e.startsWith("MPEGTS:")&&(f=parseInt(e.slice(7)))});try{v=function(e){var t=parseInt(e.slice(-3)),r=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),n=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(Z(t)&&Z(r)&&Z(i)&&Z(n)))throw Error("Malformed X-TIMESTAMP-MAP: Local:".concat(e));return t+=1e3*r,t+=6e4*i,t+36e5*n}(h)/1e3}catch(e){o=e}return}""===e&&(p=!1)}l.parse(e+"\n")}),l.flush()}var Tu="stpp.ttml.im1t",Au=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,bu=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Iu={left:"start",center:"center",right:"end",start:"start",end:"end"};function Ru(e,t,r,i){var n=Ct(new Uint8Array(e),["mdat"]);if(0!==n.length){var a=n.map(function(e){return at(e)}),s=function(e,t){return Ls(e,t,1/(arguments.length>2&&void 0!==arguments[2]?arguments[2]:1),arguments.length>3&&void 0!==arguments[3]&&arguments[3])}(t.baseTime,1,t.timescale);try{a.forEach(function(e){return r(function(e,t){var r=(new DOMParser).parseFromString(e,"text/xml"),i=r.getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");var n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:1},a=Object.keys(n).reduce(function(e,t){return e[t]=i.getAttribute("ttp:".concat(t))||n[t],e},{});!i.getAttribute("ttp:tickRate")&&i.getAttribute("ttp:frameRate")&&(a.tickRate=Number(a.frameRate)*Number(a.subFrameRate));var s="preserve"!==i.getAttribute("xml:space"),o=Pu(Lu(i,"styling","style")),l=Pu(Lu(i,"layout","region")),u=Lu(i,"body","[begin]");return[].map.call(u,function(e){var r=wu(e,s);if(!r||!e.hasAttribute("begin"))return null;var i=_u(e.getAttribute("begin"),a),n=_u(e.getAttribute("dur"),a),u=_u(e.getAttribute("end"),a);if(null===i)throw Du(e);if(null===u){if(null===n)throw Du(e);u=i+n}var c=new ou(i-t,u-t,r);c.id=Eu(c.startTime,c.endTime,c.text);var d=function(e,t,r){var i="http://www.w3.org/ns/ttml#styling",n=null,a=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],s=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;s&&r.hasOwnProperty(s)&&(n=r[s]);return a.reduce(function(r,a){var s=Cu(t,i,a)||Cu(e,i,a)||Cu(n,i,a);return s&&(r[a]=s),r},{})}(l[e.getAttribute("region")],o[e.getAttribute("style")],o),h=d.textAlign;if(h){var f=Iu[h];f&&(c.lineAlign=f),c.align=h}return Ae(c,d),c}).filter(function(e){return null!==e})}(e,s))})}catch(e){i(e)}}else i(new Error("Could not parse IMSC1 mdat"))}function Lu(e,t,r){var i=e.getElementsByTagName(t)[0];return i?[].slice.call(i.querySelectorAll(r)):[]}function Pu(e){return e.reduce(function(e,t){var r=t.getAttribute("xml:id");return r&&(e[r]=t),e},{})}function wu(e,t){return[].slice.call(e.childNodes).reduce(function(e,r,i){var n;return"br"===r.nodeName&&i?e+"\n":null!=(n=r.childNodes)&&n.length?wu(r,t):t?e+r.textContent.trim().replace(/\s+/g," "):e+r.textContent},"")}function Cu(e,t,r){return e&&e.hasAttributeNS(t,r)?e.getAttributeNS(t,r):null}function Du(e){return new Error("Could not parse ttml timestamp ".concat(e))}function _u(e,t){if(!e)return null;var r=uu(e);return null===r&&(Au.test(e)?r=function(e,t){var r=Au.exec(e),i=(0|r[4])+(0|r[5])/t.subFrameRate;return 3600*(0|r[1])+60*(0|r[2])+(0|r[3])+i/t.frameRate}(e,t):bu.test(e)&&(r=function(e,t){var r=bu.exec(e),i=Number(r[1]);switch(r[2]){case"h":return 3600*i;case"m":return 60*i;case"ms":return i/1e3;case"f":return i/t.frameRate;case"t":return i/t.tickRate}return i}(e,t))),r}function Mu(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:"disabled",a=e.ownerDocument.createElement("track");return a.kind=t,a.label=r,i&&(a.srclang=i),a.src="data:,WEBVTT",a.track.mode=n,e.appendChild(a),a}function xu(e){return e.forced&&(tr.indexOf("Apple")>-1||/iPhone|iPad|iPod/.test(er))?"forced":e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function Ou(e,t){var r=e.mode;if("disabled"===r&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error("addCue is failed for: ".concat(t))}catch(r){je.debug("[texttrack-utils]: ".concat(r));try{var i=new self.TextTrackCue(t.startTime,t.endTime,t.text);i.id=t.id,e.addCue(i)}catch(e){je.debug("[texttrack-utils]: Legacy TextTrackCue fallback failed: ".concat(e))}}"disabled"===r&&(e.mode=r)}function Fu(e,t,r,i){var n=e.mode;if("disabled"===n&&(e.mode="hidden"),e.cues&&e.cues.length>0)for(var a=function(e,t,r){var i=[],n=function(e,t){if(t<=e[0].startTime)return 0;var r=e.length-1;if(t>e[r].endTime)return-1;var i,n=0,a=r;for(;n<=a;)if(t<e[i=Math.floor((a+n)/2)].startTime)a=i-1;else{if(!(t>e[i].startTime&&n<r))return i;n=i+1}return e[n].startTime-t<t-e[a].startTime?n:a}(e,t);if(n>-1)for(var a=n,s=e.length;a<s;a++){var o=e[a];if(o.startTime>=t&&o.endTime<=r)i.push(o);else if(o.startTime>r)return i}return i}(e.cues,t,r),s=0;s<a.length;s++)i&&!i(a[s])||e.removeCue(a[s]);"disabled"===n&&(e.mode=n)}var Nu=function(e){function t(e){var r;return s(this,t),(r=a(this,t,[e,"subtitle-track-controller"])).media=null,r.tracks=[],r.groupIds=null,r.tracksInGroup=[],r.trackId=-1,r.currentTrack=null,r.selectDefaultTrack=!0,r.queuedDefaultTrack=-1,r.useTextTrackPolling=!1,r.subtitlePollingInterval=-1,r._subtitleDisplay=!0,r.asyncPollTrackChange=function(){return r.pollTrackChange(0)},r.onTextTracksChanged=function(){if(r.useTextTrackPolling||self.clearInterval(r.subtitlePollingInterval),r.media&&r.hls.config.renderTextTracksNatively){var e,t=-1,i=!1;if(r.currentTrack){var n,a=null==(n=r.currentTrack.trackNode)?void 0:n.track.mode;"showing"===a?(t=r.trackId,i=!0):"hidden"===a&&(t=r.trackId)}if(!i)for(var s=0;s<r.tracksInGroup.length;s++){var o,l=null==(o=r.tracksInGroup[s].trackNode)?void 0:o.track.mode;if("showing"===l){t=s;break}t<0&&"hidden"===l&&(t=s)}if(t>-1)r._subtitleDisplay="showing"===(null==(e=r.tracksInGroup[t].trackNode)?void 0:e.track.mode);r.setSubtitleTrack(t,!0)}},r.registerListeners(),r}return f(t,e),l(t,[{key:"destroy",value:function(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,A(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(ne.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ne.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ne.MANIFEST_PARSED,this.onManifestParsed,this),e.on(ne.LEVEL_LOADING,this.onLevelLoading,this),e.on(ne.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(ne.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(ne.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(ne.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ne.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ne.MANIFEST_PARSED,this.onManifestParsed,this),e.off(ne.LEVEL_LOADING,this.onLevelLoading,this),e.off(ne.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(ne.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(ne.ERROR,this.onError,this)}},{key:"createTracksInGroup",value:function(){var e,t=this;if(this.media&&this.hls.config.renderTextTracksNatively){this.tracksInGroup.forEach(function(e){e.trackNode||(e.trackNode=Mu(t.media,xu(e),e.name,e.lang))});var r=null==(e=this.currentTrack)||null==(e=e.trackNode)?void 0:e.track;"disabled"===(null==r?void 0:r.mode)&&(r.mode=this._subtitleDisplay?"showing":"hidden")}}},{key:"onMediaAttached",value:function(e,t){var r=t.media;this.media=r;var i=this.trackId;this.queuedDefaultTrack>-1&&(i=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.setSubtitleTrack(i),this.createTracksInGroup(),this.useTextTrackPolling=!(r.textTracks&&"onchange"in r.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):r.textTracks.addEventListener("change",this.asyncPollTrackChange)}},{key:"pollTrackChange",value:function(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}},{key:"onMediaDetaching",value:function(e,t){var r=this.media;if(r){var i=!!t.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||r.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId,this.setSubtitleTrack(-1)),this.media=null,i||this.hls.config.renderTextTracksNatively&&this.tracksInGroup.forEach(function(e){var t=e.trackNode;t&&(t.track.mode="hidden",t.remove(),e.trackNode=void 0)})}}},{key:"onManifestLoading",value:function(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}},{key:"onManifestParsed",value:function(e,t){this.tracks=t.subtitleTracks}},{key:"onSubtitleTrackLoaded",value:function(e,t){var r=t.id,i=t.groupId,n=t.details,a=this.tracksInGroup[r];if(a&&a.groupId===i){var s=a.details;a.details=t.details,this.log("Subtitle track ".concat(r,' "').concat(a.name,'" lang:').concat(a.lang," group:").concat(i," loaded [").concat(n.startSN,"-").concat(n.endSN,"]")),r===this.trackId&&this.playlistLoaded(r,t,s)}else this.warn("Subtitle track with id:".concat(r," and group:").concat(i," not found in active group ").concat(null==a?void 0:a.groupId))}},{key:"onLevelLoading",value:function(e,t){this.switchLevel(t.level)}},{key:"onLevelSwitching",value:function(e,t){this.switchLevel(t.level)}},{key:"switchLevel",value:function(e){var t=this,r=this.hls.levels[e];if(r){var i=r.subtitleGroups||null,n=this.groupIds,a=this.currentTrack;if(!i||(null==n?void 0:n.length)!==(null==i?void 0:i.length)||null!=i&&i.some(function(e){return-1===(null==n?void 0:n.indexOf(e))})){this.groupIds=i;var s=[];if(this.tracks.forEach(function(e){(e.textCodec===Tu?t.hls.config.enableIMSC1:t.hls.config.enableWebVTT)&&(!i||i.indexOf(e.groupId)>-1?(e.id=s.length,s.push(e)):e.trackNode&&(e.trackNode.remove(),e.trackNode=void 0))}),s.length===this.tracksInGroup.length){for(var o=!1,l=0;l<s.length;l++)if(s[l]!==this.tracksInGroup[l]){o=!0;break}if(!o)return}s.length&&this.selectDefaultTrack&&!s.some(function(e){return e.default})&&(this.selectDefaultTrack=!1),this.tracksInGroup=s,this.trackId=-1,this.currentTrack=null;var u=this.hls.config.subtitlePreference;if(!a&&u){this.selectDefaultTrack=!1;var c=Gr(u,s);if(c>-1)a=s[c];else{var d=Gr(u,this.tracks);a=this.tracks[d]}}var h=this.findTrackId(a);-1===h&&a&&(h=this.findTrackId(null));var f={subtitleTracks:s};this.log("Updating subtitle tracks, ".concat(s.length,' track(s) found in "').concat(null==i?void 0:i.join(","),'" group-id')),this.hls.trigger(ne.SUBTITLE_TRACKS_UPDATED,f),this.setSubtitleTrack(h),this.createTracksInGroup()}}}},{key:"findTrackId",value:function(e){for(var t=this.tracksInGroup,r=this.selectDefaultTrack,i=0;i<t.length;i++){var n=t[i];if((!r||n.default)&&(r||e)&&(!e||Hr(n,e)))return i}if(e){for(var a=0;a<t.length;a++){var s=t[a];if($s(e.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return a}for(var o=0;o<t.length;o++){var l=t[o];if($s(e.attrs,l.attrs,["LANGUAGE"]))return o}}return-1}},{key:"onError",value:function(e,t){!t.fatal&&t.context&&t.context.type===ce.SUBTITLE_TRACK&&t.context.id===this.trackId&&Wr(t.context.groupId,this.groupIds)&&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,!0)}},{key:"setSubtitleOption",value:function(e){if(this.hls.config.subtitlePreference=e,e){if(-1===e.id)return this.setSubtitleTrack(-1,!0),null;var t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){var r=this.currentTrack;if(r&&Hr(e,r))return r;var i=Gr(e,this.tracksInGroup);if(i>-1){var n=this.tracksInGroup[i];return this.setSubtitleTrack(i,!0),n}if(r)return null;var a=Gr(e,t);if(a>-1)return t[a]}}return null}},{key:"loadPlaylist",value:function(e){A(t,"loadPlaylist",this,3)([]),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}},{key:"loadingPlaylist",value:function(e,r){A(t,"loadingPlaylist",this,3)([e,r]);var i=e.id,n=e.groupId,a=this.getUrlWithDirectives(e.url,r),s=e.details,o=null==s?void 0:s.age;this.log("Loading subtitle ".concat(i,' "').concat(e.name,'" lang:').concat(e.lang," group:").concat(n).concat(void 0!==(null==r?void 0:r.msn)?" at sn "+r.msn+" part "+r.part:"").concat(o&&s.live?" age "+o.toFixed(1)+(s.type&&" "+s.type||""):""," ").concat(a)),this.hls.trigger(ne.SUBTITLE_TRACK_LOADING,{url:a,id:i,groupId:n,deliveryDirectives:r||null,track:e})}},{key:"toggleTrackModes",value:function(){var e=this;if(this.media&&this.hls.config.renderTextTracksNatively){var t=this.currentTrack;this.tracksInGroup.forEach(function(r){if(r.trackNode){var i=r===t?e._subtitleDisplay?"showing":"hidden":"disabled",n=r.trackNode.track;n.mode!==i&&(n.mode=i)}})}}},{key:"setSubtitleTrack",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=this.tracksInGroup;if(this.media||(this.queuedDefaultTrack=e),e<-1||e>=r.length||!Z(e))this.warn("Invalid subtitle track id: ".concat(e));else{var i=this.currentTrack,n=r[e]||null;if(this.trackId=e,this.currentTrack=n,t&&this.toggleTrackModes(),n){var a=!!n.details&&!n.details.live;if(n!==i||!a){this.log("Switching to subtitle-track ".concat(e)+(n?' "'.concat(n.name,'" lang:').concat(n.lang," group:").concat(n.groupId):""));var s=n.id,o=n.groupId,l=void 0===o?"":o,u=n.name,c=n.type,d=n.url;this.hls.trigger(ne.SUBTITLE_TRACK_SWITCH,{id:s,groupId:l,name:u,type:c,url:d});var h=this.switchParams(n.url,null==i?void 0:i.details,n.details);this.loadPlaylist(h)}}else i&&this.hls.trigger(ne.SUBTITLE_TRACK_SWITCH,{id:e})}}}])}(Xs),Bu=function(e){function t(e,r){var i;return s(this,t),(i=a(this,t,["gap-controller",e.logger])).hls=void 0,i.fragmentTracker=void 0,i.media=null,i.mediaSource=void 0,i.nudgeRetry=0,i.skipRetry=0,i.stallReported=!1,i.stalled=null,i.moved=!1,i.seeking=!1,i.buffered={},i.lastCurrentTime=void 0,i.ended=0,i.waiting=0,i.onMediaPlaying=function(){i.ended=0,i.waiting=0},i.onMediaWaiting=function(){var e;null!=(e=i.media)&&e.seeking||(i.waiting=self.performance.now(),i.tick())},i.onMediaEnded=function(){var e;i.hls&&(i.ended=(null==(e=i.media)?void 0:e.currentTime)||1,i.hls.trigger(ne.MEDIA_ENDED,{stalled:!1}))},i.hls=e,i.fragmentTracker=r,i.lastCurrentTime=i.getCurrentTime(),i.registerListeners(),i}return f(t,e),l(t,[{key:"registerListeners",value:function(){var e=this.hls;e&&(e.on(ne.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ne.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ne.BUFFER_APPENDED,this.onBufferAppended,this))}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ne.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ne.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ne.BUFFER_APPENDED,this.onBufferAppended,this))}},{key:"destroy",value:function(){A(t,"destroy",this,3)([]),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}},{key:"onMediaAttached",value:function(e,t){this.setInterval(100),this.mediaSource=t.mediaSource;var r=this.media=t.media;ta(r,"playing",this.onMediaPlaying),ta(r,"waiting",this.onMediaWaiting),ta(r,"ended",this.onMediaEnded)}},{key:"onMediaDetaching",value:function(e,t){this.clearInterval();var r=this.media;r&&(ra(r,"playing",this.onMediaPlaying),ra(r,"waiting",this.onMediaWaiting),ra(r,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}},{key:"onBufferAppended",value:function(e,t){this.buffered=t.timeRanges}},{key:"hasBuffered",get:function(){return Object.keys(this.buffered).length>0}},{key:"getCurrentTime",value:function(){var e,t=(null==(e=this.hls)?void 0:e.config.timelineOffset)||0;return this.media?Math.max(this.media.currentTime,t):t}},{key:"tick",value:function(){var e;if(null!=(e=this.media)&&e.readyState&&this.hasBuffered){var t=this.getCurrentTime();this.media.currentTime<t||(this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t)}}},{key:"poll",value:function(e,t){var r,i,n=null==(r=this.hls)?void 0:r.config;if(n){var a=this.media;if(a){var s=a.seeking,o=this.seeking&&!s,l=!this.seeking&&s,u=a.paused&&!s||a.ended||0===a.playbackRate;if(this.seeking=s,e!==t)return t&&(this.ended=0),this.moved=!0,s||(this.skipRetry=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.skipRetry=this.nudgeRetry=0,this.stallResolved(e),void(!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(ne.MEDIA_ENDED,{stalled:!1})));if(Bi.getBuffered(a).length){var c=Bi.bufferInfo(a,e,0),d=this.fragmentTracker;d&&this.hls&&Hu(c,e,d,this.hls);var h=c.nextStart||0;if(s&&d&&this.hls){var f=Uu(this.hls.inFlightFragments,e),v=c.len>2,g=!h||f||h-e>2&&!d.getPartialFragment(e);if(v||g)return;this.moved=!1}var p=null==(i=this.hls)?void 0:i.latestLevelDetails;if(!this.moved&&null!==this.stalled&&d){if(!(c.len>0)&&!h)return;var m=Math.max(h,c.start||0)-e,y=!(null==p||!p.live)?2*p.targetduration:2,k=Gu(e,d);if(m>0&&(m<=y||k))return void(a.paused||this._trySkipBufferHole(k))}var E=n.detectStallWithCurrentTimeMs,S=self.performance.now(),T=this.waiting,A=this.stalled;if(null===A){if(!(T>0&&S-T<E))return void(this.stalled=S);A=this.stalled=T}var b=S-A;if(!s&&(b>=E||T&&this.moved)&&this.hls){var I;if("ended"===(null==(I=this.mediaSource)?void 0:I.readyState)&&(null==p||!p.live)&&Math.abs(e-((null==p?void 0:p.edge)||0))<1){if(this.ended)return;return this.ended=e||1,void this.hls.trigger(ne.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(c),!this.media||!this.hls)return;if(a.currentTime!==e){var R=e;return e=a.currentTime,this.moved=!0,void this.log("currentTime changed ".concat(R," > ").concat(e))}}var L=Bi.bufferInfo(a,e,n.maxBufferHole);this._tryFixBufferStall(L,b,e)}else this.skipRetry=this.nudgeRetry=0}}}}},{key:"stallResolved",value:function(e){var t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){var r=self.performance.now()-t;this.log("playback not stuck anymore @".concat(e,", after ").concat(Math.round(r),"ms")),this.stallReported=!1,this.waiting=0,this.hls.trigger(ne.STALL_RESOLVED,{})}}},{key:"nudgeOnVideoHole",value:function(e,t){var r,i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(r=this.buffered.audio)&&r.length&&i&&i.length>1&&e>i.end(0)){var n=Bi.bufferedInfo(Bi.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){var a=Bi.timeRangesToArray(i),s=Bi.bufferedInfo(a,t,0).bufferedIndex;if(s>-1&&s<a.length-1){var o=Bi.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=Gu(e,this.fragmentTracker);d&&"fragment"in d?d=d.fragment:d||(d=void 0);var h=Bi.bufferInfo(this.media,e,0);this.hls.trigger(ne.ERROR,{type:re.MEDIA_ERROR,details:ie.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:c,reason:c.message,frag:d,buffer:h.len,bufferInfo:h})}}}}}},{key:"_tryFixBufferStall",value:function(e,t,r){var i,n,a=this.fragmentTracker,s=this.media,o=null==(i=this.hls)?void 0:i.config;if(s&&a&&o){var l=null==(n=this.hls)?void 0:n.latestLevelDetails,u=Gu(r,a);if(u||null!=l&&l.live&&r<l.fragmentStart)if(this._trySkipBufferHole(u)||!this.media)return;var c=e.buffered,d=this.adjacentTraversal(e,r);(c&&c.length>1&&e.len>o.maxBufferHole||e.nextStart&&(e.nextStart-r<o.maxBufferHole||d))&&(t>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}}},{key:"adjacentTraversal",value:function(e,t){var r=this.fragmentTracker,i=e.nextStart;if(r&&i){var n=r.getFragAtPos(t,de.MAIN),a=r.getFragAtPos(i,de.MAIN);if(n&&a)return a.sn-n.sn<2}return!1}},{key:"_reportStall",value:function(e){var t=this.hls,r=this.media,i=this.stallReported,n=this.stalled;if(!i&&null!==n&&r&&t){this.stallReported=!0;var a=new Error("Playback stalling at @".concat(r.currentTime," due to low buffer (").concat(Nr(e),")"));this.warn(a.message),t.trigger(ne.ERROR,{type:re.MEDIA_ERROR,details:ie.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:n}})}}},{key:"_trySkipBufferHole",value:function(e){var t=this.fragmentTracker,r=this.media,i=this.hls,n=null==i?void 0:i.config;if(!r||!t||!n)return 0;var a=r.currentTime,s=Bi.bufferInfo(r,a,0);Hu(s,a,t,i);var o=a<s.start?s.start:s.nextStart;if(o){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=t.getAppendedFrag(0,de.MAIN);h&&o<h.end&&(d=!0)}if(!d&&e){var f;if(null==(f=i.loadLevelObj)||!f.details)return 0;if(Uu(i.inFlightFragments,o))return 0;for(var v=!1,g=e.end;g<o;){var p=Gu(g,t),m=p?p.duration:0;if(!(m>0)){v=!0;break}g+=m}if(v)return 0}}var y=n.nudgeMaxRetry,k=n.skipBufferHolePadding,E=++this.skipRetry>y,S=Math.max(o,a)+k;if(E||(this.warn("skipping hole, adjusting currentTime from ".concat(a," to ").concat(S)),this.moved=!0,r.currentTime=S),null==e||!e.gap||E){var T=new Error(E?"Playhead still not moving after seeking over buffer hole from ".concat(a," to ").concat(S," after ").concat(n.nudgeMaxRetry," attempts."):"fragment loaded with buffer holes, seeking from ".concat(a," to ").concat(S)),A={type:re.MEDIA_ERROR,details:ie.BUFFER_SEEK_OVER_HOLE,fatal:E,error:T,reason:T.message,buffer:s.len,bufferInfo:s};e&&("fragment"in e?A.part=e:A.frag=e),i.trigger(ne.ERROR,A)}return S}}return 0}},{key:"_tryNudgeBuffer",value:function(e){var t=this.hls,r=this.media,i=this.nudgeRetry,n=null==t?void 0:t.config;if(!r||!n)return 0;var a=r.currentTime;if(this.nudgeRetry++,i<n.nudgeMaxRetry){var s=a+(i+1)*n.nudgeOffset,o=new Error("Nudging 'currentTime' from ".concat(a," to ").concat(s));this.warn(o.message),r.currentTime=s,t.trigger(ne.ERROR,{type:re.MEDIA_ERROR,details:ie.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(ne.ERROR,{type:re.MEDIA_ERROR,details:ie.BUFFER_STALLED_ERROR,error:l,fatal:!0,buffer:e.len,bufferInfo:e})}}}])}(Oi);function Uu(e,t){var r=Vu(e.main);if(r&&r.start<=t)return r;var i=Vu(e.audio);return i&&i.start<=t?i:null}function Vu(e){if(!e)return null;switch(e.state){case aa:case na:case ha:case fa:return null}return e.frag}function Gu(e,t){return t.getAppendedFrag(e,de.MAIN)||t.getPartialFragment(e)}function Hu(e,t,r,i){var n=i.latestLevelDetails,a=Gu(t,r);if(ya(i.config)&&!e.nextStart&&n&&a&&i.interstitialsManager){var s="type"in a?a:a.fragment,o=ei(n,s.sn);(null==o?void 0:o.level)===s.level&&ma(o,i.interstitialsManager.playerQueue,t)&&(e.nextStart=o.start)}}function Ku(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function ju(e,t,r,i,n){var a=new e(t,r,"");try{a.value=i,n&&(a.type=n)}catch(s){a=new e(t,r,Nr(n?Ie({type:n},i):i))}return a}var qu=function(){var e=Ku();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY}(),Wu=function(){return l(function e(t){var r=this;s(this,e),this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=function(){r.hls&&r.hls.trigger(ne.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(ne.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(ne.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ne.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ne.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(ne.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(ne.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(ne.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}},{key:"_unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ne.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(ne.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ne.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ne.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(ne.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(ne.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(ne.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}},{key:"onMediaAttaching",value:function(e,t){this.media=t.media}},{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.id3Track.remove(),this.id3Track=null),this.dateRangeCuesAppended={})}},{key:"onManifestLoading",value:function(){this.dateRangeCuesAppended={}}},{key:"createTrack",value:function(e){return Mu(e,"metadata","id3","","hidden")}},{key:"onFragParsingMetadata",value:function(e,t){if(this.media&&this.hls){var r=this.hls.config,i=r.enableEmsgMetadataCues,n=r.enableID3MetadataCues;if(i||n){var a=t.samples;this.id3Track||(this.id3Track=this.createTrack(this.media));var s=Ku();if(s)for(var o=0;o<a.length;o++){var l=a[o].type;if((l!==xa.emsg||i)&&n){var u=ut(a[o].data),c=a[o].pts,d=c+a[o].duration;d>qu&&(d=qu),d-c<=0&&(d=c+.25);for(var h=0;h<u.length;h++){var f=u[h];if(!ct(f)){this.updateId3CueEnds(c,l);var v=ju(s,c,d,f,l);v&&this.id3Track.track.addCue(v)}}}}}}}},{key:"updateId3CueEnds",value:function(e,t){var r,i=null==(r=this.id3Track)?void 0:r.track.cues;if(i)for(var n=i.length;n--;){var a=i[n];a.type===t&&a.startTime<e&&a.endTime===qu&&(a.endTime=e)}}},{key:"onBufferFlushing",value:function(e,t){var r=t.startOffset,i=t.endOffset,n=t.type,a=this.id3Track,s=this.hls;if(s){var o,l=s.config,u=l.enableEmsgMetadataCues,c=l.enableID3MetadataCues;if(a&&(u||c))o="audio"===n?function(e){return e.type===xa.audioId3&&c}:"video"===n?function(e){return e.type===xa.emsg&&u}:function(e){return e.type===xa.audioId3&&c||e.type===xa.emsg&&u},Fu(a.track,r,i,o)}}},{key:"onLevelUpdated",value:function(e,t){var r=t.details;this.updateDateRangeCues(r,!0)}},{key:"onLevelPtsUpdated",value:function(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}},{key:"updateDateRangeCues",value:function(e,t){var r=this;if(this.hls&&this.media){var i=this.hls.config,n=i.assetPlayerId,a=i.timelineOffset,s=i.enableDateRangeMetadataCues,o=i.interstitialsController;if(s){var l=Ku();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=ju(l,u,c,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"))&&(d.id=n,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.track.addCue(d),d.addEventListener("enter",this.onEventCueEnter))}if(e.hasProgramDateTime){var h,f=this.id3Track,v=e.dateRanges,g=Object.keys(v),p=this.dateRangeCuesAppended;if(f&&t)if(null!=(h=f.track.cues)&&h.length)for(var m,y=Object.keys(p).filter(function(e){return-1===g.indexOf(e)}),k=function(){var e=y[E],t=null==(m=p[e])?void 0:m.cues;delete p[e],t&&Object.keys(t).forEach(function(e){var i=t[e];if(i){i.removeEventListener("enter",r.onEventCueEnter);try{f.track.removeCue(i)}catch(e){}}})},E=y.length;E--;)k();else p=this.dateRangeCuesAppended={};var S=e.fragments[e.fragments.length-1];if(0!==g.length&&Z(null==S?void 0:S.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(var T=function(){var e=g[A],t=v[e],i=t.startTime,n=p[e],a=(null==n?void 0:n.cues)||{},s=(null==n?void 0:n.durationKnown)||!1,u=qu,c=t.duration;if(t.endDate&&null!==c)u=i+c,s=!0;else if(t.endOnNext&&!s){var d=g.reduce(function(e,r){if(r!==t.id){var i=v[r];if(i.class===t.class&&i.startDate>t.startDate&&(!e||t.startDate<e.startDate))return i}return e},null);d&&(u=d.startTime,s=!0)}for(var h=Object.keys(t.attr),f=0;f<h.length;f++){var m=h[f];if(Yi(m)){var y=a[m];if(y)!s||null!=n&&n.durationKnown?Math.abs(y.startTime-i)>.01&&(y.startTime=i,y.endTime=u):y.endTime=u;else if(l){var k=t.attr[m];zi(m)&&(k=vt(k));var E=ju(l,i,u,{key:m,data:k},xa.dateRange);E&&(E.id=e,r.id3Track.track.addCue(E),a[m]=E,o&&("X-ASSET-LIST"!==m&&"X-ASSET-URL"!==m||E.addEventListener("enter",r.onEventCueEnter)))}}}p[e]={cues:a,dateRange:t,durationKnown:s}},A=0;A<g.length;A++)T()}}}}}}])}();function Yu(){return self.SourceBuffer||self.WebKitSourceBuffer}function zu(){if(!qe())return!1;var e=Yu();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}var Xu,Qu,$u=0,Ju=1,Zu=2,ec=function(e){function t(e,r,i){var n;return s(this,t),(n=a(this,t,[e,r,i,"stream-controller",de.MAIN])).audioCodecSwap=!1,n.level=-1,n._forceStartLoad=!1,n._hasEnoughToStart=!1,n.altAudio=$u,n.audioOnly=!1,n._couldBacktrack=!1,n._backtrackFragment=void 0,n.audioCodecSwitch=!1,n.videoBuffer=null,n.onMediaPlaying=function(){n.tick()},n.onMediaSeeked=function(){var e=n.media,t=e?e.currentTime:null;if(null!==t&&Z(t)&&(n.log("Media seeked to ".concat(t)),n.getBufferedFrag(t))){var r=n.getFwdBufferInfoAtPos(e,t,de.MAIN,0);r&&0!==r.len?n.tick():n.log("Main buffer empty at ".concat(t,' on "seeked" event: ').concat(r?r.len:r))}},n.registerListeners(),n}return f(t,e),l(t,[{key:"registerListeners",value:function(){A(t,"registerListeners",this,3)([]);var e=this.hls;e.on(ne.MANIFEST_PARSED,this.onManifestParsed,this),e.on(ne.LEVEL_LOADING,this.onLevelLoading,this),e.on(ne.LEVEL_LOADED,this.onLevelLoaded,this),e.on(ne.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(ne.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(ne.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(ne.BUFFER_CREATED,this.onBufferCreated,this),e.on(ne.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(ne.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(ne.FRAG_BUFFERED,this.onFragBuffered,this)}},{key:"unregisterListeners",value:function(){A(t,"unregisterListeners",this,3)([]);var e=this.hls;e.off(ne.MANIFEST_PARSED,this.onManifestParsed,this),e.off(ne.LEVEL_LOADED,this.onLevelLoaded,this),e.off(ne.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(ne.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(ne.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(ne.BUFFER_CREATED,this.onBufferCreated,this),e.off(ne.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(ne.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(ne.FRAG_BUFFERED,this.onFragBuffered,this)}},{key:"onHandlerDestroying",value:function(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),A(t,"onHandlerDestroying",this,3)([])}},{key:"startLoad",value:function(e,t){if(this.levels){var r=this.lastCurrentTime,i=this.hls;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){var n=i.startLevel;-1===n&&(i.config.testBandwidth&&this.levels.length>1?(n=0,this.bitrateTest=!0):n=i.firstAutoLevel),i.nextLoadLevel=n,this.level=i.loadLevel,this._hasEnoughToStart=!!t}r>0&&-1===e&&!t&&this.initPTS.length&&(this.log("Override startPosition with lastCurrentTime @".concat(r)),e=r),this.state=aa,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,t||this.fragmentTracker.hasFragments(this.playlistType)||(this._hasEnoughToStart=this.startFragRequested=!1),this.tick()}else this._forceStartLoad=!0,this.state=na}},{key:"stopLoad",value:function(){this._forceStartLoad=!1,A(t,"stopLoad",this,3)([])}},{key:"doTick",value:function(){switch(this.state){case ga:var e=this.levels,t=this.level,r=null==e?void 0:e[t],i=null==r?void 0:r.details;if(i&&(!i.live||this.levelLastLoaded===r&&!this.waitForLive(r))){if(this.waitForCdnTuneIn(i))break;this.state=aa;break}if(this.hls.nextLoadLevel!==this.level){this.state=aa;break}break;case la:this.checkRetryDate()}this.state===aa&&this.doTickIdle(),this.onTickEnd()}},{key:"onTickEnd",value:function(){var e;A(t,"onTickEnd",this,3)([]),null!=(e=this.media)&&e.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}},{key:"doTickIdle",value:function(){var e=this.hls,t=this.levelLastLoaded,r=this.levels,i=this.media;if(null!==t&&(i||this.primaryPrefetch||!this.startFragRequested&&e.config.startFragPrefetch)&&(!this.altAudio||!this.audioOnly)){var n=this.buffering?e.nextLoadLevel:e.loadLevel;if(null!=r&&r[n]){var a=r[n],s=this.getMainFwdBufferInfo();if(null!==s){var o=this.getLevelDetails();if(o&&this._streamEnded(s,o)){var l={type:this.targetBufferType()};return this.hls.trigger(ne.BUFFER_EOS,l),void(this.state=ha)}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===ga||this.waitForLive(a))return this.level=n,this.state=ga,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=void 0);var h=this.backtrackFragment?this.backtrackFragment.start:s.end,f=this.getNextFragment(h,u);if(this.couldBacktrack&&!this.fragPrevious&&f&&pe(f)&&this.fragmentTracker.getState(f)!==yi){var v,g=(null!=(v=this.backtrackFragment)?v:f).sn-u.startSN,p=u.fragments[g-1];p&&f.cc===p.cc&&(f=p,this.fragmentTracker.removeFragment(p))}else this.backtrackFragment&&s.len&&(this.backtrackFragment=void 0);if(f&&this.isLoopLoading(f,h)){if(!f.gap){var m=this.audioOnly&&!this.altAudio?he:fe,y=(m===fe?this.videoBuffer:this.mediaBuffer)||this.media;y&&this.afterBufferFlushed(y,m)}f=this.getNextFragmentLoopLoading(f,u,s,de.MAIN,d)}f&&(this.exceedsMaxBuffer(s,d,f)||this.loadFragment(f,a,h))}}}}}}},{key:"loadFragment",value:function(e,r,i){var n=this.fragmentTracker.getState(e);n===gi||n===mi?this.bitrateTest?(this.log("Fragment ".concat(e.sn," of level ").concat(e.level," is being downloaded to test bitrate and will not be buffered")),this._loadBitrateTestFrag(e,r)):A(t,"loadFragment",this,3)([e,r,i]):this.clearTrackerIfNeeded(e)}},{key:"immediateLevelSwitch",value:function(){var e;(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==$u)&&(((null==(e=this.getLevelDetails())?void 0:e.fragmentStart)||0)>this.lastCurrentTime&&A(t,"flushMainBuffer",this,3)([0,Number.POSITIVE_INFINITY,"audio"]))}},{key:"getBufferOutput",value:function(){return this.mediaBuffer&&this.altAudio===Zu?this.mediaBuffer:this.media}},{key:"checkFragmentChanged",value:function(){var e=this.fragPlaying;if(!this.checkFragPlaying())return!1;var t=this.fragPlaying;if(t){var r=t.level;this.hls.trigger(ne.FRAG_CHANGED,{frag:t,previousFrag:e}),(null==e?void 0:e.level)!==r&&this.hls.trigger(ne.LEVEL_SWITCHED,{level:r})}return!0}},{key:"backtrackFragment",get:function(){return this._backtrackFragment},set:function(e){this._backtrackFragment=e}},{key:"couldBacktrack",get:function(){return this._couldBacktrack},set:function(e){this._couldBacktrack=e}},{key:"abortCurrentFrag",value:function(){this.backtrackFragment=void 0,A(t,"abortCurrentFrag",this,3)([])}},{key:"flushMainBuffer",value:function(e,r){A(t,"flushMainBuffer",this,3)([e,r,this.targetBufferType()])}},{key:"targetBufferType",value:function(){return this.altAudio!==Zu||this.audioOnly?null:"video"}},{key:"onMediaAttached",value:function(e,r){A(t,"onMediaAttached",this,3)([e,r]);var i=r.media;ta(i,"playing",this.onMediaPlaying),ta(i,"seeked",this.onMediaSeeked)}},{key:"onMediaDetaching",value:function(e,r){var i=this.media;i&&(ra(i,"playing",this.onMediaPlaying),ra(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,A(t,"onMediaDetaching",this,3)([e,r]),!!r.transferMedia||(this._hasEnoughToStart=!1)}},{key:"onManifestLoading",value:function(){A(t,"onManifestLoading",this,3)([]),this.log("Trigger BUFFER_RESET"),this.hls.trigger(ne.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.backtrackFragment=void 0,this.altAudio=$u,this.audioOnly=!1}},{key:"onManifestParsed",value:function(e,t){for(var r,i,n=!1,a=!1,s=0;s<t.levels.length;s++){var o=t.levels[s].audioCodec;o&&(n=n||-1!==o.indexOf("mp4a.40.2"),a=a||-1!==o.indexOf("mp4a.40.5"))}this.audioCodecSwitch=n&&a&&!("function"==typeof(null==(i=Yu())||null==(r=i.prototype)?void 0:r.changeType)),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}},{key:"onLevelLoading",value:function(e,t){if(this.levels&&this.state===aa){var r=t.levelInfo;(!r.details||r.details.live&&(this.levelLastLoaded!==r||r.details.expired)||this.waitForCdnTuneIn(r.details))&&(this.state=ga)}}},{key:"onLevelLoaded",value:function(e,t){var r,i=this,n=this.levels,a=this.startFragRequested,s=t.level,o=t.details,l=o.totalduration;if(n){this.log("Level ".concat(s," loaded [").concat(o.startSN,",").concat(o.endSN,"]").concat(o.lastPartSn?"[part-".concat(o.lastPartSn,"-").concat(o.lastPartIndex,"]"):"",", cc [").concat(o.startCC,", ").concat(o.endCC,"] duration:").concat(l));var u=t.levelInfo,c=this.fragCurrent;!c||this.state!==oa&&this.state!==la||c.level!==t.level&&c.loader&&this.abortCurrentFrag();var d=0;if(o.live||null!=(r=u.details)&&r.live){var h;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;d=this.alignPlaylists(o,u.details,null==(h=this.levelLastLoaded)?void 0:h.details)}if(u.details=o,this.levelLastLoaded=u,a||this.setStartPosition(o,d),this.hls.trigger(ne.LEVEL_UPDATED,{details:o,level:s}),this.state===ga){if(this.waitForCdnTuneIn(o))return;this.state=aa}a&&o.live&&this.synchronizeToLiveEdge(o),this.initPTS.some(function(e,t){if(t>=o.startCC)return!0;delete i.initPTS[t]}),this.tick()}else this.warn("Levels were reset while loading level ".concat(s))}},{key:"synchronizeToLiveEdge",value:function(e){var t=this.config,r=this.media;if(r){var i=this.hls.liveSyncPosition,n=this.playhead,a=e.fragmentStart,s=e.edge,o=n>=a-t.maxFragLookUpTolerance&&n<=s;if(null!==i&&r.duration>i&&(n<i||!o)){var l=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!o&&r.readyState<4||n<s-l)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),r.readyState))if(this.warn("Playback: ".concat(n," is located too far from the end of live sliding playlist: ").concat(s,", reset currentTime to : ").concat(i)),"buffered"===this.config.liveSyncMode){var u,c=Bi.bufferInfo(r,i,0);if(null==(u=c.buffered)||!u.length)return void(r.currentTime=i);if(c.start<=n)return void(r.currentTime=i);var d=Bi.bufferedInfo(c.buffered,n,0).nextStart;d&&(r.currentTime=d)}else r.currentTime=i}}}},{key:"_handleFragmentLoadProgress",value:function(e){var t,r=e.frag,i=e.part,n=e.payload,a=this.levels;if(a){var s=a[r.level];if(s){var o=s.details;if(!o)return this.warn("Dropping fragment ".concat(r.sn," of level ").concat(r.level," after level details were reset")),void this.fragmentTracker.removeFragment(r);var l=s.videoCodec,u=o.PTSKnown||!o.live,c=null==(t=r.initSegment)?void 0:t.data,d=this._getAudioCodec(s),h=this.transmuxer=this.transmuxer||new Ys(this.hls,de.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,v=-1!==f,g=_i(r,i,this.iframesOnly),p=g.decryptRange,m=g.byteRange,y=new Fi(r.level,r.sn,r.stats.chunkCount,m?m.end-m.start:n.byteLength,f,v,r.duration,this.iframesOnly,p),k=this.initPTS[r.cc];h.push(n,c,d,l,r,i,o.totalduration,u,y,k)}else this.warn("Level ".concat(r.level," not found on progress"))}else this.warn("Levels were reset while fragment load was in progress. Fragment ".concat(r.sn," of level ").concat(r.level," will not be buffered"))}},{key:"onAudioTrackSwitching",value:function(e,t){var r=this,i=this.hls,n=this.altAudio!==$u;if(qr(t.url,i))this.altAudio=Ju;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=$u,this.fragmentTracker.removeAllFragments(),i.once(ne.BUFFER_FLUSHED,function(){r.hls&&r.hls.trigger(ne.AUDIO_TRACK_SWITCHED,t)}),void i.trigger(ne.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});i.trigger(ne.AUDIO_TRACK_SWITCHED,t)}}},{key:"onAudioTrackSwitched",value:function(e,t){var r=qr(t.url,this.hls);if(r){var i=this.videoBuffer;i&&this.mediaBuffer!==i&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=i)}this.altAudio=r?Zu:$u,this.tick()}},{key:"onBufferCreated",value:function(e,t){var r,i,n=t.tracks,a=!1;for(var s in n){var o=n[s];if("main"===o.id){if(i=s,r=o,"video"===s){var l=n[s];l&&(this.videoBuffer=l.buffer)}}else a=!0}a&&r?(this.log("Alternate track found, use ".concat(i,".buffered to schedule main fragment loading")),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}},{key:"onFragBuffered",value:function(e,t){var r=t.frag,i=t.part,n=r.type===de.MAIN;if(n){if(this.fragContextChanged(r))return this.warn("Fragment ".concat(r.sn).concat(i?" p: "+i.index:""," of level ").concat(r.level," finished buffering, but was aborted. state: ").concat(this.state)),void(this.state===da&&(this.state=aa));var a=!1;if(pe(r)&&(a=!!r.gap&&!r.tagList.some(function(e){return"GAP"===e[0]})),this.fragBufferedComplete(r,i),a){var s;r.stats.retry++;var o=null==(s=this.levels)?void 0:s[r.level];o&&o.fragmentError++}}var l=this.media;l&&(!this._hasEnoughToStart&&Bi.getBuffered(l).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),n&&this.tick())}},{key:"hasEnoughToStart",get:function(){return this._hasEnoughToStart}},{key:"onError",value:function(e,t){var r;if(t.fatal)this.state=fa;else switch(t.details){case ie.FRAG_GAP:case ie.FRAG_PARSING_ERROR:case ie.FRAG_DECRYPT_ERROR:case ie.FRAG_LOAD_ERROR:case ie.FRAG_LOAD_TIMEOUT:case ie.KEY_LOAD_ERROR:case ie.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(de.MAIN,t);break;case ie.LEVEL_LOAD_ERROR:case ie.LEVEL_LOAD_TIMEOUT:case ie.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==ga||(null==(r=t.context)?void 0:r.type)!==ce.LEVEL||(this.state=aa);break;case ie.BUFFER_APPEND_NO_PROGRESS:if("main"!==t.parent)return;t.frag&&(t.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn("Marking fragment ".concat(t.frag.sn," of level ").concat(t.frag.level," as a gap after ").concat(t.appendsWithoutProgress," appends without buffered range growth, to prevent loop loading")),this.fragmentTracker.addAsGap(t.frag));break;case ie.BUFFER_ADD_CODEC_ERROR:case ie.BUFFER_APPEND_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case ie.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 ie.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}},{key:"onFragLoadEmergencyAborted",value:function(){this.state=aa,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}},{key:"onBufferFlushed",value:function(e,t){var r=t.type;if(r!==he||!this.altAudio){var i=(r===fe?this.videoBuffer:this.mediaBuffer)||this.media;i&&(this.afterBufferFlushed(i,r),this.tick())}}},{key:"onLevelsUpdated",value:function(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}},{key:"swapAudioCodec",value:function(){this.audioCodecSwap=!this.audioCodecSwap}},{key:"seekToStartPos",value:function(){var e=this.media;if(e){var t=e.currentTime,r=this.startPosition;if(r>=0&&t<r){if(e.seeking)return void this.log("could not seek to ".concat(r,", already seeking at ").concat(t));var i=this.timelineOffset;i&&r&&(r+=i);var n=this.getLevelDetails(),a=Bi.getBuffered(e),s=a.length?a.start(0):0,o=s-r,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*((null==n?void 0:n.partTarget)||0)))&&(this.log("adjusting start position by ".concat(o," to match buffer start")),r+=o,this.startPosition=r),t<r&&(this.log("seek to target start position ".concat(r," from current time ").concat(t," buffer start ").concat(s)),e.currentTime=r)}}}},{key:"_getAudioCodec",value:function(e){var t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),t}},{key:"_loadBitrateTestFrag",value:function(e,t){var r=this;e.bitrateTest=!0,this._doFragLoad(e,t).then(function(e){var i=r.hls,n=null==e?void 0:e.frag;if(n&&!r.fragContextChanged(n)){t.fragmentError=0,r.state=aa,r.startFragRequested=!1,r.bitrateTest=!1;var a=n.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),i.trigger(ne.FRAG_LOADED,e),n.bitrateTest=!1}}).catch(function(t){r.state!==na&&r.state!==fa&&(r.warn(t),r.resetFragmentLoading(e))})}},{key:"_handleTransmuxComplete",value:function(e){var t=this.playlistType,r=this.hls,i=e.remuxResult,n=e.chunkMeta,a=this.getCurrentContext(n);if(a){var s=a.frag,o=a.part,l=a.level,u=i.video,c=i.text,d=i.id3,h=i.initSegment,f=l.details,v=this.altAudio?void 0:i.audio;if(this.fragContextChanged(s))this.fragmentTracker.removeFragment(s);else{if(this.state=ca,h){var g=h.tracks;if(g){var p=s.initSegment||s;if(this.unhandledEncryptionError(h,s))return;this._bufferInitSegment(l,g,p,n),r.trigger(ne.FRAG_PARSING_INIT_SEGMENT,{frag:p,id:t,tracks:g})}var m=h.initPTS,y=h.timescale,k=this.initPTS[s.cc];if(Z(m)&&(!k||k.baseTime!==m||k.timescale!==y)){var E=h.trackId;this.initPTS[s.cc]={baseTime:m,timescale:y,trackId:E};var S=this.initPTS.slice(0);r.trigger(ne.INIT_PTS_FOUND,{timestampOffsets:S,frag:s,id:t,initPTS:m,timescale:y,trackId:E})}}if(u&&f){v&&"audiovideo"===u.type&&this.logMuxedErr(s);var T=f.fragments[s.sn-1-f.startSN],A=s.sn===f.startSN,b=!T||s.cc>T.cc;if(!1!==i.independent){var I=u.startPTS,R=u.endPTS,L=u.startDTS,P=u.endDTS;if(o)o.elementaryStreams[u.type]={startPTS:I,endPTS:R,startDTS:L,endDTS:P};else if(u.firstKeyFrame&&u.independent&&1===n.id&&!b&&(this.couldBacktrack=!0),u.dropped&&u.independent){var w=this.getMainFwdBufferInfo(),C=(w?w.end:this.getLoadPosition())+this.config.maxBufferHole,D=u.firstKeyFramePTS?u.firstKeyFramePTS:I;if(!A&&C<D-this.config.maxBufferHole&&!b)return void this.backtrack(s);b&&(s.gap=!0),s.setElementaryStreamInfo(u.type,s.start,R,s.start,P,!0)}else A&&I-(f.appliedTimelineOffset||0)>2&&(s.gap=!0);s.setElementaryStreamInfo(u.type,I,R,L,P),this.backtrackFragment&&(this.backtrackFragment=s),this.bufferFragmentData(u,s,o,n,A||b)}else{if(!A&&!b)return void this.backtrack(s);s.gap=!0}}if(v){var _=v.startPTS,M=v.endPTS,x=v.startDTS,O=v.endDTS;o&&(o.elementaryStreams[he]={startPTS:_,endPTS:M,startDTS:x,endDTS:O}),s.setElementaryStreamInfo(he,_,M,x,O),this.bufferFragmentData(v,s,o,n)}if(f&&null!=d&&d.samples.length){var F={id:t,frag:s,details:f,samples:d.samples};r.trigger(ne.FRAG_PARSING_METADATA,F)}if(f&&c){var N={id:t,frag:s,details:f,samples:c.samples};r.trigger(ne.FRAG_PARSING_USERDATA,N)}}}else this.resetWhenMissingContext(n)}},{key:"logMuxedErr",value:function(e){this.warn("".concat(pe(e)?"Media":"Init"," segment with muxed audiovideo where only video expected: ").concat(e.url))}},{key:"_bufferInitSegment",value:function(e,t,r,i){var n=this;if(this.state===ca){this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(r));var a=t.audio,s=t.video,o=t.audiovideo;if(a){var l=e.audioCodec,u=gr(a.codec,l);if("mp4a"===u&&(u="mp4a.40.5"),this.audioCodecSwitch){u&&(u=-1!==u.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");var c=a.metadata;c&&"channelCount"in c&&1!==(c.channelCount||1)&&!function(){if(void 0===Jt){var e=er.match(/Firefox\/(\d+)/i);Jt=e?parseInt(e[1]):0}return Jt}()&&(u="mp4a.40.5")}u&&-1!==u.indexOf("mp4a.40.5")&&/Android/.test(er)&&"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=de.MAIN,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=de.MAIN;var d=s.codec;if(4===(null==d?void 0:d.length))switch(d){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(d,"]").concat(s.codec!==d?" parsed-corrected="+s.codec:"").concat(s.supplemental?" supplemental="+s.supplemental:"")),delete t.audiovideo}o&&(this.iframesOnly&&this.logMuxedErr(r),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 h=Object.keys(t);if(h.length){if(this.hls.trigger(ne.BUFFER_CODECS,t),!this.hls)return;h.forEach(function(e){var a=t[e].initSegment;null!=a&&a.byteLength&&n.hls.trigger(ne.BUFFER_APPENDING,{type:e,data:a,frag:r,part:null,chunkMeta:i,parent:r.type})})}this.tickImmediate()}}},{key:"getMainFwdBufferInfo",value:function(){var e=this.getBufferOutput();return this.getFwdBufferInfo(e,de.MAIN)}},{key:"maxBufferLength",get:function(){var e=this.levels,t=this.level,r=null==e?void 0:e[t];return r?this.getMaxBufferLength(r.maxBitrate):this.config.maxBufferLength}},{key:"backtrack",value:function(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=aa}},{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 Z(t)?this.getAppendedFrag(t):null}},{key:"currentProgramDateTime",get:function(){var e,t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if(Z(t)){var r=this.getLevelDetails(),i=this.currentFrag||(r?Qr(null,r.fragments,t):null);if(i){var n=i.programDateTime;if(null!==n){var a=n+1e3*(t-i.start);return new Date(a)}}}return null}},{key:"currentLevel",get:function(){var e=this.currentFrag;return e?e.level:-1}},{key:"nextBufferedFrag",get:function(){var e=this.currentFrag;return e?this.followingBufferedFrag(e):null}},{key:"forceStartLoad",get:function(){return this._forceStartLoad}}])}(pa),tc=function(e){function t(){var e;s(this,t);for(var r=arguments.length,i=new Array(r),n=0;n<r;n++)i[n]=arguments[n];return(e=a(this,t,[].concat(i))).currentOp=void 0,e.nextOp=void 0,e.cached=[],e.cachedSize=0,e.cacheFragmentData=!0,e.initDetails=void 0,e.onBufferedToEnd=function(){var t=e.media;null!=t&&t.seeking&&(t.currentTime=t.currentTime)},e.onMediaSeeking=function(){},e}return f(t,e),l(t,[{key:"setInitPts",value:function(e){this.initPTS=e.slice()}},{key:"loadMediaAt",value:function(e,t){if(this.hls){var r=t.seekOnAppend,i=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=i,this.startPosition=e,this.state){case na:case ha:case fa:this.state=aa}this.state===aa?(this.hls.resumeBuffering(),this.tick(),this.currentOp=[i,t]):this.nextOp=[i,t],this.hls.off(ne.BUFFERED_TO_END,this.onBufferedToEnd);var n=this.media;if(r&&n)this.seekTo(i)&&(this.currentOp=[i,t],this.nextOp=void 0,this.flushPipeline(i,!0))}}},{key:"seekTo",value:function(e){var t=this.media;if(t){var r,i=null==(r=this.getLevelDetails())?void 0:r.edge,n=void 0!==i?i:t.duration;if(e>=n&&(e=n-.01),Bi.bufferInfo(t,e,0).len>0&&this.getBufferedAt(e))return t.currentTime=e,!0}return!1}},{key:"getBufferedAt",value:function(e){return this.fragmentTracker.getBufferedFrag(e,de.MAIN)}},{key:"cacheSet",value:function(e,t){if(this.hls){e.data=t;var r=this.cached;r.push(e),this.cachedSize+=t.buffer.byteLength;for(var i=this.hls.config.iframeCacheLimit;this.cachedSize>i&&r.length>1;){var n=r.shift();if(!n.data){this.cached=r.filter(function(e){return!!e.data}),this.cachedSize=r.reduce(function(e,t){var r=t.data;return r?r.buffer.byteLength:0},0);break}this.cachedSize-=n.data.byteLength,n.data=void 0}}}},{key:"onHandlerDestroying",value:function(){this.cached.length=0,this.cachedSize=0,A(t,"onHandlerDestroying",this,3)([])}},{key:"_handleFragmentLoadProgress",value:function(e){var r=e.frag,i=e.part,n=e.payload;this.cacheFragmentData&&!i&&null!=n&&n.byteLength&&!r.data&&pe(r)&&this.cacheSet(r,new Uint8Array(n.slice(0))),A(t,"_handleFragmentLoadProgress",this,3)([e])}},{key:"loadFragment",value:function(e,r,i){var n=this.fragmentTracker.getState(e);n!==gi&&n!==mi||!this.canReplayCached(e)?A(t,"loadFragment",this,3)([e,r,i]):this.replayCachedFragment(e)}},{key:"canReplayCached",value:function(e){var t;if(!this.cacheFragmentData||null==(t=e.data)||!t.byteLength)return!1;var r=e.decryptdata;return"identity"!==(null==r?void 0:r.keyFormat)||!!r.key}},{key:"replayCachedFragment",value:function(e){var t=e.data.slice().buffer;this.log("Buffering cached ".concat(e.type," sn: ").concat(e.sn," of level ").concat(e.level," (").concat(t.byteLength," bytes)")),this.fragCurrent=e,this.startFragRequested=!0;var r=e.stats=new ue;r.loading.start=r.loading.first=r.loading.end=self.performance.now(),r.loaded=r.total=t.byteLength,r.chunkCount=1,this.state=oa;var i={frag:e,part:null,payload:t,networkDetails:null};this._handleFragmentLoadProgress(i),this.hls.trigger(ne.FRAG_LOADED,i),this._handleFragmentLoadComplete(i)}},{key:"fragBufferedComplete",value:function(e,r){A(t,"fragBufferedComplete",this,3)([e,r]);var i=this.currentOp,n=this.nextOp;this.currentOp=this.nextOp=void 0,this.state=na,null!=i&&i[1].seekOnAppend&&(this.flushPipeline(i[0],!n),this.seekTo(i[0])||this.log("Could not seek to ".concat(i[0]," after fragment buffered (superseded or flushed) buffer: ").concat(this.media?ia(Bi.getBuffered(this.media)):"none"))),n&&this.loadMediaAt.apply(this,n)}},{key:"flushPipeline",value:function(e,t){if(t){var r=this.media;if(r){var i=Bi.bufferInfo(r,e,0),n=i.len?i.nextStart:0;n&&(this.fragmentTracker.removeFragmentsInRange(n,1/0,de.MAIN),this.flushMainBuffer(n,1/0))}this.hls.once(ne.BUFFERED_TO_END,this.onBufferedToEnd)}this.hls.trigger(ne.BUFFER_EOS,{type:"video"})}},{key:"playhead",get:function(){return this.nextLoadPosition}},{key:"startLoad",value:function(){if(!this.startFragRequested){var e=this.hls;e.nextLoadLevel=-1===e.startLevel?0:e.firstAutoLevel}}},{key:"seekToStartPos",value:function(){}},{key:"setStartPosition",value:function(){}},{key:"alignPlaylists",value:function(e,r,i){var n=this.initDetails;return this.initDetails=null,A(t,"alignPlaylists",this,3)([e,r,i||n||void 0])}},{key:"getMainFwdBufferInfo",value:function(){var e=this.playhead,t=this.getBufferedAt(e);if(t){var r=t.duration;return{len:r,start:e,end:e+r,bufferedIndex:-1}}return{len:0,start:e,end:e,bufferedIndex:-1}}},{key:"_streamEnded",value:function(){var e=this.playhead,t=this.fragmentTracker.getBufferedFrag(e,de.MAIN);return!(null==t||!t.endList)}}])}(ec),rc=function(e){function t(){var e;s(this,t);for(var r=arguments.length,i=new Array(r),n=0;n<r;n++)i[n]=arguments[n];return(e=a(this,t,[].concat(i)))._img=void 0,e.queued=void 0,e.cacheFragmentData=!1,e}return f(t,e),l(t,[{key:"image",get:function(){return this._img},set:function(e){var t,r=null==(t=this._img)?void 0:t.src;r&&self.URL.revokeObjectURL(r),this._img=e}},{key:"loadMediaAt",value:function(e){if(this.hls){var t=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=t,this.startPosition=e,this.state){case na:case ha:case fa:this.state=aa}if(this.state===aa){if(this.hls.resumeBuffering(),this.media||(this.media={}),this.tick(),this.state===aa){var r=this.getBufferedAt(e);r&&(this.fragCurrent=r,this.updateImage(r,null))}}else{var i=this.fragCurrent;(!i||e>=i.start&&e<i.end)&&(this.queued=[t])}}}},{key:"updateImage",value:function(e,t,r){var i=this,n=e.data;n||this.fragmentTracker.removeFragment(e);var a=this._img;if(a&&n){var s=self.performance.now();(t?t.stats:e.stats).buffering.start=e.stats.buffering.start=s,a.onload=function(){if(i.hls){var n=i.hls.levels[e.level];null!=n&&n.fragmentError&&(n.fragmentError=0,e.stats.retry=0);var a=self.performance.now(),s=t?t.stats:e.stats;s.buffering.end=e.stats.buffering.end=a,i.hls.trigger(ne.FRAG_BUFFERED,{frag:e,part:t,stats:s,id:e.type,chunkMeta:r})}},a.onerror=function(){i.handleError("Image decode error",e,t,r)};var o=a.src;o&&self.URL.revokeObjectURL(o);var l=new Blob([n],{type:"image/jpeg"});a.src=self.URL.createObjectURL(l)}else this.state=na,this.processQueued()}},{key:"processQueued",value:function(){var e=this.queued;this.queued=void 0,e&&this.loadMediaAt.apply(this,e)}},{key:"handleError",value:function(e,t,r,i){if(this.hls){var n=new Error(e);this.hls.trigger(ne.ERROR,{type:re.MEDIA_ERROR,details:ie.FRAG_PARSING_ERROR,chunkMeta:i,frag:t,part:r,fatal:!1,error:n,err:n})}}},{key:"_bufferInitSegment",value:function(){}},{key:"bufferFragmentData",value:function(e,r,i,n){A(t,"bufferFragmentData",this,3)([e,r,i,n,!0]);var a=Ct(new Uint8Array(e.data1),["mdat"]);if(0!==a.length){var s=r;this.cacheSet(s,a[0]),this.updateImage(s,i,n)}else this.handleError("Could not find I-Frame mdat",r,i,n)}},{key:"fragBufferedComplete",value:function(e,r){this.fragmentTracker.fragBuffered(e,!0),A(t,"fragBufferedComplete",this,3)([e,r]),this.processQueued()}},{key:"checkFragPlaying",value:function(){var e,t=null==(e=this.fragPrevious)?void 0:e.start;if(void 0!==t){var r=this.getAppendedFrag(t);if(r&&!me(r,this.fragPlaying))return this.fragPlaying=r,!0}return!1}},{key:"getMainFwdBufferInfo",value:function(){return{len:0,start:this.playhead,end:this.playhead,bufferedIndex:-1}}}])}(tc),ic="Image I-Frame player does not accept HTMLMediaElements",nc={seekOnAppend:!0},ac=function(e){function t(e,r){var i;return s(this,t),(i=a(this,t,["iframes",e.logger])).hls=void 0,i.stats=void 0,i.variableList=null,i.initPTS=[],i.iframeInstances=void 0,i.instanceCounter=0,Xu||(Xu=function(e){function t(e,r,i,n){var o;return s(this,t),e.streamController||(e.streamController=tc),(o=a(this,t,[e]))._url=r,o.streamController.setInitPts(i),o.streamController.initDetails=n,o}return f(t,e),l(t,[{key:"loadSource",value:function(){}},{key:"loadMediaAt",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:nc;if(!(e<0)){var r=Ie(Ie({},nc),t);this.loadingEnabled||this.startLoad(e),this.streamController.loadMediaAt(e,r)}}}])}(r)),Qu||(Qu=function(e){return function(e){function t(e,r,i,n){return s(this,t),e.cmcdController=void 0,e.emeController=void 0,e.streamController||(e.streamController=rc),e.capLevelController=void 0,e.bufferController=void 0,a(this,t,[e,r,i,n])}return f(t,e),l(t,[{key:"attachImage",value:function(e){this.streamController.image=e}},{key:"detachImage",value:function(){this.streamController.image=void 0}},{key:"loadSource",value:function(){}},{key:"attachMedia",value:function(){throw new Error(ic)}},{key:"detachMedia",value:function(){}},{key:"recoverMediaError",value:function(){}},{key:"transferMedia",value:function(){return null}},{key:"loadMediaAt",value:function(e){if(e<0)return null;this.loadingEnabled||this.startLoad(e),this.streamController.loadMediaAt(e)}}])}(e)}(Xu)),i.hls=e,i.iframeInstances=[],i.registerListeners(),i}return f(t,e),l(t,[{key:"registerListeners",value:function(){var e=this.hls;e&&(e.on(ne.MANIFEST_LOADING,this.clearAsset,this),e.on(ne.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(ne.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(ne.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(ne.FRAG_BUFFERED,this.onFragBuffered,this),e.on(ne.DESTROYING,this.onDestroying,this))}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ne.MANIFEST_LOADING,this.clearAsset,this),e.off(ne.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(ne.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(ne.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(ne.FRAG_BUFFERED,this.onFragBuffered,this),e.off(ne.DESTROYING,this.onDestroying,this))}},{key:"clearAsset",value:function(){this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances.forEach(function(e){return e.destroy()}),this.iframeInstances.length=0}},{key:"onDestroying",value:function(){this.unregisterListeners(),this.clearAsset(),this.hls=void 0}},{key:"onManifestLoaded",value:function(e,t){this.stats=t.stats,this.variableList=t.variableList}},{key:"onLevelsUpdated",value:function(e,t){var r,i=t.levels,n=null==(r=this.hls)?void 0:r.pathwayPriority;i.length&&n&&this.iframeInstances.forEach(function(e){e.pathwayPriority=n})}},{key:"onInitPtsFound",value:function(e,t){var r=t.id,i=t.timestampOffsets;r===de.MAIN&&(this.initPTS=i)}},{key:"onFragBuffered",value:function(e,t){var r,i=this,n=this.hls;n&&n.hasEnoughToStart&&((null==(r=n.mainForwardBufferInfo)?void 0:r.len)||0)>10&&this.iframeInstances.forEach(function(e){var t;e.loadingEnabled||e.startLoad((null==(t=i.hls)||null==(t=t.media)?void 0:t.currentTime)||0)})}},{key:"createIFramePlayer",value:function(e){var t;return this.createInstance(Xu,null==(t=this.hls)?void 0:t.iframeVariants,e)}},{key:"createImageIFramePlayer",value:function(e){var t,r=null==(t=this.hls)?void 0:t.iframeVariants.filter(function(e){return e.imageCodec});return this.createInstance(Qu,r,e,"image-")}},{key:"createInstance",value:function(e,t,r,i){var n=this.hls;if(!n)return null;var a=n.url,s=n.userConfig,o=n.latestLevelDetails,l=n.loadLevelObj,u=n.loadLevel,c=n.bandwidthEstimate,d=n.sessionId,h=this.stats,f=this.variableList;if(null==t||!t.length||!h||!a)return null;var v="".concat(i||"","iframe-player-").concat(this.instanceCounter++),g=n.levels,p=l||g[u],m=Yr(p,s.videoPreference),y=(null==p?void 0:p.pathwayId)||".",k=new e(Ie(Ie({},s),{},{loggerId:v,primarySessionId:d,videoPreference:m,abrEwmaDefaultEstimate:c,streamController:void 0,audioStreamController:void 0,audioTrackController:void 0,subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,id3TrackController:void 0,fpsController:void 0,gapController:void 0,iframeController:void 0,cmcd:void 0,interstitialsController:void 0,backBufferLength:1/0,maxMaxBufferLength:1,capLevelToPlayerSize:!0,enableWorker:!1,autoStartLoad:!1,startFragPrefetch:!1,testBandwidth:!1,progressive:!1},r),a,this.initPTS,o);return this.iframeInstances=this.iframeInstances.filter(function(e){return!e.url}),this.iframeInstances.push(k),k.trigger(ne.MANIFEST_LOADED,{levels:t,contentSteering:{uri:"",pathwayId:y},sessionKeys:null,audioTracks:[],iframeVariants:[],sessionData:null,startTimeOffset:null,stats:h,networkDetails:null,url:a,variableList:f}),k}}])}(Be);var sc=.025,oc=function(e){return e[e.Point=0]="Point",e[e.Range=1]="Range",e}({});function lc(e,t,r){return"".concat(e.identifier,"-").concat(r+1,"-").concat(mu(t))}var uc=function(){return l(function e(t,r){s(this,e),this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=r,this.dateRange=t,this.setDateRange(t)},[{key:"setDateRange",value:function(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}},{key:"reset",value:function(){var e;this.appendInPlaceStarted=!1,null==(e=this.assetListLoader)||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}},{key:"isAssetPastPlayoutLimit",value:function(e){var t;if(e>0&&e>=this.assetList.length)return!0;var r=this.playoutLimit;return!(e<=0||isNaN(r))&&(0===r||((null==(t=this.assetList[e])?void 0:t.startOffset)||0)>r)}},{key:"findAssetIndex",value:function(e){return this.assetList.indexOf(e)}},{key:"identifier",get:function(){return this.dateRange.id}},{key:"startDate",get:function(){return this.dateRange.startDate}},{key:"startTime",get:function(){var e=this.dateRange.startTime;if(this.snapOptions.out){var t=this.dateRange.tagAnchor;if(t)return dc(t,e)?cc(e,t):e}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-cc(t,e)<.1}return!1}},{key:"resumptionOffset",get:function(){var e=this.resumeOffset,t=Z(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 dc(t,e)?cc(e,t):e}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)<sc))},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"]?oc.Range:oc.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 cc(e,t){return e-t.start<t.duration/2&&!(Math.abs(e-(t.start+t.duration))<sc)?t.start:t.start+t.duration}function dc(e,t){return t>e.start-sc&&t<e.start+e.duration+sc}function hc(e,t,r){var i=new self.URL(e,r);return"data:"!==i.protocol&&Rr(i,"_HLS_primary_id",t),i}function fc(e,t){for(;null!=(r=e.assetList[++t])&&r.error;)var r;return t}function vc(e){var t=e.timelineStart,r=e.duration||0;return'["'.concat(e.identifier,'" ').concat(t.toFixed(2),"-").concat((t+r).toFixed(2),"]")}var gc=function(){return l(function e(t,r,i,n){var a=this;s(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(){a.reachedPlayout(a.currentTime)&&a.hls&&a.hls.trigger(ne.PLAYOUT_LIMIT_REACHED,{})};var o=this.hls=new t(r);this.interstitial=i,this.assetItem=n;var l=function(){a.hasDetails=!0};o.once(ne.LEVEL_LOADED,l),o.once(ne.AUDIO_TRACK_LOADED,l),o.once(ne.SUBTITLE_TRACK_LOADED,l),o.on(ne.MEDIA_ATTACHING,function(e,t){var r=t.media;a.removeMediaListeners(),a.mediaAttached=r,a.interstitial.playoutLimit&&(r.addEventListener("timeupdate",a.checkPlayout),a.appendInPlace&&o.on(ne.BUFFER_APPENDED,function(){var e=a.bufferedEnd;a.reachedPlayout(e)&&(a._bufferedEosTime=e,o.trigger(ne.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=hc(t,e.config.primarySessionId||"").href}catch(e){}e.loadSource(t)}}},{key:"bufferedInPlaceToEnd",value:function(e,t){var r;if(!this.appendInPlace)return!1;if(null!=(r=this.hls)&&r.bufferedToEnd)return!0;if(!e)return!1;var i=Math.min(this._bufferedEosTime||1/0,this.duration),n=this.timelineOffset+(t||0),a=Bi.bufferInfo(e,n,.02);return this.getAssetTime(a.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=Bi.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}},{key:"currentTime",get:function(){var e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}},{key:"duration",get:function(){var e=this.assetItem.duration;if(!e)return 0;var t=this.interstitial.playoutLimit;if(t){var r=t-this.startOffset;if(r>0&&r<e)return r}return e}},{key:"remaining",get:function(){var e=this.duration;return e?Math.max(0,e-this.currentTime):0}},{key:"startOffset",get:function(){return this.assetItem.startOffset}},{key:"timelineOffset",get:function(){var e;return(null==(e=this.hls)?void 0:e.config.timelineOffset)||0},set:function(e){var t=this.timelineOffset;if(e!==t){var r=e-t;if(Math.abs(r)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}},{key:"getAssetTime",value:function(e){var t=this.timelineOffset,r=this.duration;return Math.min(Math.max(0,e-t),r)}},{key:"removeMediaListeners",value:function(){var e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}},{key:"bufferSnapShot",value:function(){var e;this.mediaAttached&&(null!=(e=this.hls)&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd))}},{key:"destroy",value:function(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}},{key:"attachMedia",value:function(e){var t;this.loadSource(),null==(t=this.hls)||t.attachMedia(e)}},{key:"detachMedia",value:function(){var e;this.removeMediaListeners(),this.mediaAttached=null,null==(e=this.hls)||e.detachMedia()}},{key:"resumeBuffering",value:function(){var e;null==(e=this.hls)||e.resumeBuffering()}},{key:"pauseBuffering",value:function(){var e;null==(e=this.hls)||e.pauseBuffering()}},{key:"transferMedia",value:function(){var e;return this.bufferSnapShot(),(null==(e=this.hls)?void 0:e.transferMedia())||null}},{key:"resetDetails",value:function(){var e=this.hls;if(e&&this.hasDetails){e.stopLoad();var t=function(e){return delete e.details};e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}},{key:"on",value:function(e,t,r){var i;null==(i=this.hls)||i.on(e,t)}},{key:"once",value:function(e,t,r){var i;null==(i=this.hls)||i.once(e,t)}},{key:"off",value:function(e,t,r){var i;null==(i=this.hls)||i.off(e,t)}},{key:"toString",value:function(){var e;return"HlsAssetPlayer: ".concat(vc(this.assetItem)," ").concat(null==(e=this.hls)?void 0:e.sessionId," ").concat(this.appendInPlace?"append-in-place":"")}}])}(),pc=.033,mc=function(e){function t(e,r){var i;return s(this,t),(i=a(this,t,["interstitials-sched",r])).onScheduleUpdate=void 0,i.eventMap={},i.events=null,i.items=null,i.durations={primary:0,playout:0,integrated:0},i.onScheduleUpdate=e,i}return f(t,e),l(t,[{key:"destroy",value:function(){this.reset(),this.onScheduleUpdate=null}},{key:"reset",value:function(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(function(e){return e.reset()}),this.events=this.items=null}},{key:"resetErrorsInRange",value:function(e,t){return this.events?this.events.reduce(function(r,i){return e<=i.startOffset&&t>i.startOffset?(delete i.error,r+1):r},0):0}},{key:"duration",get:function(){var e=this.items;return e?e[e.length-1].end:0}},{key:"length",get:function(){return this.items?this.items.length:0}},{key:"getEvent",value:function(e){return e&&this.eventMap[e]||null}},{key:"hasEvent",value:function(e){return e in this.eventMap}},{key:"findItemIndex",value:function(e,t){if(e.event)return this.findEventIndex(e.event.identifier);var r=-1;e.nextEvent?r=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(r=this.findEventIndex(e.previousEvent.identifier)+1);var i=this.items;if(i)for(i[r]||(void 0===t&&(t=e.start),r=this.findItemIndexAtTime(t));r>=0&&null!=(n=i[r])&&n.event;){var n;r--}return r}},{key:"findItemIndexAtTime",value:function(e,t){var r=this.items;if(r)for(var i=0;i<r.length;i++){var n=r[i];t&&"primary"!==t&&(n=n[t]);var a=n.start,s=r[i].event,o=null!=s&&s.cue.pre?s.duration:n.end;if(e===a||e>a&&e<o)return i}return-1}},{key:"findJumpRestrictedIndex",value:function(e,t){var r=this.items;if(r)for(var i=e;i<=t&&r[i];i++){var n=r[i].event;if(null!=n&&n.restrictions.jump&&!n.appendInPlace)return i}return-1}},{key:"findEventIndex",value:function(e){var t=this.items;if(t)for(var r=t.length;r--;){var i;if((null==(i=t[r].event)?void 0:i.identifier)===e)return r}return-1}},{key:"findAssetIndex",value:function(e,t){var r=e.assetList,i=r.length;if(i>1)for(var n=0;n<i;n++){var a=r[n];if(!a.error){var s=a.timelineStart;if(t===s||t>s&&(t<s+(a.duration||0)||n===i-1))return n}}return 0}},{key:"assetIdAtEnd",get:function(){var e,t=null==(e=this.items)||null==(e=e[this.length-1])?void 0:e.event;if(t){var r=t.assetList,i=r[r.length-1];if(i)return i.identifier}return null}},{key:"parseInterstitialDateRanges",value:function(e,t){var r=this,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,n=e.main.details,a=n.dateRanges,s=this.events,o=this.parseDateRanges(a,{url:n.url},t),l=Object.keys(a),u=s?s.filter(function(e){return-1===l.indexOf(e.identifier)}):[];o.length&&o.sort(function(e,t){var r=e.cue.pre,i=e.cue.post,n=t.cue.pre,a=t.cue.post;if(r&&!n)return-1;if(n&&!r)return 1;if(i&&!a)return 1;if(a&&!i)return-1;if(!(r||n||i||a)){var s=e.startTime,o=t.startTime;if(s!==o)return s-o}return e.dateRange.tagOrder-t.dateRange.tagOrder}),this.events=o,u.forEach(function(e){r.removeEvent(e)}),this.updateSchedule(e,u,i)}},{key:"updateSchedule",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,i=arguments.length>3&&void 0!==arguments[3]&&arguments[3],n=this.events||[];if(n.length||t.length||this.length<2){var a=this.items,s=this.parseSchedule(n,e,r);(i||t.length||(null==a?void 0:a.length)!==s.length||s.some(function(e,t){return Math.abs(e.playout.start-a[t].playout.start)>.005||Math.abs(e.playout.end-a[t].playout.end)>.005}))&&(this.items=s,this.onScheduleUpdate(t,a))}}},{key:"parseDateRanges",value:function(e,t,r){for(var i=[],n=Object.keys(e),a=0;a<n.length;a++){var s=n[a],o=e[s];if(o.isInterstitial){var l=this.eventMap[s];l?l.setDateRange(o):(l=new uc(o,t),this.eventMap[s]=l,!1===r&&(l.appendInPlace=r)),i.push(l)}}return i}},{key:"parseSchedule",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,i=[],n=t.main.details,a=n.live?1/0:n.edge,s=0;if((e=e.filter(function(e){return!(e.error||e.cue.once&&e.hasPlayed)})).length){this.resolveOffsets(e,t);var o=0,l=0;if(e.forEach(function(t,u){var c=t.cue.pre,d=t.cue.post,h=e[u-1]||null,f=t.appendInPlace,v=d?a:t.startOffset,g=t.duration,p=t.timelineOccupancy===oc.Range?g:0,m=c&&n.live?r+(t.resumeOffset||0):0,y=m||t.resumptionOffset,k=(null==h?void 0:h.startTime)===v,E=v+t.cumulativeDuration,S=f?E+g:v+y;if(c||!d&&v<=0){var T=l;l+=p,t.timelineStart=E;var A=s;s+=g,i.push({event:t,start:E,end:S,playout:{start:A,end:s},integrated:{start:T,end:l}})}else{if(!(v<=a))return;if(!k){var b=v-o;if(b>pc){var I=o,R=l;l+=b;var L=s;s+=b;var P={previousEvent:e[u-1]||null,nextEvent:t,start:I,end:I+b,playout:{start:L,end:s},integrated:{start:R,end:l}};i.push(P)}else b>0&&h&&(h.cumulativeDuration+=b,i[i.length-1].end=v)}d&&(S=E),t.timelineStart=E;var w=l;l+=p;var C=s;s+=g,i.push({event:t,start:E,end:S,playout:{start:C,end:s},integrated:{start:w,end:l}})}var D=m||t.resumeTime;o=d||D>a?a:!c&&S&&t.appendInPlaceStarted&&D-S>pc?S:D}),o<a){var u,c=o,d=l,h=a-o;l+=h;var f=s;s+=h,i.push({previousEvent:(null==(u=i[i.length-1])?void 0:u.event)||null,nextEvent:null,start:o,end:c+h,playout:{start:f,end:s},integrated:{start:d,end:l}})}this.setDurations(a,s,l)}else{i.push({previousEvent:null,nextEvent:null,start:0,end:a,playout:{start:0,end:a},integrated:{start:0,end:a}}),this.setDurations(a,a,a)}return i}},{key:"setDurations",value:function(e,t,r){this.durations={primary:e,playout:t,integrated:r}}},{key:"resolveOffsets",value:function(e,t){var r=this,i=t.main.details,n=i.live?1/0:i.edge,a=0,s=-1;e.forEach(function(o,l){var u=o.cue.pre,c=o.cue.post,d=u?0:c?n:o.startTime;(r.updateAssetDurations(o),s===d?o.cumulativeDuration=a:(a=0,s=d),!c&&o.snapOptions.in&&(o.resumeAnchor=Qr(null,i.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted)&&(r.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1));!o.appendInPlace&&l+1<e.length&&(e[l+1].startTime-e[l].resumeTime<pc&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&r.warn("Could not change append strategy for abutting event ".concat(o))));var h=Z(o.resumeOffset)?o.resumeOffset:o.duration;a+=h})}},{key:"primaryCanResumeInPlaceAt",value:function(e,t){var r=this,i=e.resumeTime,n=e.startTime+e.resumptionOffset;return Math.abs(i-n)>sc?(this.log('"'.concat(e.identifier,'" resumption ').concat(i," not aligned with estimated timeline end ").concat(n)),!1):!Object.keys(t).some(function(n){var a=t[n].details,s=a.edge;if(i>=s)return r.log('"'.concat(e.identifier,'" resumption ').concat(i," past ").concat(n," playlist end ").concat(s)),!1;var o=Qr(null,a.fragments,i);if(!o)return r.log('"'.concat(e.identifier,'" resumption ').concat(i," does not align with any fragments in ").concat(n," playlist (").concat(a.fragStart,"-").concat(a.fragmentEnd,")")),!0;var l="audio"===n?.175:0;return!(Math.abs(o.start-i)<sc+l||Math.abs(o.end-i)<sc+l)&&(r.log('"'.concat(e.identifier,'" resumption ').concat(i," not aligned with ").concat(n," fragment bounds (").concat(o.start,"-").concat(o.end," sn: ").concat(o.sn," cc: ").concat(o.cc,")")),!0)})}},{key:"updateAssetDurations",value:function(e){if(e.assetListLoaded){for(var t=e.timelineStart,r=0,i=!1,n=!1,a=0;a<e.assetList.length;a++){var s=e.assetList[a],o=t+r;s.startOffset=r,s.timelineStart=o,i||(i=null===s.duration),n||(n=!!s.error),r+=s.error?0:s.duration||0}e.duration=i&&!n?Math.max(r,e.duration):r}}},{key:"removeEvent",value:function(e){e.reset(),delete this.eventMap[e.identifier]}}])}(Be);function yc(e){return"[".concat(e.event?'"'+e.event.identifier+'"':"primary",": ").concat(e.start.toFixed(2),"-").concat(e.end.toFixed(2),"]")}var kc=function(){return l(function e(t){s(this,e),this.hls=void 0,this.hls=t},[{key:"destroy",value:function(){this.hls=null}},{key:"loadAssetList",value:function(e,t){var r,i=this,n=e.assetListUrl;try{r=hc(n,this.hls.sessionId,e.baseUrl)}catch(t){var a=this.assignAssetListError(e,ie.ASSET_LIST_LOAD_ERROR,t,n);return void this.hls.trigger(ne.ERROR,a)}t&&"data:"!==r.protocol&&Rr(r,"_HLS_start_offset",""+t);var s=this.hls.config,o=new(0,s.loader)(s),l={type:ce.INTERSTITIAL_ASSET_LIST,responseType:"json",url:r.href},u=s.interstitialAssetListLoadPolicy.default,c={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:function(t,r,n,a){var s=t.data,o=null==s?void 0:s.ASSETS;if(Array.isArray(o))e.assetListResponse=s,i.hls.trigger(ne.ASSET_LIST_LOADED,{event:e,assetListResponse:s,networkDetails:a});else{var l=i.assignAssetListError(e,ie.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),n.url,r,a);i.hls.trigger(ne.ERROR,l)}},onError:function(t,r,n,a){var s=i.assignAssetListError(e,ie.ASSET_LIST_LOAD_ERROR,new Error("Error loading X-ASSET-LIST: HTTP status ".concat(t.code," ").concat(t.text," (").concat(r.url,")")),r.url,a,n);i.hls.trigger(ne.ERROR,s)},onTimeout:function(t,r,n){var a=i.assignAssetListError(e,ie.ASSET_LIST_LOAD_TIMEOUT,new Error("Timeout loading X-ASSET-LIST (".concat(r.url,")")),r.url,t,n);i.hls.trigger(ne.ERROR,a)}};return o.load(l,c,d),this.hls.trigger(ne.ASSET_LIST_LOADING,{event:e}),o}},{key:"assignAssetListError",value:function(e,t,r,i,n,a){return e.error=r,{type:re.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:i,error:r,networkDetails:a,stats:n}}}])}();function Ec(e){var t;null==e||null==(t=e.play())||t.catch(function(){})}function Sc(e,t){return"[".concat(e,"] Advancing timeline position to ").concat(t)}var Tc=function(e){function t(e,r){var i;return s(this,t),(i=a(this,t,["interstitials",e.logger])).HlsPlayerClass=void 0,i.hls=void 0,i.assetListLoader=void 0,i.mediaSelection=null,i.altSelection=null,i.media=null,i.detachedData=null,i.requiredTracks=null,i.manager=null,i.playerQueue=[],i.bufferedPos=-1,i.timelinePos=-1,i.schedule=void 0,i.playingItem=null,i.bufferingItem=null,i.waitingItem=null,i.endedItem=null,i.playingAsset=null,i.endedAsset=null,i.bufferingAsset=null,i.bufferPastEdge=!1,i.shouldPlay=!1,i.onPlay=function(){i.shouldPlay=!0},i.onPause=function(){i.shouldPlay=!1},i.onSeeking=function(){var e=i.currentTime;if(void 0!==e&&!i.playbackDisabled&&i.schedule){var t=e-i.timelinePos;if(!(Math.abs(t)<1/7056e5)){var r=t<=-.01;-1!==i.timelinePos||i.effectivePlayingItem||i.checkStart(),i.timelinePos=e,i.bufferedPos=e;var n=i.playingItem;if(n){if(r)i.schedule.resetErrorsInRange(e,e-t)&&i.updateSchedule(!0);if(i.checkBuffer(),r&&e<n.start||e>=n.end){var a,s=i.findItemIndex(n),o=i.schedule.findItemIndexAtTime(e);if(-1===o&&(o=s+(r?-1:1),i.log("seeked ".concat(r?"back ":"","to position not covered by schedule ").concat(e," (resolving from ").concat(s," to ").concat(o,")"))),!i.isInterstitial(n)&&null!=(a=i.media)&&a.paused&&(i.shouldPlay=!1),!r&&o>s){var l=i.schedule.findJumpRestrictedIndex(s+1,o);if(l>s)return void i.setSchedulePosition(l)}i.setSchedulePosition(o)}else{var u=i.playingAsset;if(u){var c,d=u.timelineStart,h=u.duration||0;if(r&&e<d||e>=d+h)null!=(c=n.event)&&c.appendInPlace&&(i.clearAssetPlayers(n.event,n),i.flushFrontBuffer(e)),i.setScheduleToAssetAtTime(e,u)}else if(i.playingLastItem&&i.isInterstitial(n)){var f=n.event.assetList[0];f&&(i.endedItem=i.playingItem,i.playingItem=null,i.setScheduleToAssetAtTime(e,f))}}}else i.checkBuffer()}}},i.onTimeupdate=function(){var e=i.currentTime;if(void 0!==e&&!i.playbackDisabled&&(-1!==i.timelinePos||i.effectivePlayingItem||i.checkStart(),e>i.timelinePos)){i.timelinePos=e,e>i.bufferedPos&&i.checkBuffer();var t=i.playingItem;if(t&&!i.playingLastItem){if(e>=t.end){i.timelinePos=t.end;var r=i.findItemIndex(t);i.setSchedulePosition(r+1)}var n=i.playingAsset;if(n)e>=n.timelineStart+(n.duration||0)&&i.setScheduleToAssetAtTime(e,n)}}},i.onScheduleUpdate=function(e,t){var r=i.schedule;if(r){var n=i.playingItem,a=r.events||[],s=r.items||[],o=r.durations,l=e.map(function(e){return e.identifier}),u=!(!a.length&&!l.length);(u||t)&&i.log("INTERSTITIALS_UPDATED (".concat(a.length,"): ").concat(a,"\nSchedule: ").concat(s.map(function(e){return yc(e)})," pos: ").concat(i.timelinePos)),l.length&&i.log("Removed events ".concat(l));var c=null,d=null;n&&(c=i.updateItem(n,i.timelinePos),i.itemsMatch(n,c)?i.playingItem=c:i.waitingItem=null),i.waitingItem=i.updateItem(i.waitingItem);var h=i.bufferingItem;if(h&&(d=i.updateItem(h,i.bufferedPos),i.itemsMatch(h,d)?i.bufferingItem=d:h.event&&(i.bufferingItem=i.playingItem,i.clearInterstitial(h.event,null))),e.forEach(function(e){e.assetList.forEach(function(e){i.clearAssetPlayer(e.identifier,null)})}),i.playerQueue.forEach(function(e){if(e.interstitial.appendInPlace){var t=e.assetItem.timelineStart,r=e.timelineOffset-t;if(r)try{e.timelineOffset=t}catch(n){Math.abs(r)>sc&&i.warn("".concat(n,' ("').concat(e.assetId,'" ').concat(e.timelineOffset,"->").concat(t,")"))}}}),u||t){if(i.hls.trigger(ne.INTERSTITIALS_UPDATED,{events:a.slice(0),schedule:s.slice(0),durations:o,removedIds:l}),i.isInterstitial(n)&&l.indexOf(n.event.identifier)>-1)return i.warn('Interstitial "'.concat(n.event.identifier,'" removed while playing')),void i.primaryFallback(n.event);n&&i.trimInPlace(c,n),h&&d!==c&&i.trimInPlace(d,h),i.checkBuffer()}}},i.hls=e,i.HlsPlayerClass=r,i.assetListLoader=new kc(e),i.schedule=new mc(i.onScheduleUpdate,e.logger),i.registerListeners(),i}return f(t,e),l(t,[{key:"registerListeners",value:function(){var e=this.hls;e&&(e.on(ne.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(ne.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ne.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ne.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(ne.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(ne.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(ne.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(ne.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(ne.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(ne.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(ne.BUFFER_APPENDED,this.onBufferAppended,this),e.on(ne.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(ne.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(ne.MEDIA_ENDED,this.onMediaEnded,this),e.on(ne.ERROR,this.onError,this),e.on(ne.DESTROYING,this.onDestroying,this))}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ne.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(ne.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ne.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ne.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(ne.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(ne.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(ne.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(ne.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(ne.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(ne.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(ne.BUFFER_CODECS,this.onBufferCodecs,this),e.off(ne.BUFFER_APPENDED,this.onBufferAppended,this),e.off(ne.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(ne.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(ne.MEDIA_ENDED,this.onMediaEnded,this),e.off(ne.ERROR,this.onError,this),e.off(ne.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=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){ra(e,"play",this.onPlay),ra(e,"pause",this.onPause),ra(e,"seeking",this.onSeeking),ra(e,"timeupdate",this.onTimeupdate)}},{key:"onMediaAttaching",value:function(e,t){var r=this.media=t.media;ta(r,"seeking",this.onSeeking),ta(r,"timeupdate",this.onTimeupdate),ta(r,"play",this.onPlay),ta(r,"pause",this.onPause)}},{key:"onMediaAttached",value:function(e,t){var r=this.effectivePlayingItem,i=this.detachedData;if(this.detachedData=null,null===r)this.checkStart();else if(!i){this.clearScheduleState();var n=this.findItemIndex(r);this.setSchedulePosition(n)}}},{key:"clearScheduleState",value:function(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}},{key:"onMediaDetaching",value:function(e,t){var r=!!t.transferMedia,i=this.media;if(this.media=null,!r&&(i&&this.removeMediaListeners(i),this.detachedData)){var n=this.getBufferingPlayer();n&&(this.log("Removing schedule state for detachedData and ".concat(n)),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,n.detachMedia()),this.shouldPlay=!1}}},{key:"interstitialsManager",get:function(){if(!this.hls)return null;if(this.manager)return this.manager;var e=this,t=function(){return e.bufferingItem||e.waitingItem},r=function(t){return t?e.getAssetPlayer(t.identifier):t},i=function(t,i,a,s,o){if(t){var l=t[i].start,u=t.event;if(u){if("playout"===i||u.timelineOccupancy!==oc.Point){var c=r(a);(null==c?void 0:c.interstitial)===u&&(l+=c.assetItem.startOffset+c[o])}}else l+=("bufferedPos"===s?n():e[s])-t.start;return l}return 0},n=function(){var t=e.bufferedPos;return t===Number.MAX_VALUE?a("primary"):Math.max(t,0)},a=function(t){var r,i;return null!=(r=e.primaryDetails)&&r.live?e.primaryDetails.edge:(null==(i=e.schedule)?void 0:i.durations[t])||0},s=function(t,n){var a,s,o=e.effectivePlayingItem;if((null==o||null==(a=o.event)||!a.restrictions.skip)&&e.schedule){e.log("seek to ".concat(t,' "').concat(n,'"'));var l=e.effectivePlayingItem,u=e.schedule.findItemIndexAtTime(t,n),c=null==(s=e.schedule.items)?void 0:s[u],d=e.getBufferingPlayer(),h=null==d?void 0:d.interstitial,f=null==h?void 0:h.appendInPlace,v=l&&e.itemsMatch(l,c);if(l&&(f||v)){var g=r(e.playingAsset),p=(null==g?void 0:g.media)||e.primaryMedia;if(p){var m="primary"===n?p.currentTime:i(l,n,e.playingAsset,"timelinePos","currentTime"),y=t-m,k=(f?m:p.currentTime)+y;if(k>=0&&(!g||f||k<=g.duration))return void(p.currentTime=k)}}if(c){var E=t;if("primary"!==n){var S=t-c[n].start;E=c.start+S}var T=!e.isInterstitial(c);if(e.isInterstitial(l)&&!l.event.appendInPlace||!T&&!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 I=0;if(T)e.timelinePos=E,e.checkBuffer();else for(var R=c.event.assetList,L=t-(c[n]||c).start,P=R.length;P--;){var w=R[P];if(w.duration&&L>=w.startOffset&&L<w.startOffset+w.duration){I=P;break}}e.setSchedulePosition(u,I)}}else{var C=e.media||(f?null==d?void 0:d.media:null);C&&(C.currentTime=E)}}}},o=function(){var r=e.effectivePlayingItem;if(e.isInterstitial(r))return r;var i=t();return e.isInterstitial(i)?i:null},l={get bufferedEnd(){var r,n=t(),a=e.bufferingItem;return a&&a===n&&(i(a,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-a.playout.start||(null==(r=e.bufferingAsset)?void 0:r.startOffset))||0},get currentTime(){var t=o(),r=e.effectivePlayingItem;return r&&r===t?i(r,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-r.playout.start:0},set currentTime(t){var r=o(),i=e.effectivePlayingItem;i&&i===r&&s(t+i.playout.start,"playout")},get duration(){var e=o();return e?e.playout.end-e.playout.start:0},get assetPlayers(){var t,r=null==(t=o())?void 0:t.event.assetList;return r?r.map(function(t){return e.getAssetPlayer(t.identifier)}):[]},get playingIndex(){var t,r=null==(t=o())?void 0:t.event;return r&&e.effectivePlayingAsset?r.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return o()}};return this.manager={get events(){var t;return(null==(t=e.schedule)||null==(t=t.events)?void 0:t.slice(0))||[]},get schedule(){var t;return(null==(t=e.schedule)||null==(t=t.items)?void 0:t.slice(0))||[]},get interstitialPlayer(){return o()?l:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){var r=t();return e.findItemIndex(r)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){var t=e.effectivePlayingItem;return e.findItemIndex(t)},primary:{get bufferedEnd(){return n()},get currentTime(){var t=e.timelinePos;return t>0?t:0},set currentTime(e){s(e,"primary")},get duration(){return a("primary")},get seekableStart(){return e.seekableStart}},integrated:{get bufferedEnd(){return i(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(e){s(e,"integrated")},get duration(){return a("integrated")},get seekableStart(){return function(t,r){var i;if(0!==t&&"primary"!==r&&null!=(i=e.schedule)&&i.length){var n,a=e.schedule.findItemIndexAtTime(t),s=null==(n=e.schedule.items)?void 0:n[a];if(s)return t+(s[r].start-s.start)}return t}(e.seekableStart,"integrated")}},skip:function(){var t=e.effectivePlayingItem,r=null==t?void 0:t.event;if(r&&!r.restrictions.skip){var i=e.findItemIndex(t);if(r.appendInPlace){var n=t.playout.start+t.event.duration;s(n+.001,"playout")}else e.advanceAfterAssetEnded(r,i,1/0)}}}}},{key:"effectivePlayingItem",get:function(){return this.waitingItem||this.playingItem||this.endedItem}},{key:"effectivePlayingAsset",get:function(){return this.playingAsset||this.endedAsset}},{key:"playingLastItem",get:function(){var e,t=this.playingItem,r=null==(e=this.schedule)?void 0:e.items;return!!(this.playbackStarted&&t&&r)&&this.findItemIndex(t)===r.length-1}},{key:"playbackStarted",get:function(){return null!==this.effectivePlayingItem}},{key:"currentTime",get:function(){var e,t;if(null!==this.mediaSelection){var r=this.waitingItem||this.playingItem;if(!this.isInterstitial(r)||r.event.appendInPlace){var i=this.media;!i&&null!=(e=this.bufferingItem)&&null!=(e=e.event)&&e.appendInPlace&&(i=this.primaryMedia);var n=null==(t=i)?void 0:t.currentTime;if(void 0!==n&&Z(n))return n}}}},{key:"primaryMedia",get:function(){var e;return this.media||(null==(e=this.detachedData)?void 0:e.media)||null}},{key:"isInterstitial",value:function(e){return!(null==e||!e.event)}},{key:"retreiveMediaSource",value:function(e,t){var r=this.getAssetPlayer(e);r&&this.transferMediaFromPlayer(r,t)}},{key:"transferMediaFromPlayer",value:function(e,t){var r=e.interstitial.appendInPlace,i=e.media;if(r&&i===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&i)return void(this.detachedData={media:i});var n=e.transferMedia();this.log("transfer MediaSource from ".concat(e," ").concat(Nr(n))),this.detachedData=n}else t&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))}},{key:"transferMediaTo",value:function(e,t){var r,i,n=this;if(e.media!==t){var a,s=null,o=this.hls,l=e!==o,u=l&&e.interstitial.appendInPlace,c=null==(r=this.detachedData)?void 0:r.mediaSource;if(o.media)u&&(s=o.transferMedia(),this.detachedData=s),a="Primary";else{var d=this.getBufferingPlayer();d?(s=d.transferMedia(),this.detachedData=s,a="".concat(d)):a=c?"detached MediaSource":"detached media"}if(!s)if(c)s=this.detachedData,this.log("using detachedData: MediaSource ".concat(Nr(s)));else if(!this.detachedData||o.media===t){var h=this.playerQueue;h.length>1&&h.forEach(function(e){if(l&&e.interstitial.appendInPlace!==u){var t=e.interstitial;n.clearInterstitial(e.interstitial,null),t.appendInPlace=!1,t.appendInPlace&&n.warn("Could not change append strategy for queued assets ".concat(t))}}),this.hls.detachMedia(),this.detachedData={media:t}}var f=s&&"mediaSource"in s&&"closed"!==(null==(i=s.mediaSource)?void 0:i.readyState);if(this.log("".concat(f?"transfering MediaSource":"attaching media"," to ").concat(l?e:"Primary"," from ").concat(a," (media.currentTime: ").concat(t.currentTime,")")),f||l){var v=f&&s?Ie({},s):{media:t},g=this.schedule;if(g&&l){var p=e.assetId===g.assetIdAtEnd;v.overrides={duration:g.duration,endOfStream:p||!1===e.appendInPlace}}if(!f&&u){var m=e,y=m.assetItem.timelineStart;if(y){var k=m.hls,E=Math.max(this.timelinePos-y,Number.EPSILON);k.startPosition!==E&&(this.log("Set ".concat(m," startPosition: ").concat(E)),k.config.startPosition=E,k.loadingEnabled&&k.startLoad(E))}}e.attachMedia(v)}else e.attachMedia(t)}}},{key:"onInterstitialCueEnter",value:function(){this.onTimeupdate()}},{key:"checkStart",value:function(){var e=this.schedule,t=null==e?void 0:e.events,r=this.hls;if(t&&!this.playbackDisabled&&this.media&&r){-1===this.bufferedPos&&(this.bufferedPos=0);var i=this.timelinePos,n=this.effectivePlayingItem;if(-1===i){if(!r.loadingEnabled)return void this.log("waiting for startLoad( <startPosition> )");var a=r.startPosition;if(this.timelinePos=a,0===t.length)this.setSchedulePosition(0);else if(t[0].cue.pre){this.log(Sc("checkStart (preroll)",a));var s=e.findEventIndex(t[0].identifier);this.setSchedulePosition(s)}else if(a>=0||!this.primaryLive){this.log(Sc("checkStart",a));var o=this.timelinePos=a>0?a:0,l=e.findItemIndexAtTime(o);this.setSchedulePosition(l)}else 0===r.liveSyncPosition?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(n&&!this.playingItem){this.log(Sc("checkStart (playing item)",n.start));var u=e.findItemIndex(n);this.setSchedulePosition(u)}}}},{key:"advanceAssetBuffering",value:function(e,t){var r=e.event,i=r.findAssetIndex(t),n=fc(r,i);if(r.isAssetPastPlayoutLimit(n)){if(this.schedule){var a,s=this.getNextItemIndex(e,!0),o=null==(a=this.schedule.items)?void 0:a[s];o&&this.bufferedToItem(o)}}else this.bufferedToEvent(e,n)}},{key:"livePrerollResumption",value:function(e,t){if(e.cue.pre&&this.primaryLive&&!Z(e.resumeOffset)&&this.hls){var r=this.getLiveStartPos();if(t){var i=this.getBufferingPlayer();return r+(null!=i&&i.interstitial.cue.pre?i.remaining:0)}return r}}},{key:"getNextItemIndex",value:function(e,t){if(this.schedule){var r=this.livePrerollResumption(e.event,t);if(void 0!==r)return this.log("find next item index @".concat(r)),this.schedule.findItemIndexAtTime(r)}return this.findItemIndex(e)+1}},{key:"advanceAfterAssetEnded",value:function(e,t,r){var i=fc(e,r);if(e.isAssetPastPlayoutLimit(i)){if(this.schedule){var n=this.schedule.items;if(n){var a=n[t],s=a.event?this.getNextItemIndex(a):t+1;if(s>=n.length)return void this.setSchedulePosition(-1);var o=e.resumeTime;this.timelinePos<o&&(this.log(Sc("advanceAfterAssetEnded",o)),this.timelinePos=o,e.appendInPlace&&!n[s].event&&this.hls.startLoad(o+.01),this.checkBuffer(this.bufferedPos<o)),this.setSchedulePosition(s)}}}else{if(e.appendInPlace){var l=e.assetList[i];l&&this.advanceInPlace(l.timelineStart)}this.setSchedulePosition(t,i)}}},{key:"setScheduleToAssetAtTime",value:function(e,t){var r=this.schedule;if(r){var i=t.parentIdentifier,n=r.getEvent(i);if(n){var a=r.findEventIndex(i),s=r.findAssetIndex(n,e);this.advanceAfterAssetEnded(n,a,s-1)}}}},{key:"setSchedulePosition",value:function(e,t){var r,i=null==(r=this.schedule)?void 0:r.items;if(i&&!this.playbackDisabled){var n=e>=0?i[e]:null;this.log("setSchedulePosition ".concat(e,", ").concat(t," (").concat(n?yc(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(vc(l))),this.endedAsset=l,this.playingAsset=null,this.hls.trigger(ne.INTERSTITIAL_ASSET_ENDED,{asset:l,assetListIndex:h,event:o,schedule:i.slice(0),scheduleIndex:e,player:c}),a!==this.playingItem)return void(this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(o,this.findItemIndex(this.playingItem),h));this.retreiveMediaSource(u,n),!c.media||null!=(d=this.detachedData)&&d.mediaSource||c.detachMedia()}if(!this.eventItemsMatch(a,n)&&(this.endedItem=a,this.playingItem=this.waitingItem=null,this.log("INTERSTITIAL_ENDED ".concat(o," ").concat(yc(a))),o.hasPlayed=!0,this.hls.trigger(ne.INTERSTITIAL_ENDED,{event:o,schedule:i.slice(0),scheduleIndex:e}),o.cue.once&&this.hls)){var f;this.updateSchedule();var v=null==(f=this.schedule)?void 0:f.items;if(n&&v){var g=this.findItemIndex(n),p=this.livePrerollResumption(o);if(void 0!==p){var m=p,y=this.getNextItemIndex(a);if(!this.isInterstitial(i[y])){var k,E=null==(k=this.primaryDetails)?void 0:k.fragments;if(o.snapOptions.in&&E){var S=Qr(null,E,p);S&&(m=Math.min(Math.max(i[y].start,cc(m,S)),i[y].end))}}if(this.log(Sc("live join (preroll)",m)),this.timelinePos=m,y!==g&&(y||0===y))return void this.advanceSchedule(y,v,void 0,a,s)}this.advanceSchedule(g,v,t,a,s)}return}}this.advanceSchedule(e,i,t,a,s)}}},{key:"advanceSchedule",value:function(e,t,r,i,n){var a=this,s=this.schedule;if(s){var o=t[e]||null,l=this.primaryMedia,u=this.playerQueue;if(u.length&&u.forEach(function(t){var r=t.interstitial,i=s.findEventIndex(r.identifier);(i<e||i>e+1)&&a.clearInterstitial(r,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);var c=o.event;if(void 0===r){var d=fc(c,(r=c.cue.pre?0:s.findAssetIndex(c,this.timelinePos))-1);if(c.isAssetPastPlayoutLimit(d)||c.appendInPlace&&this.timelinePos===o.end)return void this.advanceAfterAssetEnded(c,e,r);r=d}var h=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);var f=this.preloadAssets(c,r);if(this.eventItemsMatch(o,h||i)||(this.waitingItem=o,this.log("INTERSTITIAL_STARTED ".concat(yc(o)," ").concat(c.appendInPlace?"append in place":"")),c.hasPlayed=!1,this.hls.trigger(ne.INTERSTITIAL_STARTED,{event:c,schedule:t.slice(0),scheduleIndex:e})),!c.assetListLoaded)return void this.log("Waiting for ASSET-LIST to complete loading ".concat(c));if(c.assetListLoader&&(c.assetListLoader.destroy(),c.assetListLoader=void 0),!l)return void this.log("Waiting for attachMedia to start Interstitial ".concat(c));this.waitingItem=this.endedItem=null,this.playingItem=o;var v=c.assetList[r];if(!v)return void this.advanceAfterAssetEnded(c,e,r||0);if(f||(f=this.getAssetPlayer(v.identifier)),null===f||f.destroyed){var g=c.assetList.length;this.warn("asset ".concat(r+1,"/").concat(g," player destroyed ").concat(c)),(f=this.createAssetPlayer(c,v,r)).loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&c.appendInPlace&&this.isAssetBuffered(v))return;this.startAssetPlayer(f,r,t,e,l),this.shouldPlay&&Ec(f.media)}else o?(this.resumePrimary(o,e,i),this.shouldPlay&&Ec(this.hls.media)):n&&this.isInterstitial(i)&&(this.endedItem=null,this.playingItem=i,i.event.appendInPlace||this.attachPrimary(s.durations.primary,null))}}},{key:"playbackDisabled",get:function(){return!1===this.hls.config.enableInterstitialPlayback}},{key:"primaryDetails",get:function(){var e;return null==(e=this.mediaSelection)?void 0:e.main.details}},{key:"primaryLive",get:function(){var e;return!(null==(e=this.primaryDetails)||!e.live)}},{key:"resumePrimary",value:function(e,t,r){var i,n;this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=null,this.bufferedToItem(e),this.endedItem=null,this.log("resuming ".concat(yc(e)));var a=this.timelinePos;if(null!=(i=this.detachedData)&&i.mediaSource?this.primaryLive&&this.startLoadingPrimaryAt(a):((a<e.start||a>=e.end||a<this.seekableStart)&&(a=this.getPrimaryResumption(e,t),this.log(Sc("resumePrimary",a)),this.timelinePos=a),this.attachPrimary(a,e)),r){var s=null==(n=this.schedule)?void 0:n.items;s&&(this.log("INTERSTITIALS_PRIMARY_RESUMED ".concat(yc(e))),this.hls.trigger(ne.INTERSTITIALS_PRIMARY_RESUMED,{schedule:s.slice(0),scheduleIndex:t}),this.checkBuffer())}}},{key:"seekableStart",get:function(){var e;return this.primaryLive&&(null==(e=this.primaryDetails)?void 0:e.fragmentStart)||0}},{key:"getPrimaryResumption",value:function(e,t,r){var i=e.start;if(this.primaryLive){if(0===t)return this.hls.startPosition;var n=this.endedItem||this.playingItem,a=null!=n&&n.event?this.livePrerollResumption(n.event,r):void 0;if(void 0!==a)return a;var s=this.primaryDetails;if(s){var o=s.fragmentStart,l=s.edge;if(i<o||i>l&&!r){var u=this.hls.liveSyncPosition;return this.log("primary resumption out of bounds (".concat(i," [").concat(o,"-").concat(l,"]) snapping to liveSync ").concat(u)),u||o}}}return this.log("primary resumption itemStart: ".concat(i)),i}},{key:"getLiveStartPos",value:function(){var e,t=this.hls.startPosition,r=this.hls.liveSyncPosition||0,i=3*((null==(e=this.primaryDetails)?void 0:e.targetduration)||10);return-1===t||r&&r-t<i?r||0:t}},{key:"isAssetBuffered",value:function(e){var t=this.getAssetPlayer(e.identifier);return null!=t&&t.hls?t.hls.bufferedToEnd:Bi.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}},{key:"attachPrimary",value:function(e,t,r){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;var i=this.primaryMedia;if(i){var n=this.hls;n.media?this.checkBuffer():(this.transferMediaTo(n,i),r&&this.startLoadingPrimaryAt(e,r)),r||(this.log(Sc("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,r))}}},{key:"startLoadingPrimaryAt",value:function(e,t){var r=this.hls,i=r.loadingEnabled,n=r.bufferingEnabled,a=r.startPosition,s=r.hasEnoughToStart;if(this.log("Start loading primary @".concat(e," bufferedPos: ").concat(this.bufferedPos," startPosition: ").concat(a," skip seek: ").concat(t," has enough ").concat(s," loadingEnabled: ").concat(i," bufferingEnabled: ").concat(n)),!t&&s||!i||Math.abs(a-e)>.1){var o=this.primaryDetails;if(null!=o&&o.live&&e+.5>=o.edge){var l=this.bufferingItem;return this.log("Resume primary loading when live passes ".concat(e," buffering item: ").concat(l?yc(l):null)),r.pauseBuffering(),void(this.bufferPastEdge=!0)}r.startLoad(e,t)}else n||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(ne.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(ne.BUFFER_CODECS,this.onBufferCodecs,this)}},{key:"onLevelUpdated",value:function(e,t){if(-1!==t.level&&this.schedule){var r=this.hls.levels[t.level];if(r.details){var i=Ie(Ie({},this.mediaSelection||this.altSelection),{},{main:r});this.mediaSelection=i;var n=this.hls.startPosition;if(this.schedule.parseInterstitialDateRanges(i,this.hls.config.interstitialAppendInPlace,-1===n?0:n),this.schedule.items)if(this.effectivePlayingItem){if(this.bufferPastEdge){var a=this.primaryDetails,s=this.bufferedPos;if(null!=a&&a.live&&s+.5<a.edge){this.bufferPastEdge=!1;var o=this.bufferingItem;if(this.log("Live edge ".concat(a.edge," passed buffer: ").concat(s," buffering item: ").concat(o?yc(o):null)),(null==o?void 0:o.end)===1/0){var l=this.playingItem,u=this.isInterstitial(l)&&l.event.appendInPlace;this.hls.startLoad(Math.max(s,o.start),u)}else{var c=this.getBufferingPlayer();if(c)c.bufferedInPlaceToEnd(this.primaryMedia,c.currentTime)&&c.hls&&c.hls.trigger(ne.BUFFERED_TO_END,void 0)}}}}else this.checkStart()}}}},{key:"onAudioTrackUpdated",value:function(e,t){var r=this.hls.audioTracks[t.id],i=this.mediaSelection;if(i){var n=Ie(Ie({},i),{},{audio:r});this.mediaSelection=n}else this.altSelection=Ie(Ie({},this.altSelection),{},{audio:r})}},{key:"onSubtitleTrackUpdated",value:function(e,t){var r=this.hls.subtitleTracks[t.id],i=this.mediaSelection;if(i){var n=Ie(Ie({},i),{},{subtitles:r});this.mediaSelection=n}else this.altSelection=Ie(Ie({},this.altSelection),{},{subtitles:r})}},{key:"onAudioTrackSwitching",value:function(e,t){var r=Vr(t);this.playerQueue.forEach(function(e){var i=e.hls;return i&&(i.setAudioOption(t)||i.setAudioOption(r))})}},{key:"onSubtitleTrackSwitch",value:function(e,t){var r=Vr(t);this.playerQueue.forEach(function(e){var i=e.hls;return i&&(i.setSubtitleOption(t)||-1!==t.id&&i.setSubtitleOption(r))})}},{key:"onBufferCodecs",value:function(e,t){var r=t.tracks;r&&(this.requiredTracks=r)}},{key:"onBufferAppended",value:function(e,t){this.checkBuffer()}},{key:"onBufferFlushed",value:function(e,t){var r=this.playingItem;if(r&&!this.itemsMatch(r,this.bufferingItem)&&!this.isInterstitial(r)){var i=this.timelinePos;this.bufferedPos=i,this.checkBuffer()}}},{key:"onBufferedToEnd",value:function(e){if(this.schedule){var t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(var r=0;r<t.length;r++){var i=t[r];if(i.cue.post){var n=this.getEventItem(i.identifier);n&&this.eventItemsMatch(n,this.bufferingItem)&&this.bufferedToItem(n,0);break}}this.bufferedPos=Number.MAX_VALUE}}}},{key:"onMediaEnded",value:function(e){var t=this.playingItem;if(!this.playingLastItem&&t){var r=this.findItemIndex(t);this.setSchedulePosition(r+1)}else this.shouldPlay=!1}},{key:"updateItem",value:function(e,t){var r,i=null==(r=this.schedule)?void 0:r.items;return e&&i&&i[this.findItemIndex(e,t)]||null}},{key:"trimInPlace",value:function(e,t){var r=this;if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach(function(t,i){e.event.isAssetPastPlayoutLimit(i)&&r.clearAssetPlayer(t.identifier,null)});var i=e.end+.25,n=Bi.bufferInfo(this.primaryMedia,i,0);if(n.end>i||(n.nextStart||0)>i){this.log("trim buffered interstitial ".concat(yc(e)," (was ").concat(yc(t),")"));this.attachPrimary(i,null,!0),this.flushFrontBuffer(i)}}}},{key:"itemsMatch",value:function(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}},{key:"eventItemsMatch",value:function(e,t){var r;return!!t&&(e===t||e.event.identifier===(null==(r=t.event)?void 0:r.identifier))}},{key:"findEventIndex",value:function(e){return this.schedule?this.schedule.findEventIndex(e):-1}},{key:"getEventItem",value:function(e){if(this.schedule){var t,r=null==(t=this.schedule.items)?void 0:t[this.findEventIndex(e)];if(this.isInterstitial(r)&&r.event.identifier===e)return r}}},{key:"findItemIndex",value:function(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}},{key:"updateSchedule",value:function(){var e,t,r=arguments.length>0&&void 0!==arguments[0]&&arguments[0],i=this.mediaSelection;if(i){var n=(null==(e=this.hls)?void 0:e.liveSyncPosition)||0;null==(t=this.schedule)||t.updateSchedule(i,[],n,r)}}},{key:"checkBuffer",value:function(e){var t,r=null==(t=this.schedule)?void 0:t.items;if(r){var i=Bi.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=i.len<1),this.updateBufferedPos(i.end,r,e)}}},{key:"updateBufferedPos",value:function(e,t,r){var i=this.schedule,n=this.bufferingItem;if(!(this.bufferedPos>e)&&i)if(1===t.length&&this.itemsMatch(t[0],n))this.bufferedPos=e;else{var a=this.playingItem,s=this.findItemIndex(a),o=i.findItemIndexAtTime(e);if(this.bufferedPos<e){var l,u=this.findItemIndex(n),c=Math.min(u+1,t.length-1),d=t[c];if((-1===o&&n&&e>=n.end||null!=(l=d.event)&&l.appendInPlace&&e+.01>=d.start)&&(o=c),this.isInterstitial(n)){var h=n.event;if(c-s>1&&!1===h.appendInPlace)return;if(0===h.assetList.length&&h.assetListLoader)return}if(this.bufferedPos=e,o>u&&o>s)this.bufferedToItem(d);else{var f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&d.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(d)&&this.preloadAssets(d.event,0)}}else r&&a&&!this.itemsMatch(a,n)&&(o===s?this.bufferedToItem(a):o===s+1&&this.bufferedToItem(t[o]))}}},{key:"assetsBuffered",value:function(e,t){var r=this;return 0!==e.event.assetList.length&&!e.event.assetList.some(function(e){var i=r.getAssetPlayer(e.identifier);return!(null!=i&&i.bufferedInPlaceToEnd(t))})}},{key:"setBufferingItem",value:function(e){var t=this,r=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(e,r)&&i){var n=i.items,a=i.events;if(!n||!a)return r;var s=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));var l=o?o.remaining:r?r.end-this.timelinePos:0;if(this.log("INTERSTITIALS_BUFFERED_TO_BOUNDARY ".concat(yc(e))+(r?" (".concat(l.toFixed(2)," remaining)"):"")),!this.playbackDisabled)if(s){var u=i.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach(function(e,r){var i=t.getAssetPlayer(e.identifier);i&&(r===u&&i.loadSource(),i.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(function(e){return e.pauseBuffering()});this.hls.trigger(ne.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:a.slice(0),schedule:n.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return r}},{key:"bufferedToItem",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=this.setBufferingItem(e);if(!this.playbackDisabled)if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(null!==r){this.bufferingAsset=null;var i=this.getPrimaryResumption(e,this.findItemIndex(e),!0),n=this.bufferedPos=Math.max(i,Math.min(this.bufferedPos,e.end),this.timelinePos,e.start),a=this.detachedData;if(a)if(a.mediaSource){this.attachPrimary(n,e,!0)}else this.startLoadingPrimaryAt(n);else{var s=this.playingItem,o=this.isInterstitial(s)&&s.event.appendInPlace;this.startLoadingPrimaryAt(n,o)}}}},{key:"bufferedToEvent",value:function(e,t){var r=e.event,i=0===r.assetList.length&&!r.assetListLoader,n=r.cue.once;if(i||!n){var a=this.preloadAssets(r,t);if(null!=a&&a.interstitial.appendInPlace){var s=this.primaryMedia;s&&this.bufferAssetPlayer(a,s)}}}},{key:"preloadAssets",value:function(e,t){var r=e.assetUrl,i=e.assetList.length,n=0===i&&!e.assetListLoader,a=e.cue.once;if(n){var s,o,l=e.timelineStart,u=this.playingItem,c=this.getBufferingPlayer();if(e.appendInPlace)this.isInterstitial(u)||(null==u||null==(s=u.nextEvent)?void 0:s.identifier)!==e.identifier||this.flushFrontBuffer(l+.25);var d=0;if(c&&!c.interstitial.cue.pre||!this.primaryLive||(d=this.getLiveStartPos(),c&&(d+=c.remaining)),d&&!e.cue.pre&&!e.cue.post){var h=d-l;h>0&&(o=Math.round(1e3*h)/1e3)}if(this.log("Load interstitial asset ".concat(t+1,"/").concat(r?1:i," ").concat(e).concat(d?" live-start: ".concat(d," start-offset: ").concat(o," (timeline-start: ").concat(l,")"):"")),r)return this.createAsset(e,0,0,l,e.duration,r);var f=this.assetListLoader.loadAssetList(e,o);f&&(e.assetListLoader=f)}else if(!a&&i){for(var v=t;v<i;v++){var g=e.assetList[v],p=this.getAssetPlayerQueueIndex(g.identifier);-1!==p&&!this.playerQueue[p].destroyed||g.error||this.createAssetPlayer(e,g,v)}var m=e.assetList[t];if(m){var y=this.getAssetPlayer(m.identifier);return y&&y.loadSource(),y}}return null}},{key:"flushFrontBuffer",value:function(e){var t=this,r=this.requiredTracks;if(r){var i=this.primaryDetails;if(!(i&&e>=i.edge))this.log("Removing front buffer starting at ".concat(e)),Object.keys(r).forEach(function(r){t.hls.trigger(ne.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:r})})}}},{key:"getAssetPlayerQueueIndex",value:function(e){for(var t=this.playerQueue,r=0;r<t.length;r++)if(e===t[r].assetId)return r;return-1}},{key:"getAssetPlayer",value:function(e){var t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}},{key:"getBufferingPlayer",value:function(){var e=this.playerQueue,t=this.primaryMedia;if(t)for(var r=0;r<e.length;r++)if(e[r].media===t)return e[r];return null}},{key:"createAsset",value:function(e,t,r,i,n,a){var s={parentIdentifier:e.identifier,identifier:lc(e,a,t),duration:n,startOffset:r,timelineStart:i,uri:a};return this.createAssetPlayer(e,s,t)}},{key:"createAssetPlayer",value:function(e,t,r){var i=this,n=this.hls,a=n.userConfig,s=Yr(n.loadLevelObj||n.levels[n.currentLevel],a.videoPreference),o=n.audioTracks[n.audioTrack],l=n.subtitleTracks[n.subtitleTrack],u=0;if(this.primaryLive||e.appendInPlace){var c=this.timelinePos-t.timelineStart;if(c>=0){var d=t.duration;d&&c<d&&(u=c)}}var h=t.identifier,f=Ie(Ie({},a),{},{maxMaxBufferLength:Math.min(15,n.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:n.sessionId,assetPlayerId:h,abrEwmaDefaultEstimate:n.bandwidthEstimate,interstitialsController:void 0,startPosition:u,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:s,audioPreference:o||a.audioPreference,subtitlePreference:l||a.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(f.timelineOffset=t.timelineStart));var v=f.cmcd;null!=v&&v.sessionId&&v.contentId&&(f.cmcd=Ae({},v,{contentId:mu(t.uri)})),this.getAssetPlayer(h)&&this.warn("Duplicate date range identifier ".concat(e," and asset ").concat(h));var g=new gc(this.HlsPlayerClass,f,e,t);this.playerQueue.push(g),e.assetList[r]=t;var p=!0,m=function(n){if(n.live){var a=new Error("Interstitials MUST be VOD assets ".concat(e)),s={fatal:!0,type:re.OTHER_ERROR,details:ie.INTERSTITIAL_ASSET_ITEM_ERROR,error:a},o=i.findEventIndex(e.identifier);i.handleAssetItemError(s,e,o,r,a.message)}else{var l=n.edge-n.fragmentStart,u=t.duration;(p||null===u||l>u)&&(p=!1,i.log('Interstitial asset "'.concat(h,'" duration change ').concat(u," > ").concat(l)),t.duration=l,i.updateSchedule())}};g.on(ne.LEVEL_UPDATED,function(e,t){var r=t.details;return m(r)}),g.on(ne.LEVEL_PTS_UPDATED,function(e,t){var r=t.details;return m(r)}),g.on(ne.EVENT_CUE_ENTER,function(){return i.onInterstitialCueEnter()});var y=function(e,t){var r=i.getAssetPlayer(h);if(r&&t.tracks){r.off(ne.BUFFER_CODECS,y),r.tracks=t.tracks;var n=i.primaryMedia;i.bufferingAsset===r.assetItem&&n&&!r.media&&i.bufferAssetPlayer(r,n)}};g.on(ne.BUFFER_CODECS,y);g.on(ne.BUFFERED_TO_END,function(){var t=i.getAssetPlayer(h);if(i.log("buffered to end of asset ".concat(t)),t&&i.schedule){var r=i.getEventItem(e.identifier);r&&i.advanceAssetBuffering(r,t.assetItem)}});var k=function(t){return function(){if(i.getAssetPlayer(h)&&i.schedule){i.shouldPlay=!0;var r=i.findEventIndex(e.identifier);i.advanceAfterAssetEnded(e,r,t)}}};return g.once(ne.MEDIA_ENDED,k(r)),g.once(ne.PLAYOUT_LIMIT_REACHED,k(1/0)),g.on(ne.ERROR,function(t,n){if(i.schedule){var a=i.getAssetPlayer(h);if(n.details===ie.BUFFER_STALLED_ERROR)return null!=a&&a.appendInPlace?void i.handleInPlaceStall(e):(i.onTimeupdate(),void i.checkBuffer(!0));n.details!==ie.BUFFER_SEEK_OVER_HOLE&&i.handleAssetItemError(n,e,i.findEventIndex(e.identifier),r,"Asset player error ".concat(n.error," ").concat(e))}}),g.on(ne.DESTROYING,function(){if(i.getAssetPlayer(h)&&i.schedule){var t=new Error("Asset player destroyed unexpectedly ".concat(h)),n={fatal:!0,type:re.OTHER_ERROR,details:ie.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};i.handleAssetItemError(n,e,i.findEventIndex(e.identifier),r,t.message)}}),this.log("INTERSTITIAL_ASSET_PLAYER_CREATED ".concat(vc(t))),this.hls.trigger(ne.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:r,event:e,player:g}),g}},{key:"clearInterstitial",value:function(e,t){this.clearAssetPlayers(e,t),e.reset()}},{key:"clearAssetPlayers",value:function(e,t){var r=this;e.assetList.forEach(function(e){r.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 r=this.playerQueue[t];this.transferMediaFromPlayer(r,null),r.resetDetails()}}},{key:"clearAssetPlayer",value:function(e,t){var r=this.getAssetPlayerQueueIndex(e);if(-1!==r){var i=this.playerQueue[r];this.log("clear ".concat(i," toSegment: ").concat(t?yc(t):t)),this.transferMediaFromPlayer(i,t),this.playerQueue.splice(r,1),i.destroy()}}},{key:"emptyPlayerQueue",value:function(){for(var e;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}},{key:"startAssetPlayer",value:function(e,t,r,i,n){var a=e.interstitial,s=e.assetItem,o=e.assetId,l=a.assetList.length,u=this.playingAsset;this.endedAsset=null,this.playingAsset=s,(null==u?void 0:u.identifier)!==o&&(u&&(this.clearAssetPlayer(u.identifier,r[i]),delete u.error),this.log("INTERSTITIAL_ASSET_STARTED ".concat(t+1,"/").concat(l," ").concat(vc(s))),this.hls.trigger(ne.INTERSTITIAL_ASSET_STARTED,{asset:s,assetListIndex:t,event:a,schedule:r.slice(0),scheduleIndex:i,player:e})),this.bufferAssetPlayer(e,n)}},{key:"bufferAssetPlayer",value:function(e,t){var r;if(this.schedule){var i=e.interstitial,n=e.assetItem,a=this.getEventItem(i.identifier);if(a)if(e.loadSource(),this.setBufferingItem(a),this.bufferingAsset=n,e.bufferedInPlaceToEnd(this.primaryMedia,e.currentTime))this.advanceAssetBuffering(a,n);else{var s=this.getBufferingPlayer();if(s!==e){var o=i.appendInPlace;if(!o||!1!==(null==s?void 0:s.interstitial.appendInPlace)){var l=(null==s?void 0:s.tracks)||(null==(r=this.detachedData)?void 0:r.tracks)||this.requiredTracks;if(o&&n!==this.playingAsset){if(!e.tracks)return void this.log("Waiting for track info before buffering ".concat(e));if(l&&!We(l,e.tracks)){var u=new Error("Asset ".concat(vc(n)," SourceBuffer tracks ('").concat(Object.keys(e.tracks),"') are not compatible with primary content tracks ('").concat(Object.keys(l),"')")),c={fatal:!0,type:re.OTHER_ERROR,details:ie.INTERSTITIAL_ASSET_ITEM_ERROR,error:u},d=i.findAssetIndex(n);return void this.handleAssetItemError(c,i,this.findEventIndex(i.identifier),d,u.message)}}this.transferMediaTo(e,t)}}}}}},{key:"handleInPlaceStall",value:function(e){var t=this.schedule,r=this.primaryMedia;if(t&&r){var i=r.currentTime,n=t.findAssetIndex(e,i),a=e.assetList[n];if(a){var s=this.getAssetPlayer(a.identifier);if(s){var o=s.currentTime||i-a.timelineStart,l=s.duration-o;if(this.warn("Stalled at ".concat(o," of ").concat(o+l," in ").concat(s," ").concat(e," (media.currentTime: ").concat(i,")")),o&&(l/r.playbackRate<.5||s.bufferedInPlaceToEnd(r,s.currentTime))&&s.hls){var u=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,u,n)}}}}}},{key:"advanceInPlace",value:function(e){var t=this.primaryMedia;if(t&&t.currentTime<e){var r="advance currentTime to ".concat(e,", duration: ").concat(t.duration);t.duration>e?(this.log(r),t.currentTime=e):this.log("Cannot ".concat(r))}}},{key:"handleAssetItemError",value:function(e,t,r,i,n){if(e.details!==ie.BUFFER_STALLED_ERROR){var a=t.assetList[i]||null;if(this.warn("INTERSTITIAL_ASSET_ERROR ".concat(a?vc(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=Ae({},e,{fatal:!1,errorAction:vi(!0),asset:a,assetListIndex:i,event:t,schedule:u,scheduleIndex:r,player:l});if(this.hls.trigger(ne.INTERSTITIAL_ASSET_ERROR,c),e.fatal){var d=this.playingAsset,h=this.bufferingAsset,f=new Error(n);if(a&&(this.clearAssetPlayer(s,null),a.error=f),t.assetList.some(function(e){return!e.error}))for(var v=i;v<t.assetList.length;v++)this.resetAssetPlayer(t.assetList[v].identifier);else t.error=f;this.updateSchedule(!0),t.error?this.primaryFallback(t):(null==d?void 0:d.identifier)===s?this.advanceAfterAssetEnded(t,r,i):(null==h?void 0:h.identifier)===s&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,h)}}}}},{key:"primaryFallback",value:function(e){var t=e.timelineStart,r=this.effectivePlayingItem,i=this.playingItem,n=this.seekableStart,a=this.hls.startPosition,s=this.timelinePos;if(this.isInterstitial(r)){this.log('Fallback to primary from event "'.concat(e.identifier,'" start: ').concat(t," pos: ").concat(s," playing: ").concat(yc(r)," startPosition: ").concat(a," seekableStart: ").concat(n," error: ").concat(e.error)),-1===s&&(s=a),s=Math.max(s,n);var o=this.updateItem(r,s);this.itemsMatch(r,o)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(-1===s)return void this.checkStart();if(this.schedule&&this.isInterstitial(i)){var l=this.schedule.findItemIndexAtTime(s);this.setSchedulePosition(l)}}},{key:"onAssetListLoaded",value:function(e,t){var r,i,n=this,a=t.event,s=a.identifier,o=t.assetListResponse.ASSETS;if(null!=(r=this.schedule)&&r.hasEvent(s)){var l=a.timelineStart,u=a.duration,c=0;o.forEach(function(e,t){var r=parseFloat(e.DURATION);n.createAsset(a,t,c,l+c,r,e.URI),c+=r}),a.duration=c,this.log("Loaded asset-list with duration: ".concat(c," (was: ").concat(u,") ").concat(a));var d=this.waitingItem,h=(null==d?void 0:d.event.identifier)===s;this.updateSchedule();var f=null==(i=this.bufferingItem)?void 0:i.event;if(h){var v=this.findEventIndex(s),g=this.getEventItem(s);if(g){if(!this.playingItem&&this.timelinePos>g.end)if(this.schedule.findItemIndexAtTime(this.timelinePos)!==v)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(g)}this.setSchedulePosition(v)}else if((null==f?void 0:f.identifier)===s){var p=a.assetList[0];if(p){var m=this.getAssetPlayer(p.identifier);if(f.appendInPlace){var y=this.primaryMedia;m&&y&&this.bufferAssetPlayer(m,y)}else m&&m.loadSource()}}}}},{key:"onError",value:function(e,t){if(this.schedule)switch(t.details){case ie.ASSET_LIST_PARSING_ERROR:case ie.ASSET_LIST_LOAD_ERROR:case ie.ASSET_LIST_LOAD_TIMEOUT:var r=t.interstitial;r&&(this.updateSchedule(!0),this.primaryFallback(r));break;case ie.BUFFER_STALLED_ERROR:var i=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&i.event.appendInPlace)return void this.handleInPlaceStall(i.event);var n=this.primaryMedia;this.log("Primary player stall @".concat(this.timelinePos," currentTime: ").concat(null==n?void 0:n.currentTime," bufferedPos: ").concat(this.bufferedPos)),this.onTimeupdate(),this.checkBuffer(!0)}}}])}(Be),Ac=function(){return l(function e(t){var r=this;s(this,e),this.hls=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=function(){var e,t=r.media,i=r.levelDetails;if(t&&i&&r.hls){r.currentTime=t.currentTime;var n=r.hls.config,a=r.computeLatency();if(null!==a){r._latency=a;var s=n.lowLatencyMode,o=n.maxLiveSyncPlaybackRate;if(s&&1!==o&&i.live){var l=r.targetLatency;if(null!==l){var u=a-l,c=u<Math.min(r.maxLatency,l+i.targetduration),d=ya(n)&&!(null==(e=r.hls.interstitialsManager)||null==(e=e.playingItem)||!e.event);if(c&&u>.05&&r.forwardBufferLength>1&&!d){var h=Math.min(2,Math.max(1,o)),f=Math.round(2/(1+Math.exp(-.75*u-r.edgeStalled))*20)/20,v=Math.min(h,Math.max(1,f));r.changeMediaPlaybackRate(t,v)}else 1!==t.playbackRate&&0!==t.playbackRate&&r.changeMediaPlaybackRate(t,1)}}}}},this.hls=t,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,t=null==(e=this.hls)?void 0:e.config;if(!t)return 0;if(void 0!==t.liveMaxLatencyDuration)return t.liveMaxLatencyDuration;var r=this.levelDetails;return r?t.liveMaxLatencyDurationCount*r.targetduration:0}},{key:"targetLatency",get:function(){var e=this.levelDetails;if(null===e||!this.hls)return null;var t=this.hls.config,r=e.holdBack,i=e.partHoldBack,n=e.targetduration,a=t.liveSyncDuration,s=t.liveSyncDurationCount,o=t.lowLatencyMode,l=this.hls.userConfig,u=o&&i||r;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||0===u)&&(u=void 0!==a?a:s*n);var c=n;return u+Math.min(this.stallCount*t.liveSyncOnStallIncrease,c)},set:function(e){this.hls&&(this.stallCount=0,this.hls.config.liveSyncDuration=e,this._targetLatencyUpdated=!0)}},{key:"liveSyncPosition",get:function(){var e=this.estimateLiveEdge(),t=this.targetLatency;if(null===e||null===t||!this.hls)return null;var r=this.levelDetails;if(null===r)return null;var i=r.edge,n=e-t-this.edgeStalled,a=i-r.totalduration,s=i-(this.hls.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(a,n),s)}},{key:"drift",get:function(){var e=this.levelDetails;return null===e?1:e.drift}},{key:"edgeStalled",get:function(){var e=this.levelDetails;if(null===e||!this.hls)return 0;var t=3*(this.hls.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}},{key:"forwardBufferLength",get:function(){var e=this.media,t=this.levelDetails;if(!e||!t)return 0;var r=e.buffered.length;return(r?e.buffered.end(r-1):t.edge)-this.currentTime}},{key:"destroy",value:function(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}},{key:"registerListeners",value:function(){var e=this.hls;e&&(e.on(ne.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ne.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ne.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(ne.ERROR,this.onError,this),e.on(ne.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ne.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ne.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ne.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(ne.ERROR,this.onError,this),e.off(ne.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}},{key:"onMediaAttached",value:function(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}},{key:"onMediaDetaching",value:function(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}},{key:"onManifestLoading",value:function(){this._latency=null,this.stallCount=0}},{key:"onLevelUpdated",value:function(e,t){var r=t.details;r.advanced&&this.onTimeupdate(),!r.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}},{key:"onAssetStarted",value:function(e,t){var r,i=this.hls,n=this.media||t.event.appendInPlace&&(null==i||null==(r=i.interstitialsManager)?void 0:r.playerQueue.reduce(function(e,t){return e||t.media},null));i&&n&&n.playbackRate>1&&n.playbackRate<=i.config.maxLiveSyncPlaybackRate&&this.changeMediaPlaybackRate(n,1)}},{key:"onError",value:function(e,t){var r;t.details===ie.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(r=this.levelDetails)&&r.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}},{key:"changeMediaPlaybackRate",value:function(e,t){var r,i;e.playbackRate!==t&&(null==(r=this.hls)||r.logger.debug("[latency-controller]: latency=".concat(this.latency.toFixed(3),", targetLatency=").concat(null==(i=this.targetLatency)?void 0:i.toFixed(3),", forwardBufferLength=").concat(this.forwardBufferLength.toFixed(3),": adjusting playback rate from ").concat(e.playbackRate," to ").concat(t)),e.playbackRate=t)}},{key:"estimateLiveEdge",value:function(){var e=this.levelDetails;return null===e?null:e.edge+e.age}},{key:"computeLatency",value:function(){var e=this.estimateLiveEdge();return null===e?null:e-this.currentTime}}])}(),bc=function(e){function t(e,r,i){var n;return s(this,t),(n=a(this,t,[e,r,i,"subtitle-stream-controller",de.SUBTITLE])).currentTrackId=-1,n.tracksBuffered=[],n.mainDetails=null,n.registerListeners(),n}return f(t,e),l(t,[{key:"onHandlerDestroying",value:function(){this.unregisterListeners(),A(t,"onHandlerDestroying",this,3)([]),this.mainDetails=null}},{key:"registerListeners",value:function(){A(t,"registerListeners",this,3)([]);var e=this.hls;e.on(ne.LEVEL_LOADED,this.onLevelLoaded,this),e.on(ne.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(ne.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(ne.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(ne.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(ne.BUFFER_FLUSHING,this.onBufferFlushing,this)}},{key:"unregisterListeners",value:function(){A(t,"unregisterListeners",this,3)([]);var e=this.hls;e.off(ne.LEVEL_LOADED,this.onLevelLoaded,this),e.off(ne.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(ne.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(ne.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(ne.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(ne.BUFFER_FLUSHING,this.onBufferFlushing,this)}},{key:"startLoad",value:function(e,t){this.stopLoad(),this.state=aa,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}},{key:"onManifestLoading",value:function(){A(t,"onManifestLoading",this,3)([]),this.mainDetails=null}},{key:"onMediaDetaching",value:function(e,r){this.tracksBuffered=[],A(t,"onMediaDetaching",this,3)([e,r])}},{key:"onLevelLoaded",value:function(e,t){this.mainDetails=t.details}},{key:"onSubtitleFragProcessed",value:function(e,t){var r=t.frag,i=t.part;if(t.success){var n=this.tracksBuffered[this.currentTrackId];if(n){for(var a,s=(i||r).start,o=0;o<n.length;o++)if(s>=n[o].start&&s<=n[o].end){a=n[o];break}var l=s+(i||r).duration;if(a?a.end=l:(a={start:s,end:l},n.push(a)),!i||l>=r.end){var u=this.fragmentTracker.fragBuffered(r);i&&u&&(u.range.subs={time:[{startPTS:r.start,endPTS:l}],partial:!0}),pe(r)&&!this.fragContextChanged(r)&&(this.fragPrevious=r),this.fragBufferedComplete(r,i),this.media&&this.tickImmediate()}}}}},{key:"onBufferFlushing",value:function(e,t){var r=t.startOffset,i=t.endOffset;if(0===r&&i!==Number.POSITIVE_INFINITY){var n=i-1;if(n<=0)return;t.endOffsetSubtitles=Math.max(0,n),this.tracksBuffered.forEach(function(e){if(e)for(var t=0;t<e.length;)if(e[t].end<=n)e.shift();else{if(!(e[t].start<n))break;e[t].start=n,t++}}),this.fragmentTracker.removeFragmentsInRange(r,n,de.SUBTITLE)}}},{key:"onError",value:function(e,t){var r=t.frag;(null==r?void 0:r.type)===de.SUBTITLE&&(t.details===ie.FRAG_GAP&&this.fragmentTracker.addAsGap(r),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==na&&(this.state=aa))}},{key:"onSubtitleTracksUpdated",value:function(e,t){var r=this,i=t.subtitleTracks;this.levels&&Qs(this.levels,i)?this.levels=i.map(function(e){return new xr(e)}):(this.tracksBuffered=[],this.levels=i.map(function(e){var t=new xr(e);return r.tracksBuffered[t.id]=[],t}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,de.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null)}},{key:"onSubtitleTrackSwitch",value:function(e,t){var r;if(this.currentTrackId=t.id,this.abortCurrentFrag(),null!=(r=this.levels)&&r.length&&-1!==this.currentTrackId){var i=this.levels[this.currentTrackId];null!=i&&i.details?(this.mediaBuffer=this.mediaBufferTimeRanges,this.state!==na&&this.setInterval(500)):this.mediaBuffer=null}else this.clearInterval()}},{key:"onSubtitleTrackLoaded",value:function(e,t){var r,i=this.currentTrackId,n=this.levels,a=t.details,s=t.id;if(n){var o=n[s];if(!(s>=n.length)&&o){this.log("Subtitle track ".concat(s," loaded [").concat(a.startSN,",").concat(a.endSN,"]").concat(a.lastPartSn?"[part-".concat(a.lastPartSn,"-").concat(a.lastPartIndex,"]"):"",",duration:").concat(a.totalduration)),this.mediaBuffer=this.mediaBufferTimeRanges;var l=this.mainDetails,u=0;if(a.live||null!=(r=o.details)&&r.live){if(a.deltaUpdateFailed)return;if(!l)return void(this.startFragRequested=!1);var c;if(o.details)u=this.alignPlaylists(a,o.details,null==(c=this.levelLastLoaded)?void 0:c.details);a.alignedSliding||(ea(l,a,this),u=a.fragmentStart)}o.details=a,this.levelLastLoaded=o,l&&!this.startFragRequested&&this.setStartPosition(l,u),s===i&&(this.hls.trigger(ne.SUBTITLE_TRACK_UPDATED,{details:a,id:s,groupId:t.groupId}),this.tickImmediate())}}else this.warn("Subtitle tracks were reset while loading level ".concat(s))}},{key:"_handleFragmentLoadProgress",value:function(e){var t=e.frag,r=e.part,i=e.payload;r&&null!=i&&i.byteLength&&this.shouldDecrypt(t)&&this.decryptPayload(i,t,r)}},{key:"_handleFragmentLoadComplete",value:function(e){var t=e.frag,r=e.payload;!this.fragContextChanged(t)&&null!=r&&r.byteLength&&this.shouldDecrypt(t)&&this.decryptPayload(r,t,null)}},{key:"shouldDecrypt",value:function(e){var t=e.decryptdata;return!!(null!=t&&t.key&&t.iv&&Zi(t.method))}},{key:"decryptPayload",value:function(e,t,r){var i=this,n=t.decryptdata,a=performance.now();this.decrypter.decrypt(new Uint8Array(e),n.key.buffer,n.iv.buffer,en(n.method)).then(function(e){i.fragContextChanged(t)||i.hls.trigger(ne.FRAG_DECRYPTED,{frag:t,part:r,payload:e,stats:{tstart:a,tdecrypt:performance.now()}})}).catch(function(e){i.hls.trigger(ne.ERROR,{type:re.MEDIA_ERROR,details:ie.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t,part:r}),r||(i.warn("".concat(e.name,": ").concat(e.message)),i.state=aa)})}},{key:"doTick",value:function(){if(this.state===aa&&this.levels){var e;if(!this.media&&!this.primaryPrefetch&&(this.startFragRequested||!this.config.startFragPrefetch))return;var t=this.currentTrackId,r=this.levels[t],i=null==r?void 0:r.details;if(!i||this.waitForLive(r)||this.waitForCdnTuneIn(i))return void(this.startFragRequested=!1);var n=this.config,a=this.playhead,s=Bi.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],a,n.maxBufferHole),o=s.end,l=s.len;if(l>Math.max(this.hls.maxBufferLength+i.levelTargetDuration,(null==(e=this.hls.mainForwardBufferInfo)?void 0:e.len)||0)||l&&!this.buffering)return;var u=this.getNextFragment(o,i);if(!u)return;if(pe(u)){var c,d=u.sn-i.startSN,h=i.fragments[d-1];u.cc!==(null==h?void 0:h.cc)||null!=(c=i.partList)&&c.length||this.fragmentTracker.getState(h)!==gi||(u=h)}this.loadFragment(u,r,o)}}},{key:"loadFragment",value:function(e,r,i){var n=this.fragmentTracker.getState(e);n!==gi&&n!==mi||A(t,"loadFragment",this,3)([e,r,i])}},{key:"mediaBufferTimeRanges",get:function(){return new Ic(this.tracksBuffered[this.currentTrackId]||[])}}])}(pa),Ic=l(function e(t){s(this,e),this.buffered=void 0;var r=function(e,r,i){if((r>>>=0)>i-1)throw new DOMException("Failed to execute '".concat(e,"' on 'TimeRanges': The index provided (").concat(r,") is greater than the maximum bound (").concat(i,")"));return t[r][e]};this.buffered={get length(){return t.length},end:function(e){return r("end",e,t.length)},start:function(e){return r("start",e,t.length)}}}),Rc={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},Lc=function(e){return String.fromCharCode(Rc[e]||e)},Pc=15,wc=42,Cc={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Dc={17:2,18:4,21:6,22:8,23:10,19:13,20:15},_c={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Mc={25:2,26:4,29:6,30:8,31:10,27:13,28:15},xc=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],Oc=function(){return l(function e(){s(this,e),this.time=null,this.verboseLevel=0},[{key:"log",value:function(e,t){if(this.verboseLevel>=e){var r="function"==typeof t?t():t;je.log("".concat(this.time," [").concat(e,"] ").concat(r))}}}])}(),Fc=function(e){for(var t=[],r=0;r<e.length;r++)t.push(e[r].toString(16));return t},Nc=Object.freeze({foreground:"white",underline:!1,italics:!1,background:"black",flash:!1}),Bc=function(){return l(function e(){s(this,e),this.styles=Nc},[{key:"foreground",get:function(){return this.styles.foreground},set:function(e){var t=this.styles;this.styles={foreground:e,underline:t.underline,italics:t.italics,background:t.background,flash:t.flash}}},{key:"underline",get:function(){return this.styles.underline},set:function(e){var t=this.styles;this.styles={foreground:t.foreground,underline:e,italics:t.italics,background:t.background,flash:t.flash}}},{key:"italics",get:function(){return this.styles.italics},set:function(e){var t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:e,background:t.background,flash:t.flash}}},{key:"background",get:function(){return this.styles.background},set:function(e){var t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:t.italics,background:e,flash:t.flash}}},{key:"flash",get:function(){return this.styles.flash},set:function(e){var t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:t.italics,background:t.background,flash:e}}},{key:"reset",value:function(){this.styles=Nc}},{key:"setStyles",value:function(e){var t=this.styles,r=Object.prototype.hasOwnProperty;this.styles={foreground:r.call(e,"foreground")?e.foreground:t.foreground,underline:r.call(e,"underline")?e.underline:t.underline,italics:r.call(e,"italics")?e.italics:t.italics,background:r.call(e,"background")?e.background:t.background,flash:r.call(e,"flash")?e.flash:t.flash}}},{key:"toString",value:function(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}])}(),Uc=function(){return l(function e(){s(this,e),this.uchar=" ",this.penState=new Bc},[{key:"reset",value:function(){this.uchar=" ",this.penState.reset()}},{key:"setChar",value:function(e,t){this.uchar=e,this.penState.styles=t.styles}},{key:"setPenState",value:function(e){this.penState.styles=e.styles}},{key:"copy",value:function(e){this.uchar=e.uchar,this.penState.styles=e.penState.styles}}])}(),Vc=function(){return l(function e(t){s(this,e),this.chars=[],this.pos=0,this.currPenState=new Bc,this.cueStartTime=null,this.logger=void 0;for(var r=0;r<wc;r++)this.chars.push(new Uc);this.logger=t},[{key:"equals",value:function(e){for(var t=this.chars,r=e.chars,i=0;i<wc;i++){var n=t[i],a=r[i];if(n.uchar!==a.uchar)return!1;var s=n.penState.styles,o=a.penState.styles;if(s!==o&&(s.foreground!==o.foreground||s.underline!==o.underline||s.italics!==o.italics||s.background!==o.background||s.flash!==o.flash))return!1}return!0}},{key:"copy",value:function(e){for(var t=0;t<wc;t++)this.chars[t].copy(e.chars[t])}},{key:"isEmpty",value:function(){for(var e=this.chars,t=0;t<wc;t++){var r=e[t];if(" "!==r.uchar)return!1;var i=r.penState.styles;if(i!==Nc&&("white"!==i.foreground||i.underline||i.italics||"black"!==i.background||i.flash))return!1}return!0}},{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>=wc&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=41)}},{key:"moveCursor",value:function(e){var t=Math.min(this.pos+e,wc);if(e>1)for(var r=this.pos+1;r<t;r++)this.chars[r].setPenState(this.currPenState);this.setCursor(t)}},{key:"backSpace",value:function(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}},{key:"insertChar",value:function(e){var t=this;e>=144&&this.backSpace();var r=Lc(e);this.pos>=wc?this.logger.log(0,function(){return"Cannot insert "+e.toString(16)+" ("+r+") at position "+t.pos+". Skipping it!"}):(this.chars[this.pos].setChar(r,this.currPenState),this.moveCursor(1))}},{key:"clearFromPos",value:function(e){var t;for(t=e;t<wc;t++)this.chars[t].reset()}},{key:"clear",value:function(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}},{key:"clearToEndOfRow",value:function(){this.clearFromPos(this.pos)}},{key:"getTextString",value:function(){for(var e=[],t=!0,r=0;r<wc;r++){var i=this.chars[r].uchar;" "!==i&&(t=!1),e.push(i)}return t?"":e.join("")}},{key:"setPenStyles",value:function(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}])}(),Gc=function(){return l(function e(t){s(this,e),this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(var r=0;r<Pc;r++)this.rows.push(new Vc(t));this.logger=t},[{key:"reset",value:function(){for(var e=0;e<Pc;e++)this.rows[e].clear();this.currRow=14}},{key:"equals",value:function(e){for(var t=!0,r=0;r<Pc;r++)if(!this.rows[r].equals(e.rows[r])){t=!1;break}return t}},{key:"copy",value:function(e){for(var t=0;t<Pc;t++)for(var r=this.rows[t].chars,i=e.rows[t].chars,n=0;n<wc;n++){var a=r[n],s=i[n];a.uchar=s.uchar,a.penState.styles=s.penState.styles}}},{key:"isEmpty",value:function(){for(var e=!0,t=0;t<Pc;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 = "+Nr(e)});var t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(var r=0;r<Pc;r++)this.rows[r].clear();var i=this.currRow+1-this.nrRollUpRows,n=this.lastOutputScreen;if(n){var a=n.rows[i].cueStartTime,s=this.logger.time;if(null!==a&&null!==s&&a<s)for(var o=0;o<this.nrRollUpRows;o++)this.rows[t-this.nrRollUpRows+o+1].copy(n.rows[i+o])}}this.currRow=t;var l=this.rows[this.currRow];if(null!==e.indent){var u=e.indent,c=Math.max(u-1,0);l.setCursor(e.indent),e.color=l.chars[c].penState.foreground}var d={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(d)}},{key:"setBkgData",value:function(e){this.logger.log(2,function(){return"bkgData = "+Nr(e)}),this.backSpace(),this.setPen(e),this.insertChar(32)}},{key:"setRollUpRows",value:function(e){this.nrRollUpRows=e}},{key:"rollUp",value:function(){var e=this;if(null!==this.nrRollUpRows){this.logger.log(1,function(){return e.getDisplayText()});var t=this.currRow+1-this.nrRollUpRows,r=this.rows.splice(t,1)[0];r.clear(),this.rows.splice(this.currRow,0,r),this.logger.log(2,"Rolling up")}else this.logger.log(3,"roll_up but nrRollUpRows not set yet")}},{key:"getDisplayText",value:function(e){e=e||!1;for(var t=[],r="",i=-1,n=0;n<Pc;n++){var a=this.rows[n].getTextString();a&&(i=n+1,e?t.push("Row "+i+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(r=e?"["+t.join(" | ")+"]":t.join("\n")),r}},{key:"getTextAndFormat",value:function(){return this.rows}}])}(),Hc=function(){return l(function e(t,r,i){s(this,e),this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=t,this.outputFilter=r,this.mode=null,this.verbose=0,this.displayedMemory=new Gc(i),this.nonDisplayedMemory=new Gc(i),this.lastOutputScreen=new Gc(i),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i},[{key:"reset",value:function(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}},{key:"getHandler",value:function(){return this.outputFilter}},{key:"setHandler",value:function(e){this.outputFilter=e}},{key:"setPAC",value:function(e){this.writeScreen.setPAC(e)}},{key:"setBkgData",value:function(e){this.writeScreen.setBkgData(e)}},{key:"setMode",value:function(e){e!==this.mode&&(this.mode=e,this.logger.log(2,function(){return"MODE="+e}),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}},{key:"insertChars",value:function(e){for(var t=this,r=0;r<e.length;r++)this.writeScreen.insertChar(e[r]);var i=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,function(){return i+": "+t.writeScreen.getDisplayText(!0)}),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,function(){return"DISPLAYED: "+t.displayedMemory.getDisplayText(!0)}),this.outputDataUpdate())}},{key:"ccRCL",value:function(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}},{key:"ccBS",value:function(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}},{key:"ccAOF",value:function(){}},{key:"ccAON",value:function(){}},{key:"ccDER",value:function(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}},{key:"ccRU",value:function(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}},{key:"ccFON",value:function(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}},{key:"ccRDC",value:function(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}},{key:"ccTR",value:function(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}},{key:"ccRTD",value:function(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}},{key:"ccEDM",value:function(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}},{key:"ccCR",value:function(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}},{key:"ccENM",value:function(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}},{key:"ccEOC",value:function(){var e=this;if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){var t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,function(){return"DISP: "+e.displayedMemory.getDisplayText()})}this.outputDataUpdate(!0)}},{key:"ccTO",value:function(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}},{key:"ccMIDROW",value:function(e){var t={flash:!1};if(t.underline=e%2==1,t.italics=e>=46,t.italics)t.foreground="white";else{var r=Math.floor(e/2)-16;t.foreground=["white","green","blue","cyan","red","yellow","magenta"][r]}this.logger.log(2,"MIDROW: "+Nr(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))}}])}(),Kc=function(){return l(function e(t,r,i){s(this,e),this.channels=[null,null,null],this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0,this.field=void 0,this.outputFilters=void 0,this.logger=new Oc,this.field=t,this.outputFilters=[null,r,i]},[{key:"getHandler",value:function(e){return this.outputFilters[e]}},{key:"setHandler",value:function(e,t){var r;this.outputFilters[e]=t,null==(r=this.channels[e])||r.setHandler(t)}},{key:"getChannel",value:function(e){var t=this.channels[e];return t||(t=this.channels[e]=new Hc(this.field+e-1,this.outputFilters[e],this.logger)),t}},{key:"addData",value:function(e,t){var r=this;this.logger.time=e;for(var i=function(e){var i=127&t[e],n=127&t[e+1],a=!1,s=null;if(0===i&&0===n)return 0;r.logger.log(3,function(){return"["+Fc([t[e],t[e+1]])+"] -> ("+Fc([i,n])+")"});var o=r.cmdHistory;if(i>=16&&i<=31){if(function(e,t,r){return r.a===e&&r.b===t}(i,n,o))return jc(null,null,o),r.logger.log(3,function(){return"Repeated command ("+Fc([i,n])+") is dropped"}),0;jc(i,n,r.cmdHistory),(a=r.parseCmd(i,n))||(a=r.parseMidrow(i,n)),a||(a=r.parsePAC(i,n)),a||(a=r.parseBackgroundAttributes(i,n))}else jc(null,null,o);if(!a&&(s=r.parseChars(i,n))){var l=r.currentChannel;if(l&&l>0)r.getChannel(l).insertChars(s);else r.logger.log(2,"No channel found yet. TEXT-MODE?")}a||s||r.logger.log(2,function(){return"Couldn't parse cleaned data "+Fc([i,n])+" orig: "+Fc([t[e],t[e+1]])})},n=0;n<t.length;n+=2)i(n)}},{key:"parseCmd",value:function(e,t){if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=33&&t<=35))return!1;var r=20===e||21===e||23===e?1:2,i=this.getChannel(r);return 20===e||21===e||28===e||29===e?32===t?i.ccRCL():33===t?i.ccBS():34===t?i.ccAOF():35===t?i.ccAON():36===t?i.ccDER():37===t?i.ccRU(2):38===t?i.ccRU(3):39===t?i.ccRU(4):40===t?i.ccFON():41===t?i.ccRDC():42===t?i.ccTR():43===t?i.ccRTD():44===t?i.ccEDM():45===t?i.ccCR():46===t?i.ccENM():47===t&&i.ccEOC():i.ccTO(t-32),this.currentChannel=r,!0}},{key:"parseMidrow",value:function(e,t){var r=0;if((17===e||25===e)&&t>=32&&t<=47){if((r=17===e?1:2)!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;var i=this.channels[r];return!!i&&(i.ccMIDROW(t),this.logger.log(3,function(){return"MIDROW ("+Fc([e,t])+")"}),!0)}return!1}},{key:"parsePAC",value:function(e,t){var r;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127)&&!((16===e||24===e)&&t>=64&&t<=95))return!1;var i=e<=23?1:2;return r=t>=64&&t<=95?1===i?Cc[e]:_c[e]:1===i?Dc[e]:Mc[e],this.getChannel(i).setPAC(this.interpretPAC(r,t)),this.currentChannel=i,!0}},{key:"interpretPAC",value:function(e,t){var r,i={color:null,italics:!1,indent:null,underline:!1,row:e};return r=t>95?t-96:t-64,i.underline=!(1&~r),r<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(i.italics=!0,i.color="white"):i.indent=4*Math.floor((r-16)/2),i}},{key:"parseChars",value:function(e,t){var r,i,n=null,a=null;(e>=25?(r=2,a=e-8):(r=1,a=e),a>=17&&a<=19)?(i=17===a?t+80:18===a?t+112:t+144,this.logger.log(2,function(){return"Special char '"+Lc(i)+"' in channel "+r}),n=[i]):e>=32&&e<=127&&(n=0===t?[e]:[e,t]);return n&&this.logger.log(3,function(){return"Char codes = "+Fc(n).join(",")}),n}},{key:"parseBackgroundAttributes",value:function(e,t){var r;if(!((16===e||24===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=45&&t<=47))return!1;var i={};16===e||24===e?(r=Math.floor((t-32)/2),i.background=xc[r],t%2==1&&(i.background=i.background+"_semi")):45===t?i.background="transparent":(i.foreground="black",47===t&&(i.underline=!0));var n=e<=23?1:2;return this.getChannel(n).setBkgData(i),!0}},{key:"reset",value:function(){for(var e=0;e<Object.keys(this.channels).length;e++){var t=this.channels[e];t&&t.reset()}jc(null,null,this.cmdHistory)}},{key:"cueSplitAtTime",value:function(e){for(var t=0;t<this.channels.length;t++){var r=this.channels[t];r&&r.cueSplitAtTime(e)}}}])}();function jc(e,t,r){r.a=e,r.b=t}var qc=function(){return l(function e(t,r){s(this,e),this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=t,this.trackName=r},[{key:"dispatchCue",value:function(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}},{key:"newCue",value:function(e,t,r){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=r,this.timelineController.createCaptionsTrack(this.trackName)}},{key:"reset",value:function(){this.cueRanges=[],this.startTime=null}}])}(),Wc=function(){return l(function e(t){s(this,e),this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.cueCache={},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.cueCache={},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(ne.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(ne.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(ne.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ne.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(ne.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(ne.FRAG_LOADING,this.onFragLoading,this),t.on(ne.FRAG_LOADED,this.onFragLoaded,this),t.on(ne.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(ne.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(ne.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(ne.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(ne.BUFFER_APPENDED,this.onBufferAppended,this),t.on(ne.BUFFER_FLUSHING,this.onBufferFlushing,this)},[{key:"destroy",value:function(){var e=this.hls;e.off(ne.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(ne.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ne.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(ne.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(ne.FRAG_LOADING,this.onFragLoading,this),e.off(ne.FRAG_LOADED,this.onFragLoaded,this),e.off(ne.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(ne.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(ne.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(ne.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(ne.BUFFER_APPENDED,this.onBufferAppended,this),e.off(ne.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 qc(this,"textTrack1"),t=new qc(this,"textTrack2"),r=new qc(this,"textTrack3"),i=new qc(this,"textTrack4");this.cea608Parser1=new Kc(1,e,t),this.cea608Parser2=new Kc(3,r,i)}},{key:"addCues",value:function(e,t,r,i,n){for(var a=!1,s=n.length;s--;){var o=n[s],l=Yc(o[0],o[1],t,r);if(l>=0&&(o[0]=Math.min(o[0],t),o[1]=Math.max(o[1],r),a=!0,l/(r-t)>.5))return}if(a||n.push([t,r]),this.config.renderTextTracksNatively){var u=this.cueCache[e];if(u){var c=this.Cues.newCue(null,t,r,i);c.length&&u.push.apply(u,c)}else{var d=this.captionsTracks[e].track;this.Cues.newCue(d,t,r,i)}}else{var h,f=this.Cues.newCue(null,t,r,i),v=null==(h=this.captionsProperties[e])?void 0:h.media;this.hls.trigger(ne.CUES_PARSED,{type:"captions",cues:f,track:e,closedCaptions:v})}}},{key:"onInitPtsFound",value:function(e,t){var r=this,i=t.id,n=t.timestampOffsets,a=this.unparsedVttFrags;i===de.MAIN&&(this.initPTS=n),a.length&&(this.unparsedVttFrags=[],a.forEach(function(e){r.initPTS[e.frag.cc]?r.onFragLoaded(ne.FRAG_LOADED,e):r.hls.trigger(ne.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e.frag,part:null,error:new Error("Subtitle discontinuity domain does not match main")})}))}},{key:"createCaptionsTrack",value:function(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}},{key:"createNativeTrack",value:function(e){if(!this.captionsTracks[e]){var t=this.captionsProperties,r=this.captionsTracks,i=this.cueCache,n=this.media,a=t[e],s=a.label,o=a.languageCode;n&&(i[e]=[],r[e]=Mu(n,"captions",s,o,"hidden"))}}},{key:"createNonNativeTrack",value:function(e){if(!this.nonNativeCaptionsTracks[e]){var t=this.captionsProperties[e];if(t){var r={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=r,this.hls.trigger(ne.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[r]})}}}},{key:"onMediaAttaching",value:function(e,t){this.media=t.media}},{key:"onMediaDetaching",value:function(e,t){var r=!!t.transferMedia;if(this.media=null,!r){if(this.config.renderTextTracksNatively){var i=this.captionsTracks,n=this.cueCache;for(var a in i)i[a].remove(),delete n[a]}this.cueCache={},this.captionsTracks={},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.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}},{key:"onSubtitleTracksUpdated",value:function(e,t){var r=t.subtitleTracks||[];if(r.length&&!this.config.renderTextTracksNatively&&!Qs(this.tracks,r)){var i=r.map(function(e){return{label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e}});this.hls.trigger(ne.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:i})}this.tracks=r}},{key:"onManifestLoaded",value:function(e,t){var r=this;this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(function(e){var t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(t){var i="textTrack".concat(t[1]),n=r.captionsProperties[i];n&&(n.label=e.name,e.lang&&(n.languageCode=e.lang),n.media=e)}})}},{key:"closedCaptionsForLevel",value:function(e){var t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]}},{key:"onFragLoading",value:function(e,t){if(this.enabled&&t.frag.type===de.MAIN){var r,i,n=this.cea608Parser1,a=this.cea608Parser2,s=this.lastSn,o=t.frag,l=o.cc,u=o.sn,c=null!=(r=null==(i=t.part)?void 0:i.index)?r:-1;n&&a&&(u!==s+1||u===s&&c!==this.lastPartIndex+1||l!==this.lastCc)&&(n.reset(),a.reset()),this.lastCc=l,this.lastSn=u,this.lastPartIndex=c}}},{key:"onFragLoaded",value:function(e,t){var r,i=t.frag,n=t.payload;if(i.level<this.tracks.length&&i.type===de.SUBTITLE)if(n.byteLength||null!=(r=i.initSegment)&&null!=(r=r.data)&&r.byteLength){var a=i.decryptdata,s="stats"in t;if(null==a||!a.encrypted||s){var o=this.tracks[i.level],l=this.vttCCs;l[i.cc]||(l[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),(null==o?void 0:o.textCodec)===Tu?this._parseIMSC1(t):this._parseVTTs(t)}}else{var u="part"in t?t.part:null;this.hls.trigger(ne.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,part:u,error:new Error("Empty subtitle payload")})}}},{key:"_parseIMSC1",value:function(e){var t=this,r=e.frag,i=e.payload,n="part"in e?e.part:null,a=this.hls;Ru(i,this.initPTS[r.cc],function(e){t._appendCues(e,r.level),a.trigger(ne.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:r,part:n})},function(e){a.logger.log("Cannot parse IMSC1 (sn: ".concat(r.sn," @").concat(r.start,"): ").concat(e)),a.trigger(ne.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,part:n,error:e})})}},{key:"_parseVTTs",value:function(e){var t,r=this,i=e.frag,n=e.payload,a="part"in e?e.part:null,s=this.initPTS,o=this.unparsedVttFrags,l=s.length-1;if(s[i.cc]||-1!==l){var u=this.hls,c=null==(t=i.initSegment)?void 0:t.data;Su(c?Kt(c,new Uint8Array(n)).buffer:n,this.initPTS[i.cc],this.vttCCs,i.cc,(a&&!c?a:i).start,function(e){r._appendCues(e,i.level),u.trigger(ne.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i,part:a})},function(t){var n=t.message.startsWith("Missing initPTS");u.logger.log("".concat(n?"Deferred parsing of":"Cannot parse"," VTT cue (sn: ").concat(i.sn," @").concat(i.start,"): ").concat(t)),n?o.push(e):(r.config.enableIMSC1&&r._fallbackToIMSC1(e),u.trigger(ne.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,part:a,error:t}))})}else o.push(e)}},{key:"_fallbackToIMSC1",value:function(e){var t=this,r=e.frag,i=e.payload,n=this.tracks[r.level];n.textCodec||Ru(i,this.initPTS[r.cc],function(){n.textCodec=Tu,t._parseIMSC1(e)},function(){n.textCodec="wvtt"})}},{key:"_appendCues",value:function(e,t){var r=this.hls;if(this.config.renderTextTracksNatively){var i,n=null==(i=this.tracks[t].trackNode)?void 0:i.track;if(!n||"disabled"===n.mode)return;e.forEach(function(e){return Ou(n,e)})}else{var a=this.tracks[t];if(!a)return;var s=a.default?"default":"subtitles"+t;r.trigger(ne.CUES_PARSED,{type:"subtitles",cues:e,track:s,subtitleTrack:a})}}},{key:"onFragDecrypted",value:function(e,t){t.frag.type===de.SUBTITLE&&this.onFragLoaded(ne.FRAG_LOADED,t)}},{key:"onSubtitleTracksCleared",value:function(){this.tracks=[],this.captionsTracks={}}},{key:"onFragParsingUserdata",value:function(e,t){if(this.enabled&&this.config.enableCEA708Captions){var r=t.frag,i=t.samples;if(r.type!==de.MAIN||"NONE"!==this.closedCaptionsForLevel(r))for(var n=0;n<i.length;n++){var a=i[n].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();var s=this.extractCea608Data(a);this.cea608Parser1.addData(i[n].pts,s[0]),this.cea608Parser2.addData(i[n].pts,s[1])}}}}},{key:"onBufferAppended",value:function(e,t){if(this.config.renderTextTracksNatively){var r,i=t.type,n=t.timeRanges;if("video"===i&&null!=(r=n[i])&&r.length){var a=this.captionsTracks,s=this.cueCache;Object.keys(s).forEach(function(e){var t,r=null==(t=a[e])?void 0:t.track;if(r)for(var i=s[e],n=0;n<i.length;n++)Ou(r,i[n]);delete s[e]})}}}},{key:"onBufferFlushing",value:function(e,t){var r=t.startOffset,i=t.endOffset,n=t.endOffsetSubtitles,a=t.type,s=this.media;if(s&&!(s.currentTime<i)){if(!a||"video"===a){var o=this.captionsTracks,l=this.cueCache;Object.keys(o).forEach(function(e){return Fu(o[e].track,r,i)}),Object.keys(l).forEach(function(e){for(var t=l[e],n=t.length;n--;){var a=t[n];a.startTime>=r&&a.endTime<=i&&t.splice(n,1)}})}this.config.renderTextTracksNatively&&0===r&&void 0!==n&&this.tracks.forEach(function(e){var t,i=null==(t=e.trackNode)?void 0:t.track;i&&Fu(i,r,n)})}}},{key:"extractCea608Data",value:function(e){for(var t=[[],[]],r=31&e[0],i=2,n=0;n<r;n++){var a=e[i++],s=127&e[i++],o=127&e[i++];if(0!==s||0!==o)if(!!(4&a)){var l=3&a;0!==l&&1!==l||(t[l].push(s),t[l].push(o))}}return t}}])}();function Yc(e,t,r,i){return Math.min(t,i)-Math.max(e,r)}var zc=/\s/,Xc={newCue:function(e,t,r,i){for(var n,a,s,o,l,u=[],c=self.VTTCue||self.TextTrackCue,d=0;d<i.rows.length;d++)if(s=!0,o=0,l="",!(n=i.rows[d]).isEmpty()){for(var h,f=0;f<n.chars.length;f++)zc.test(n.chars[f].uchar)&&s?o++:(l+=n.chars[f].uchar,s=!1);n.cueStartTime=t,t===r&&(r+=1e-4),o>=16?o--:o++;var v=gu(l.trim()),g=Eu(t,r,v);null!=e&&null!=(h=e.cues)&&h.getCueById(g)||((a=new c(t,r,v)).id=g,a.line=d+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*o/32)),u.push(a))}return e&&u.length&&(u.sort(function(e,t){return"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line}),u.forEach(function(t){return Ou(e,t)})),u}},Qc=function(){return l(function e(){s(this,e),this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=0,this.config=null,this.callbacks=null,this.context=null,this.stats=new ue},[{key:"destroy",value:function(){this.callbacks=this.context=this.config=null,this.abortInternal(),this.stats=null}},{key:"load",value:function(e,t,r){var i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=r,this.loadInternal()}},{key:"abort",value:function(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.getNetworkDetails())}},{key:"loadtimeout",value:function(){if(this.config){var e=this.config.loadPolicy.timeoutRetry;if(Me(e,this.stats.retry,!0))this.retry(e);else{var t;je.warn("timeout while loading ".concat(null==(t=this.context)?void 0:t.url));var r=this.callbacks;r&&(this.abortInternal(),r.onTimeout(this.stats,this.context,this.getNetworkDetails()))}}}},{key:"retry",value:function(e){var t=this,r=this.context,i=this.stats;this.retryDelay=De(e,i.retry),i.retry++,je.warn("".concat(status?"HTTP Status "+status:"Timeout"," while loading ").concat(null==r?void 0:r.url,", retrying ").concat(i.retry,"/").concat(e.maxNumRetry," in ").concat(this.retryDelay,"ms")),this.abortInternal(),this.resetInternalLoader(),self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(function(){return t.loadInternal()},this.retryDelay)}}])}();var $c=/(\d+)-(\d+)\/(\d+)/,Jc=function(e){function t(e){var r;return s(this,t),(r=a(this,t)).fetchSetup=void 0,r.request=null,r.response=null,r.controller=null,r.fetchSetup=e.fetchSetup||Zc,r}return f(t,e),l(t,[{key:"destroy",value:function(){this.request=null,A(t,"destroy",this,3)([]),this.response=null,this.controller=null,this.fetchSetup=null}},{key:"abortInternal",value:function(){self.clearTimeout(this.retryTimeout),this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}},{key:"getNetworkDetails",value:function(){return this.response}},{key:"resetInternalLoader",value:function(){this.response=null}},{key:"loadInternal",value:function(){var e=this,t=this.config,r=this.context,i=this.stats;if(t&&r){i.loading.first=0,i.loaded=0,i.aborted=!1,this.controller=new self.AbortController;var n=function(e,t){var r={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(Ae({},e.headers))};e.rangeEnd&&r.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return r}(r,this.controller.signal),a="arraybuffer"===r.responseType,s=a?"byteLength":"length",o=t.loadPolicy,l=o.maxTimeToFirstByteMs,u=o.maxLoadTimeMs;this.request=this.fetchSetup(r,n),self.clearTimeout(this.requestTimeout),t.timeout=l&&Z(l)?l:u,this.requestTimeout=self.setTimeout(function(){e.loadtimeout()},t.timeout),(Ks(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(function(n){var s;e.response=n;var o=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(e.requestTimeout),t.timeout=u,e.requestTimeout=self.setTimeout(function(){e.loadtimeout()},u-(o-i.loading.start)),!n.ok){var l=n.status,c=n.statusText;throw new ed(c||"fetch, bad network response",l,n)}i.loading.first=o,i.total=function(e){var t=e.get("Content-Range");if(t){var r=function(e){var t=$c.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(Z(r))return r}var i=e.get("Content-Length");if(i)return parseInt(i)}(n.headers)||i.total;var d=null==(s=e.callbacks)?void 0:s.onProgress;return d&&Z(t.highWaterMark)?e.loadProgressively(n,i,r,t.highWaterMark,d):a?n.arrayBuffer():"json"===r.responseType?n.json():n.text()}).then(function(n){var a,o,l=e.response;if(!l)throw new Error("loader destroyed");self.clearTimeout(e.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);var u=n[s];u&&(i.loaded=i.total=u);var c={url:l.url,data:n,code:l.status},d=null==(a=e.callbacks)?void 0:a.onProgress;d&&!Z(t.highWaterMark)&&d(i,r,n,l),null==(o=e.callbacks)||o.onSuccess(c,i,r,l)}).catch(function(n){if(self.clearTimeout(e.requestTimeout),!i.aborted){var a,s=n&&n.code||0,o=n?n.message:null,l=t.loadPolicy.errorRetry;if(Me(l,i.retry,!1,{url:r.url,data:void 0,code:s}))e.retry(l);else je.error("".concat(s," while loading ").concat(r.url)),null==(a=e.callbacks)||a.onError({code:s,text:o},r,n?n.details:null,i)}})}}},{key:"getCacheAge",value:function(){var e=null;if(this.response){var t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}},{key:"getResponseHeader",value:function(e){return this.response?this.response.headers.get(e):null}},{key:"loadProgressively",value:function(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,n=arguments.length>4?arguments[4]:void 0,a=new ka,s=e.body.getReader(),o=function(){return s.read().then(function(s){if(s.done)return a.dataLength&&n(t,r,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));var l=s.value,u=l.length;return t.loaded+=u,u<i||a.dataLength?(a.push(l),a.dataLength>=i&&n(t,r,a.flush().buffer,e)):n(t,r,l.buffer,e),o()}).catch(function(){return Promise.reject()})};return o()}}])}(Qc);function Zc(e,t){return new self.Request(e.url,t)}var ed=function(e){function t(e,r,i){var n;return s(this,t),(n=a(this,t,[e])).code=void 0,n.details=void 0,n.code=r,n.details=i,n}return f(t,e),l(t)}(w(Error)),td=/^age:\s*[\d.]+\s*$/im,rd=function(e){function t(e){var r;return s(this,t),(r=a(this,t)).xhrSetup=void 0,r.loader=null,r.xhrSetup=e.xhrSetup||null,r}return f(t,e),l(t,[{key:"destroy",value:function(){A(t,"destroy",this,3)([]),this.loader=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:"getNetworkDetails",value:function(){return this.loader}},{key:"resetInternalLoader",value:function(){this.loader=null}},{key:"loadInternal",value:function(){var e=this,t=this.config,r=this.context;if(t&&r){var i=this.loader=new self.XMLHttpRequest,n=this.stats;n.loading.first=0,n.loaded=0,n.aborted=!1;var a=this.xhrSetup;a?Promise.resolve().then(function(){if(e.loader===i&&!e.stats.aborted)return a.call(e,i,r.url,r)}).catch(function(t){if(e.loader===i&&!e.stats.aborted)return i.open("GET",r.url,!0),a.call(e,i,r.url,r)}).then(function(){e.loader!==i||e.stats.aborted||e.openAndSendXhr(i,r,t)}).catch(function(t){var a;null==(a=e.callbacks)||a.onError({code:i.status,text:t.message},r,i,n)}):this.openAndSendXhr(i,r,t)}}},{key:"openAndSendXhr",value:function(e,t,r){e.readyState||e.open("GET",t.url,!0);var i=t.headers,n=r.loadPolicy,a=n.maxTimeToFirstByteMs,s=n.maxLoadTimeMs;if(i)for(var o in i)e.setRequestHeader(o,i[o]);t.rangeEnd&&e.setRequestHeader("Range","bytes=".concat(t.rangeStart,"-").concat(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),r.timeout=a&&Z(a)?a:s,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),e.send()}},{key:"readystatechange",value:function(){var e=this.context,t=this.loader,r=this.stats;if(e&&t){var i=t.readyState,n=this.config;if(!r.aborted&&i>=2&&(0===r.loading.first&&(r.loading.first=Math.max(self.performance.now(),r.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(r.loading.first-r.loading.start)))),4===i)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;var a=t.status,s="text"===t.responseType?t.responseText:null;if(a>=200&&a<300){var o=null!=s?s:t.response;if(null!=o){var l,u;r.loading.end=Math.max(self.performance.now(),r.loading.first);var c="arraybuffer"===t.responseType?o.byteLength:o.length;r.loaded=r.total=c,r.bwEstimate=8e3*r.total/(r.loading.end-r.loading.first);var d=null==(l=this.callbacks)?void 0:l.onProgress;d&&d(r,e,o,t);var h={url:t.responseURL,data:o,code:a};return e.rangeEnd&&c!==e.rangeEnd-e.rangeStart&&je.warn("Payload length ".concat(c," does not match requested Range: bytes=").concat(e.rangeStart,"-").concat(e.rangeEnd-1)),void(null==(u=this.callbacks)||u.onSuccess(h,r,e,t))}}var f,v=n.loadPolicy.errorRetry;if(Me(v,r.retry,!1,{url:e.url,data:void 0,code:a}))this.retry(v);else je.error("".concat(a," while loading ").concat(e.url)),null==(f=this.callbacks)||f.onError({code:a,text:t.statusText},e,t,r)}}}},{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&&td.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}}])}(Qc),id=Ie(Ie({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,loopBackBufferFlush:void 0,startOnSegmentBoundary:!1,nextAudioTrackBufferFlushForwardOffset:.25,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,skipBufferHolePadding:.1,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveMaxUnchangedPlaylistRefresh: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,appendTimeout:1/0,ignorePlaylistParsingErrors:!1,loader:rd,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,handleMpegTsVideoIntegrityErrors:"process",abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,abrSwitchInterval:0,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:pn,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,emsgKLVSchemaUri:void 0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,iframeCacheLimit:2097152,useMediaCapabilities:!0,preserveManualLevelOnError:!1,errorPenaltyExpireMs:0,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,streamController:ec,abrController:zr,bufferController:io,capLevelController:co,errorController:di,fpsController:su,id3TrackController:Wu,gapController:Bu,latencyController:Ac},{cueHandler:Xc,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:bc,subtitleTrackController:Nu,timelineController:Wc,audioStreamController:zs,audioTrackController:Js,emeController:iu,cmcdController:$l,contentSteeringController:Jl,iframeController:ac,interstitialsController:Tc});function nd(e,t,r){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');if(void 0!==t.liveMaxUnchangedPlaylistRefresh){var i=t.liveMaxUnchangedPlaylistRefresh,n=(a=i,s=2,o=1/0,Math.max(s,Math.min(a,o)));n!==i&&r.warn('hls.js config: "liveMaxUnchangedPlaylistRefresh" clamped from '.concat(i," to ").concat(n,".")),t.liveMaxUnchangedPlaylistRefresh=n}var a,s,o,l=ad(e),u=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(function(e){var i="".concat("level"===e?"playlist":e,"LoadPolicy"),n=void 0===t[i],a=[];u.forEach(function(r){var s="".concat(e,"Loading").concat(r),o=t[s];if(void 0!==o&&n){a.push(s);var u=l[i].default;switch(t[i]={default:u},r){case"TimeOut":u.maxLoadTimeMs=o,u.maxTimeToFirstByteMs=o;break;case"MaxRetry":u.errorRetry.maxNumRetry=o,u.timeoutRetry.maxNumRetry=o;break;case"RetryDelay":u.errorRetry.retryDelayMs=o,u.timeoutRetry.retryDelayMs=o;break;case"MaxRetryTimeout":u.errorRetry.maxRetryDelayMs=o,u.timeoutRetry.maxRetryDelayMs=o}}}),a.length&&r.warn('hls.js config: "'.concat(a.join('", "'),'" setting(s) are deprecated, use "').concat(i,'": ').concat(Nr(t[i])))}),Ie(Ie({},l),t)}function ad(e){return e&&"object"===R(e)?Array.isArray(e)?e.map(ad):Object.keys(e).reduce(function(t,r){return t[r]=ad(e[r]),t},{}):e}function sd(e,t){var r=e.loader;r!==Jc&&r!==rd?(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=Jc,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}var od=function(e){function t(e,r){var i;return s(this,t),(i=a(this,t,[e,"level-controller"]))._levels=[],i._firstLevel=-1,i._maxAutoLevel=-1,i._startLevel=void 0,i.currentLevel=null,i.currentLevelIndex=-1,i.manualLevelIndex=-1,i.steering=void 0,i.lastABRSwitchTime=-1,i._iframeVariants=[],i.onParsedComplete=void 0,i.steering=r,i._registerListeners(),i}return f(t,e),l(t,[{key:"_registerListeners",value:function(){var e=this.hls;e.on(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ne.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(ne.LEVEL_LOADED,this.onLevelLoaded,this),e.on(ne.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(ne.FRAG_BUFFERED,this.onFragBuffered,this),e.on(ne.ERROR,this.onError,this)}},{key:"_unregisterListeners",value:function(){var e=this.hls;e.off(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ne.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(ne.LEVEL_LOADED,this.onLevelLoaded,this),e.off(ne.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(ne.FRAG_BUFFERED,this.onFragBuffered,this),e.off(ne.ERROR,this.onError,this)}},{key:"destroy",value:function(){this._unregisterListeners(),this.steering=null,this.resetLevels(),A(t,"destroy",this,3)([])}},{key:"stopLoad",value:function(){this._levels.forEach(function(e){e.loadError=0,e.fragmentError=0}),A(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,this._iframeVariants=[]}},{key:"onManifestLoading",value:function(e,t){this.resetLevels()}},{key:"onManifestLoaded",value:function(e,t){var r=this,i=this.hls.config.preferManagedMediaSource,n=[],a={},s={},o=!1,l=!1,u=!1,c=!1;t.levels.forEach(function(e){var t=e.attrs,d=cd(e,i),h=e.audioCodec,f=e.videoCodec,v=e.imageCodec,g=e.width,p=e.height;if(d){o||(o=!(!g||!p)),l||(l=!!f),u||(u=!!h),c||(c=!!v);var m=t.CODECS,y=t["FRAME-RATE"],k=t["HDCP-LEVEL"],E=t["PATHWAY-ID"],S=t.RESOLUTION,T=t["VIDEO-RANGE"],A="".concat(E||".","-"),b="".concat(A).concat(e.bitrate,"-").concat(S,"-").concat(y,"-").concat(m,"-").concat(T,"-").concat(k);if(a[b])if(a[b].uri===e.url||e.attrs["PATHWAY-ID"])e.iframes||(a[b].addGroupId("audio",t.AUDIO),a[b].addGroupId("text",t.SUBTITLES));else{var I=s[b]+=1;e.attrs["PATHWAY-ID"]=new Array(I+1).join(".");var R=r.createLevel(e);a[b]=R,n.push(R)}else{var L=r.createLevel(e);a[b]=L,s[b]=1,n.push(L)}}else r.log('Some or all CODECS not supported "'.concat(t.CODECS,'"'))}),this.filterAndSortMediaOptions(n,t,o,l,u,c)}},{key:"createLevel",value:function(e){var t=new xr(e),r=e.supplemental;if(null!=r&&r.videoCodec&&!ud(r.videoCodec,this.hls.config.preferManagedMediaSource)){var i=new Error('SUPPLEMENTAL-CODECS not supported "'.concat(r.videoCodec,'"'));this.log(i.message),t.supportedResult=Tr(i,[])}return t}},{key:"filterAndSortMediaOptions",value:function(e,t,r,i,n,a){var s,o=this,l=[],u=[],c=e,d=(null==(s=t.stats)?void 0:s.parsing)||{},h=this.hls.config.preferManagedMediaSource;if((r||i)&&n&&(c=c.filter(function(e){var t,r=e.videoCodec,i=e.videoRange,n=e.width,a=e.height;return(!!r||!(!n||!a))&&(!!(t=i)&&Pr.indexOf(t)>-1)})),i&&a&&(c=c.filter(function(e){return!e.imageCodec})),0===c.length)return Promise.resolve().then(function(){if(o.hls){var e="no level with compatible codecs found in manifest",r=e;t.levels.length&&(r="one or more CODECS in variant not supported: ".concat(Nr(t.levels.map(function(e){return e.attrs.CODECS}).filter(function(e,t,r){return r.indexOf(e)===t}))),o.warn(r),e+=" (".concat(r,")"));var i=new Error(e);o.hls.trigger(ne.ERROR,{type:re.MEDIA_ERROR,details:ie.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:i,reason:r})}}),void(d.end=performance.now());t.audioTracks&&dd(l=t.audioTracks.filter(function(e){return!e.audioCodec||ld(e.audioCodec,h)})),t.subtitles&&dd(u=t.subtitles);var f=c.slice(0);c.sort(function(e,t){if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return Pr.indexOf(e.videoRange)-Pr.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){var i=cr(e.videoCodec),n=cr(t.videoCodec);if(i!==n)return n-i}if(e.uri===t.uri&&e.codecSet!==t.codecSet){var a=dr(e.codecSet),s=dr(t.codecSet);if(a!==s)return s-a}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0});var v=f[0];if(this.steering&&(c=this.steering.filterParsedLevels(c)).length!==f.length)for(var g=0;g<f.length;g++)if(f[g].pathwayId===c[0].pathwayId){v=f[g];break}this._levels=c;for(var p=0;p<c.length;p++)if(c[p]===v){var m;this._firstLevel=p;var y=v.bitrate,k=this.hls.bandwidthEstimate;if(this.log("manifest loaded, ".concat(c.length," level(s) found, first bitrate: ").concat(y)),void 0===(null==(m=this.hls.userConfig)?void 0:m.abrEwmaDefaultEstimate)){var E=Math.min(y,this.hls.config.abrEwmaDefaultEstimateMax);E>k&&k===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=E)}break}var S=t.iframeVariants.filter(function(e){return cd(e,h)});this._iframeVariants=S;var T=n&&!i,A=this.hls.config,b=!(!A.audioStreamController||!A.audioTrackController),I={levels:c,audioTracks:l,subtitleTracks:u,iframeVariants:S,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:i,altAudio:b&&!T&&l.some(function(e){return!!e.url})};d.end=performance.now(),this.hls.trigger(ne.MANIFEST_PARSED,I)}},{key:"iframeVariants",get:function(){return 0===this._iframeVariants.length?null:this._iframeVariants}},{key:"levels",get:function(){return 0===this._levels.length?null:this._levels}},{key:"loadLevelObj",get:function(){return this.currentLevel}},{key:"level",get:function(){return this.currentLevelIndex},set:function(e){var t=this._levels;if(0!==t.length){if(e<0||e>=t.length){var r=new Error("invalid level idx"),i=e<0;if(this.hls.trigger(ne.ERROR,{type:re.OTHER_ERROR,details:ie.LEVEL_SWITCH_ERROR,level:e,fatal:i,error:r,reason:r.message}),i)return;e=Math.min(e,t.length-1)}var n=this.currentLevelIndex,a=this.currentLevel,s=a?a.attrs["PATHWAY-ID"]:void 0,o=t[e],l=o.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=o,n!==e||!a||s!==l){this.log("Switching to level ".concat(e," (").concat(o.height?o.height+"p ":"").concat(o.videoRange?o.videoRange+" ":"").concat(o.codecSet?o.codecSet+" ":"","@").concat(o.bitrate,")").concat(l?" with Pathway "+l:""," from level ").concat(n).concat(s?" with Pathway "+s:""));var u={level:e,attrs:o.attrs,details:o.details,bitrate:o.bitrate,averageBitrate:o.averageBitrate,maxBitrate:o.maxBitrate,realBitrate:o.realBitrate,width:o.width,height:o.height,codecSet:o.codecSet,audioCodec:o.audioCodec,videoCodec:o.videoCodec,audioGroups:o.audioGroups,subtitleGroups:o.subtitleGroups,loaded:o.loaded,loadError:o.loadError,fragmentError:o.fragmentError,name:o.name,id:o.id,uri:o.uri,url:o.url,urlId:0,audioGroupIds:o.audioGroupIds,textGroupIds:o.textGroupIds};this.hls.trigger(ne.LEVEL_SWITCHING,u);var c=o.details;if(!c||c.live){var d=this.switchParams(o.uri,null==a?void 0:a.details,c);this.loadPlaylist(d)}}}}},{key:"manualLevel",get:function(){return this.manualLevelIndex},set:function(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}},{key:"firstLevel",get:function(){return this._firstLevel},set:function(e){this._firstLevel=e}},{key:"startLevel",get:function(){if(void 0===this._startLevel){var e=this.hls.config.startLevel;return void 0!==e?e:this.hls.firstAutoLevel}return this._startLevel},set:function(e){this._startLevel=e}},{key:"pathways",get:function(){return this.steering?this.steering.pathways():[]}},{key:"pathwayPriority",get:function(){return this.steering?this.steering.pathwayPriority:null},set:function(e){if(this.steering){var t=this.steering.pathways(),r=e.filter(function(e){return-1!==t.indexOf(e)});if(e.length<1)return void this.warn("pathwayPriority ".concat(e," should contain at least one pathway from list: ").concat(t));this.steering.pathwayPriority=r}}},{key:"onError",value:function(e,t){!t.fatal&&t.context&&t.context.type===ce.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}},{key:"onFragBuffered",value:function(e,t){var r=t.frag;if(r.type===de.MAIN){var i=r.elementaryStreams;if(!Object.keys(i).some(function(e){return!!i[e]}))return;var n=this._levels[r.level];null!=n&&n.loadError&&(this.log("Resetting level error count of ".concat(n.loadError," on frag buffered")),n.loadError=0)}}},{key:"onLevelLoaded",value:function(e,t){var r,i,n=t.level,a=t.details,s=t.levelInfo;if(!s)return this.warn("Invalid level index ".concat(n)),void(null!=(i=t.deliveryDirectives)&&i.skip&&(a.deltaUpdateFailed=!0));if(s===this.currentLevel||t.withoutMultiVariant){0===s.fragmentError&&(s.loadError=0);var o=s.details;o===t.details&&o.advanced&&(o=void 0),this.playlistLoaded(n,t,o)}else null!=(r=t.deliveryDirectives)&&r.skip&&(a.deltaUpdateFailed=!0)}},{key:"loadPlaylist",value:function(e){A(t,"loadPlaylist",this,3)([]),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}},{key:"loadingPlaylist",value:function(e,r){A(t,"loadingPlaylist",this,3)([e,r]);var i=this.getUrlWithDirectives(e.uri,r),n=this.currentLevelIndex,a=e.attrs["PATHWAY-ID"],s=e.details,o=null==s?void 0:s.age;this.log("Loading level index ".concat(n).concat(void 0!==(null==r?void 0:r.msn)?" at sn "+r.msn+" part "+r.part:"").concat(a?" Pathway "+a:"").concat(o&&s.live?" age "+o.toFixed(1)+(s.type&&" "+s.type||""):""," ").concat(i)),this.hls.trigger(ne.LEVEL_LOADING,{url:i,level:n,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:r||null})}},{key:"nextLoadLevel",get:function(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},set:function(e){var t=this.currentLevelIndex;if(-1===this.manualLevelIndex&&e!==t&&-1!==e){var r=this.hls.config.abrSwitchInterval;if(r>0){var i=performance.now(),n=i-this.lastABRSwitchTime,a=1e3*r;if(this.lastABRSwitchTime>-1&&n<a)return void this.warn("Preventing ABR level switch: ".concat(t," -> ").concat(e," (").concat(Math.round(n),"ms < ").concat(a,"ms / ").concat(r,"s)"));this.lastABRSwitchTime=i,this.log("Allowing ABR level switch: ".concat(t," -> ").concat(e," (").concat(Math.round(n),"ms >= ").concat(a,"ms / ").concat(r,"s)"))}}this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}},{key:"removeLevel",value:function(e){var t,r=this;if(1!==this._levels.length){var i=this._levels.filter(function(t,i){return i!==e||(r.steering&&r.steering.removeLevel(t),t===r.currentLevel&&(r.currentLevel=null,r.currentLevelIndex=-1,t.details&&t.details.fragments.forEach(function(e){return e.level=-1})),!1)});zn(i),this._levels=i,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);var n=i.length-1;this._firstLevel=Math.min(this._firstLevel,n),this._startLevel&&(this._startLevel=Math.min(this._startLevel,n)),this.hls.trigger(ne.LEVELS_UPDATED,{levels:i})}}},{key:"onLevelsUpdated",value:function(e,t){var r=t.levels;this._levels=r}},{key:"checkMaxAutoUpdated",value:function(){var e=this.hls,t=e.autoLevelCapping,r=e.maxAutoLevel,i=e.maxHdcpLevel;this._maxAutoLevel!==r&&(this._maxAutoLevel=r,this.hls.trigger(ne.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:r,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}])}(Xs);function ld(e,t){return or(e,"audio",t)}function ud(e,t){return or(e,"video",t)}function cd(e,t){var r=e.audioCodec,i=e.videoCodec;r&&(e.audioCodec=r=vr(r,t)||void 0),i&&(i=e.videoCodec=function(e){for(var t=e.split(","),r=0;r<t.length;r++){var i=t[r].split(".");i.length>2&&"avc1"===i[0]&&(t[r]="avc1.".concat(parseInt(i[1]).toString(16)).concat(("000"+parseInt(i[2]).toString(16)).slice(-4)))}return t.join(",")}(i));var n=e.unknownCodecs;return!((null==n?void 0:n.length)||0||r&&!ld(r,t)||i&&!ud(i,t))}function dd(e){var t={};e.forEach(function(e){var r=e.groupId||"";e.id=t[r]=t[r]||0,t[r]++})}var hd=function(e){function t(e,r){var i;return s(this,t),(i=a(this,t,["key-loader",r])).config=void 0,i.keyLoaderInfo={},i.emeController=null,i.config=e,i}return f(t,e),l(t,[{key:"abort",value:function(e){for(var t in this.keyLoaderInfo){var r=this.keyLoaderInfo[t].loader;if(r){var i;if(e&&e!==(null==(i=r.context)?void 0:i.frag.type))return;r.abort()}}}},{key:"destroy",value:function(){for(var e in this.keyLoaderInfo){var t=this.keyLoaderInfo[e].loader;t&&t.destroy()}this.emeController=null,this.keyLoaderInfo={}}},{key:"loadClear",value:function(e,t,r){return this.emeController?this.emeController.loadClear(e,t,r):null}},{key:"load",value:function(e,t){var r=this;return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(function(i){return r.loadInternal(e,t,i)}):this.loadInternal(e,t)}},{key:"loadInternal",value:function(e,t,r){var i=this;r&&e.setKeyFormat(r);var n=e.decryptdata;if(!n){var a=new Error(r?"Expected frag.decryptdata to be defined after setting format ".concat(r):"Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ".concat(this.emeController&&this.config.emeEnabled,")"));return Promise.reject(fd(e,ie.KEY_LOAD_ERROR,a))}var s=e;switch(n.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===n.keyFormat?this.loadKeyHTTP(s):t?t.then(function(){return i.loadKeyEME(s)}):this.loadKeyEME(s);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(s);default:return Promise.reject(fd(e,ie.KEY_LOAD_ERROR,new Error('Key supplied with unsupported METHOD: "'.concat(n.method,'"'))))}}},{key:"loadKeyEME",value:function(e){if(this.emeController&&this.config.emeEnabled){var t;if(!e.decryptdata.keyId&&null!=(t=e.initSegment)&&t.data){var r=function(e){var t=[];return Ut(e,function(e){return t.push(e.subarray(8,24))}),t}(e.initSegment.data);if(r.length){var i=r[0],n=e.decryptdata.uri;if(i.some(function(e){return 0!==e}))this.log("Using keyId found in init segment ".concat(ft(i)," keyUri: ").concat(n)),kn.setKeyIdForUri(n,i);else{var a=kn.addKeyIdForUri(n);this.log("Patching empty keyId with ".concat(ft(a)," keyUri: ").concat(n)),i=a}e.decryptdata.keyId=i}}return this.emeController.loadKey(e).then(function(){return{frag:e,keyInfo:{decryptdata:e.decryptdata}}})}return Promise.reject(fd(e,ie.KEY_LOAD_ERROR,new Error("emeEnabled with controller: ".concat(this.emeController&&this.config.emeEnabled,")"))))}},{key:"loadKeyHTTP",value:function(e){var t=this,r=e.decryptdata,i=r.uri;if(!i)return Promise.reject(fd(e,ie.KEY_LOAD_ERROR,new Error('Invalid key URI: "'.concat(i,'"'))));var n=this.keyLoaderInfo[i];if(n){if(n.decryptdata.key)return r.key=n.decryptdata.key,n.keyLoadPromise=null,Promise.resolve({frag:e,keyInfo:n});if(n.keyLoadPromise)return n.keyLoadPromise.then(function(t){return r.key=n.decryptdata.key,Ie(Ie({},t),{},{frag:e})})}this.log("Loading".concat(r.keyId?" keyId: "+ft(r.keyId):""," URI: ").concat(r.uri," from ").concat(e.type," ").concat(e.level));var a=this.config,s=new(0,a.loader)(a);e.keyLoader=s;var o=this.keyLoaderInfo[i]={decryptdata:r,keyLoadPromise:null,loader:s};return o.keyLoadPromise=new Promise(function(r,n){var l={type:ce.KEY,keyInfo:o,frag:e,responseType:"arraybuffer",url:i},u=a.keyLoadPolicy.default,c={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:function(e,i,a,s){var o=a.frag,l=a.keyInfo,u=a.url;if(!o.decryptdata||l!==t.keyLoaderInfo[u])return n(fd(o,ie.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),s));l.decryptdata.key=o.decryptdata.key=new Uint8Array(e.data),o.keyLoader=l.loader=l.keyLoadPromise=null,r({frag:o,keyInfo:l})},onError:function(r,a,s,o){t.resetLoader(a),n(fd(e,ie.KEY_LOAD_ERROR,new Error("HTTP Error ".concat(r.code," loading key ").concat(r.text)),s,Ie({url:i,data:void 0},r)))},onTimeout:function(r,i,a){t.resetLoader(i),n(fd(e,ie.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),a))},onAbort:function(r,i,a){t.resetLoader(i),n(fd(e,ie.INTERNAL_ABORTED,new Error("key loading aborted"),a))}};s.load(l,c,d)})}},{key:"resetLoader",value:function(e){var t=e.frag,r=e.keyInfo,i=e.url,n=r.loader;t.keyLoader===n&&(t.keyLoader=r.loader=r.keyLoadPromise=null),delete this.keyLoaderInfo[i],n&&n.destroy()}}])}(Be);function fd(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ie.KEY_LOAD_ERROR,r=arguments.length>2?arguments[2]:void 0,i=arguments.length>3?arguments[3]:void 0,n=arguments.length>4?arguments[4]:void 0;return new xi({type:re.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:r,networkDetails:i||null})}function vd(e){switch(e.type){case ce.AUDIO_TRACK:return de.AUDIO;case ce.SUBTITLE_TRACK:return de.SUBTITLE;default:return de.MAIN}}function gd(e,t){var r=e.url;return void 0!==r&&0!==r.indexOf("data:")||(r=t.url),r}var pd=function(){return l(function e(t){s(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(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ne.LEVEL_LOADING,this.onLevelLoading,this),e.on(ne.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(ne.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(ne.LEVELS_UPDATED,this.onLevelsUpdated,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ne.LEVEL_LOADING,this.onLevelLoading,this),e.off(ne.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(ne.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(ne.LEVELS_UPDATED,this.onLevelsUpdated,this)}},{key:"createInternalLoader",value:function(e){var t=this.hls.config,r=t.pLoader,i=t.loader,n=new(r||i)(t);return this.loaders[e.type]=n,n}},{key:"getInternalLoader",value:function(e){return this.loaders[e.type]}},{key:"resetInternalLoader",value:function(e){this.loaders[e]&&delete this.loaders[e]}},{key:"destroyInternalLoaders",value:function(){for(var e in this.loaders){var t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}},{key:"destroy",value:function(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}},{key:"onManifestLoading",value:function(e,t){var r=t.url;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:ce.MANIFEST,url:r,deliveryDirectives:null,levelOrTrack:null})}},{key:"onLevelLoading",value:function(e,t){var r=t.id,i=t.level,n=t.pathwayId,a=t.url,s=t.deliveryDirectives,o=t.levelInfo;this.load({id:r,level:i,pathwayId:n,responseType:"text",type:ce.LEVEL,url:a,deliveryDirectives:s,levelOrTrack:o})}},{key:"onAudioTrackLoading",value:function(e,t){var r=t.id,i=t.groupId,n=t.url,a=t.deliveryDirectives,s=t.track;this.load({id:r,groupId:i,level:null,responseType:"text",type:ce.AUDIO_TRACK,url:n,deliveryDirectives:a,levelOrTrack:s})}},{key:"onSubtitleTrackLoading",value:function(e,t){var r=t.id,i=t.groupId,n=t.url,a=t.deliveryDirectives,s=t.track;this.load({id:r,groupId:i,level:null,responseType:"text",type:ce.SUBTITLE_TRACK,url:n,deliveryDirectives:a,levelOrTrack:s})}},{key:"onLevelsUpdated",value:function(e,t){var r=this.loaders[ce.LEVEL];if(r){var i=r.context;i&&!t.levels.some(function(e){return e===i.levelOrTrack})&&(r.abort(),delete this.loaders[ce.LEVEL])}}},{key:"load",value:function(e){var t,r,i,n=this,a=this.hls.config,s=this.getInternalLoader(e);if(s){var o=this.hls.logger,l=s.context;if((null==l?void 0:l.levelOrTrack)===e.levelOrTrack&&(l.url===e.url||l.deliveryDirectives&&!e.deliveryDirectives))return void(l.url===e.url?o.log("[playlist-loader]: ignore ".concat(e.url," ongoing request")):o.log("[playlist-loader]: ignore ".concat(e.url," in favor of ").concat(l.url)));o.log("[playlist-loader]: aborting previous loader for type: ".concat(e.type)),s.abort()}if((r=e.type===ce.MANIFEST?a.manifestLoadPolicy.default:Ae({},a.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),Z(null==(t=e.deliveryDirectives)?void 0:t.part))&&(e.type===ce.LEVEL&&null!==e.level?i=this.hls.levels[e.level].details:e.type===ce.AUDIO_TRACK&&null!==e.id?i=this.hls.audioTracks[e.id].details:e.type===ce.SUBTITLE_TRACK&&null!==e.id&&(i=this.hls.subtitleTracks[e.id].details),i)){var u=i.partTarget,c=i.targetduration;if(u&&c){var d=1e3*Math.max(3*u,.8*c);r=Ae({},r,{maxTimeToFirstByteMs:Math.min(d,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(d,r.maxTimeToFirstByteMs)})}}var h=r.errorRetry||r.timeoutRetry||{},f={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:h.maxNumRetry||0,retryDelay:h.retryDelayMs||0,maxRetryDelay:h.maxRetryDelayMs||0},v={onSuccess:function(e,t,r,i){var a=n.getInternalLoader(r);n.resetInternalLoader(r.type);var s=e.data;t.parsing.start=performance.now(),Rn.isMediaPlaylist(s)||r.type!==ce.MANIFEST?n.handleTrackOrLevelPlaylist(e,t,r,i||null,a):n.handleMasterPlaylist(e,t,r,i)},onError:function(e,t,r,i){n.handleNetworkError(t,r,!1,e,i)},onTimeout:function(e,t,r){n.handleNetworkError(t,r,!0,void 0,e)}};s.load(e,f,v)}},{key:"checkAutostartLoad",value:function(){if(this.hls){var e=this.hls,t=e.config,r=t.autoStartLoad,i=t.startPosition,n=e.forceStartLoad;(r||n)&&(this.hls.logger.log("".concat(r?"auto":"force"," startLoad with configured startPosition ").concat(i)),this.hls.startLoad(i))}}},{key:"handleMasterPlaylist",value:function(e,t,r,i){var n=this,a=this.hls,s=e.data,o=gd(e,r),l=Rn.parseMasterPlaylist(s,o);if(l.playlistParsingError)return t.parsing.end=performance.now(),void this.handleManifestParsingError(e,r,l.playlistParsingError,i,t);var u=l.contentSteering,c=l.levels,d=l.iframeVariants,h=l.sessionData,f=l.sessionKeys,v=l.startTimeOffset,g=l.variableList;this.variableList=g,c.forEach(function(e){var t=e.unknownCodecs;if(t)for(var r=n.hls.config.preferManagedMediaSource,i=e.audioCodec,a=e.videoCodec,s=t.length;s--;){var o=t[s];or(o,"audio",r)?(e.audioCodec=i=i?"".concat(i,",").concat(o):o,ar.audio[i.substring(0,4)]=2,t.splice(s,1)):or(o,"video",r)&&(e.videoCodec=a=a?"".concat(a,",").concat(o):o,ar.video[a.substring(0,4)]=2,t.splice(s,1))}});var p=Rn.parseMasterPlaylistMedia(s,o,l),m=p.AUDIO,y=void 0===m?[]:m,k=p.SUBTITLES,E=p["CLOSED-CAPTIONS"];y.length&&(y.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"),y.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Wi({}),bitrate:0,url:""})));a.trigger(ne.MANIFEST_LOADED,{levels:c,audioTracks:y,subtitles:k,iframeVariants:d,captions:E,contentSteering:u,url:o,stats:t,networkDetails:i,sessionData:h,sessionKeys:f,startTimeOffset:v,variableList:g})}},{key:"handleTrackOrLevelPlaylist",value:function(e,t,r,i,n){var a=this.hls,s=r.id,o=r.level,l=r.type,u=gd(e,r),c=Z(o)?o:Z(s)?s:0,d=vd(r),h=Rn.parseLevelPlaylist(e.data,u,c,d,0,this.variableList);if(l===ce.MANIFEST){var f={attrs:new Wi({}),bitrate:0,details:h,name:"",url:u};h.requestScheduled=t.loading.start+jn(h,0),a.trigger(ne.MANIFEST_LOADED,{levels:[f],audioTracks:[],iframeVariants:[],url:u,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),r.levelDetails=h,this.handlePlaylistLoaded(h,e,t,r,i,n)}},{key:"handleManifestParsingError",value:function(e,t,r,i,n){this.hls.trigger(ne.ERROR,{type:re.NETWORK_ERROR,details:ie.MANIFEST_PARSING_ERROR,fatal:t.type===ce.MANIFEST,url:e.url,err:r,error:r,reason:r.message,response:e,context:t,networkDetails:i,stats:n})}},{key:"handleNetworkError",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=arguments.length>3?arguments[3]:void 0,n=arguments.length>4?arguments[4]:void 0,a="A network ".concat(r?"timeout":"error"+(i?" (status "+i.code+")":"")," occurred while loading ").concat(e.type);e.type===ce.LEVEL?a+=": ".concat(e.level," id: ").concat(e.id):e.type!==ce.AUDIO_TRACK&&e.type!==ce.SUBTITLE_TRACK||(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=ie.UNKNOWN,l=!1,u=this.getInternalLoader(e);switch(e.type){case ce.MANIFEST:o=r?ie.MANIFEST_LOAD_TIMEOUT:ie.MANIFEST_LOAD_ERROR,l=!0;break;case ce.LEVEL:o=r?ie.LEVEL_LOAD_TIMEOUT:ie.LEVEL_LOAD_ERROR,l=!1;break;case ce.AUDIO_TRACK:o=r?ie.AUDIO_TRACK_LOAD_TIMEOUT:ie.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case ce.SUBTITLE_TRACK:o=r?ie.SUBTITLE_TRACK_LOAD_TIMEOUT:ie.SUBTITLE_LOAD_ERROR,l=!1}u&&this.resetInternalLoader(e.type);var c={type:re.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:u,context:e,error:s,networkDetails:t,stats:n};if(i){var d=e.url;t&&"url"in t&&(d=t.url),c.response=Ie({url:d,data:void 0},i)}this.hls.trigger(ne.ERROR,c)}},{key:"handlePlaylistLoaded",value:function(e,t,r,i,n,a){var s=this.hls,o=i.type,l=i.level,u=i.levelOrTrack,c=i.id,d=i.groupId,h=i.deliveryDirectives,f=gd(t,i),v=vd(i),g="number"==typeof i.level&&v===de.MAIN?l:void 0;u&&"iframes"in u&&u.iframes&&!e.iframesOnly&&(e.playlistParsingError=new Error("EXT-X-I-FRAME-STREAM-INF media playlist MUST contain an EXT-X-I-FRAMES-ONLY tag"),e.iframesOnly=!0);var p=e.playlistParsingError;if(p){if(this.hls.logger.warn("".concat(p," ").concat(e.url)),!s.config.ignorePlaylistParsingErrors)return void s.trigger(ne.ERROR,{type:re.NETWORK_ERROR,details:ie.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:p,reason:p.message,response:t,context:i,level:g,parent:v,networkDetails:n,stats:r});e.playlistParsingError=null}if(e.fragments.length)switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),a.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case ce.MANIFEST:case ce.LEVEL:if(g)if(u){if(u!==s.levels[g]){var m=s.levels.indexOf(u);m>-1&&(g=m)}}else g=0;s.trigger(ne.LEVEL_LOADED,{details:e,levelInfo:u||s.levels[0],level:g||0,id:c||0,stats:r,networkDetails:n,deliveryDirectives:h,withoutMultiVariant:o===ce.MANIFEST,context:i});break;case ce.AUDIO_TRACK:s.trigger(ne.AUDIO_TRACK_LOADED,{details:e,track:u,id:c||0,groupId:d||"",stats:r,networkDetails:n,deliveryDirectives:h,context:i});break;case ce.SUBTITLE_TRACK:s.trigger(ne.SUBTITLE_TRACK_LOADED,{details:e,track:u,id:c||0,groupId:d||"",stats:r,networkDetails:n,deliveryDirectives:h,context:i})}else{var y=e.playlistParsingError=new Error("No Segments found in Playlist");s.trigger(ne.ERROR,{type:re.NETWORK_ERROR,details:ie.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:y,reason:y.message,response:t,context:i,level:g,parent:v,networkDetails:n,stats:r})}}}])}(),md=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};s(this,e),this.config=void 0,this.userConfig=void 0,this.logger=void 0,this._url=null,this.streamController=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Aa,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.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.iframeController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;var r=this.logger=function(e,t,r){var i=Ge();if("object"===("undefined"==typeof console?"undefined":R(console))&&!0===e||"object"===R(e)){var n=["debug","log","info","warn","error"];n.forEach(function(t){i[t]=He(t,e,r)});try{i.log('Debug logs enabled for "'.concat(t,'" in hls.js version ',"1.7.3"))}catch(e){return Ge()}n.forEach(function(t){Ke[t]=He(t,e)})}else Ae(Ke,i);return i}(t.debug||!1,"Hls instance",t.loggerId||t.assetPlayerId),i=this.config=nd(e.DefaultConfig,t,r);this.userConfig=t,i.progressive&&sd(i,r);var n=i.streamController,a=i.abrController,o=i.bufferController,l=i.capLevelController,u=i.errorController,c=i.fpsController,d=i.id3TrackController,h=i.iframeController,f=i.gapController,v=new u(this),g=this.abrController=new a(this),p=new ki(this),m=i.interstitialsController,y=m?this.interstitialsController=new m(this,e):null,k=o?this.bufferController=new o(this,p):null,E=l?this.capLevelController=new l(this):null,S=c?new c(this):null,T=i.cmcdController,A=T?this.cmcdController=new T(this):null,b=new pd(this),I=i.contentSteeringController,L=I?new I(this):null,P=this.levelController=new od(this,L),w=d?new d(this):void 0,C=new hd(this.config,this.logger),D=this.streamController=new n(this,p,C),_=this.gapController=f?new f(this,p):void 0;E&&E.setStreamController(D);var M=[b,P,D];y&&M.splice(1,0,y),L&&M.splice(1,0,L),this.networkControllers=M;var x=[g];k&&x.push(k),_&&x.push(_),E&&x.push(E),S&&(S.setStreamController(D),x.push(S)),w&&x.push(w),x.push(p),this.audioTrackController=this.createController(i.audioTrackController,M);var O=i.audioStreamController;O&&M.push(this.audioStreamController=new O(this,p,C)),this.subtitleTrackController=this.createController(i.subtitleTrackController,M);var F=i.subtitleStreamController;F&&M.push(this.subtititleStreamController=new F(this,p,C)),this.createController(i.timelineController,x),C.emeController=this.emeController=this.createController(i.emeController,x),A&&x.push(A),this.latencyController=this.createController(i.latencyController,x),this.coreComponents=x,this.iframeController=h?new h(this,e):void 0,M.push(v);var N=v.onErrorOut;"function"==typeof N&&this.on(ne.ERROR,N,v),this.on(ne.MANIFEST_LOADED,b.onManifestLoaded,b)}return l(e,[{key:"createController",value:function(e,t){if(e){var r=new e(this);return t&&t.push(r),r}return null}},{key:"on",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this;this._emitter.on(e,t,r)}},{key:"once",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this;this._emitter.once(e,t,r)}},{key:"removeAllListeners",value:function(e){this._emitter.removeAllListeners(e)}},{key:"off",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this,i=arguments.length>3?arguments[3]:void 0;this._emitter.off(e,t,r,i)}},{key:"listeners",value:function(e){return this._emitter.listeners(e)}},{key:"emit",value:function(e,t,r){return this._emitter.emit(e,t,r)}},{key:"trigger",value:function(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),!this.triggeringException){this.triggeringException=!0;var r=e===ne.ERROR;this.trigger(ne.ERROR,{type:re.OTHER_ERROR,details:ie.INTERNAL_EXCEPTION,fatal:r,event:e,error:t}),this.triggeringException=!1}}return!1}},{key:"listenerCount",value:function(e){return this._emitter.listenerCount(e)}},{key:"destroy",value:function(){this.logger.log("destroy"),this.trigger(ne.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,this.iframeController=void 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(ne.ERROR,{type:re.OTHER_ERROR,details:ie.ATTACH_MEDIA_ERROR,fatal:!0,error:t})}else{this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());var r="media"in e,i=r?e.media:e,n=r?e:{media:i};this._media=i,this.trigger(ne.MEDIA_ATTACHING,n)}}},{key:"detachMedia",value:function(){this.logger.log("detachMedia");var e={};this.trigger(ne.MEDIA_DETACHING,e),this._media=null,this.trigger(ne.MEDIA_DETACHED,e)}},{key:"transferMedia",value:function(){var e;this._media=null;var t=(null==(e=this.bufferController)?void 0:e.transferMedia())||null,r={transferMedia:t};return this.trigger(ne.MEDIA_DETACHING,r),this.trigger(ne.MEDIA_DETACHED,r),t}},{key:"loadSource",value:function(e){var t;this.stopLoad();var r=this.media,i=this._url,n=this._url=le.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log("loadSource:".concat(n)),r&&i&&(i!==n||null!=(t=this.bufferController)&&t.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(r)),this.trigger(ne.MANIFEST_LOADING,{url:e})}},{key:"url",get:function(){return this._url}},{key:"hasEnoughToStart",get:function(){return this.streamController.hasEnoughToStart}},{key:"startPosition",get:function(){return this.streamController.startPositionValue}},{key:"startLoad",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:-1,t=arguments.length>1?arguments[1]:void 0;this.logger.log("startLoad(".concat(e+(t?", <skip seek to start>":""),")")),this.started=!0,this.resumeBuffering();for(var r=0;r<this.networkControllers.length&&(this.networkControllers[r].startLoad(e,t),this.started&&this.networkControllers);r++);}},{key:"stopLoad",value:function(){this.logger.log("stopLoad"),this.started=!1;for(var e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!this.started&&this.networkControllers);e++);}},{key:"loadingEnabled",get:function(){return this.started&&this.streamController.state!==na}},{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=c({},de.MAIN,this.streamController.inFlightFrag);return this.audioStreamController&&(e[de.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[de.SUBTITLE]=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=this.started,r=null==e?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&(r?this.startLoad(r):this.config.autoStartLoad||this.startLoad()))}},{key:"removeLevel",value:function(e){this.levelController.removeLevel(e)}},{key:"sessionId",get:function(){var e=this._sessionId;return e||(e=this._sessionId=Je()),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=this.capLevelController,r=!!e;t&&r!==this.config.capLevelToPlayerSize&&(r?t.startCapping():(t.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=r)}},{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 Lr.indexOf(e)>-1})(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}},{key:"autoLevelEnabled",get:function(){return-1===this.levelController.manualLevel}},{key:"manualLevel",get:function(){return this.levelController.manualLevel}},{key:"minAutoLevel",get:function(){var e=this.levels,t=this.config.minAutoBitrate;if(!e)return 0;for(var r=e.length,i=0;i<r;i++)if(e[i].maxBitrate>=t)return i;return 0}},{key:"maxAutoLevel",get:function(){var e,t=this.levels,r=this.autoLevelCapping,i=this.maxHdcpLevel;if(e=-1===r&&null!=t&&t.length?t.length-1:r,i)for(var n=e;n--;){var a=t[n].attrs["HDCP-LEVEL"];if(a&&a<=i)return n}return e}},{key:"firstAutoLevel",get:function(){return this.abrController.firstAutoLevel}},{key:"nextAutoLevel",get:function(){return this.abrController.nextAutoLevel},set:function(e){this.abrController.nextAutoLevel=e}},{key:"playingDate",get:function(){return this.streamController.currentProgramDateTime}},{key:"mainForwardBufferInfo",get:function(){return this.streamController.getMainFwdBufferInfo()}},{key:"audioForwardBufferInfo",get:function(){var e;return(null==(e=this.audioStreamController)?void 0:e.getFwdBufferInfo())||null}},{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:"nextAudioTrack",get:function(){var e,t;return null!=(e=null==(t=this.audioStreamController)?void 0:t.nextAudioTrack)?e:-1},set:function(e){var t=this.audioTrackController;t&&(t.nextAudioTrack=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(){var e,t;return null!=(e=null==(t=this.latencyController)?void 0:t.liveSyncPosition)?e:null}},{key:"latency",get:function(){var e;return(null==(e=this.latencyController)?void 0:e.latency)||0}},{key:"maxLatency",get:function(){var e;return(null==(e=this.latencyController)?void 0:e.maxLatency)||0}},{key:"targetLatency",get:function(){var e;return(null==(e=this.latencyController)?void 0:e.targetLatency)||null},set:function(e){this.latencyController&&(this.latencyController.targetLatency=e)}},{key:"drift",get:function(){var e;return(null==(e=this.latencyController)?void 0:e.drift)||null}},{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(){return this.interstitialsController?this.interstitialsController.interstitialsManager:null}},{key:"iframeVariants",get:function(){var e=this.levelController.iframeVariants;return e||[]}},{key:"createIFramePlayer",value:function(e){return this._url&&this.iframeController?this.iframeController.createIFramePlayer(e):null}},{key:"createImageIFramePlayer",value:function(e){return this._url&&this.iframeController?this.iframeController.createImageIFramePlayer(e):null}},{key:"getMediaDecodingInfo",value:function(e){return Ar(e,Ur(arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.allAudioTracks),navigator.mediaCapabilities)}}],[{key:"version",get:function(){return ba}},{key:"isMSESupported",value:function(){return zu()}},{key:"isSupported",value:function(){return function(){if(!zu())return!1;var e=qe();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(ur(t,"video"))})||["mp4a.40.2","fLaC"].some(function(t){return e.isTypeSupported(ur(t,"audio"))}))}()}},{key:"getMediaSource",value:function(){return qe()}},{key:"Events",get:function(){return ne}},{key:"MetadataSchema",get:function(){return xa}},{key:"ErrorTypes",get:function(){return re}},{key:"ErrorDetails",get:function(){return ie}},{key:"DefaultConfig",get:function(){return e.defaultConfig?e.defaultConfig:id},set:function(t){e.defaultConfig=t}}])}();function yd(){var e,t,r,i=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=function(e){var t=e.match(/Chrome\/(\d+)/);return t&&t[1]?parseInt(t[1],10):0}(i),h=function(e){var t=e.match(/AppleWebKit\/(\d+)/);return t&&t[1]?parseInt(t[1],10):0}(i);if(r=d>0?d:void 0,/Web0S|webOS|LG Browser|LGSTB/i.test(i)){if(a="LG WebOS",l=!0,(f=i.match(/Web0S[/\s]*([\d.]+)/i)||i.match(/webOS[/\s]*([\d.]+)/i))&&f[1]||(f=i.match(/webOSTV[/\s-]*([\d.]+)/i)||i.match(/webOS\.TV[/\s-]*([\d.]+)/i)),f&&f[1])e=o=(v=(s=f[1]).split("."))[0]?parseInt(v[0],10):0;else d>0?d>=79?(e=6,s="6.0",o=6):d>=68?(e=5,s="5.0",o=5):d>=53?(e=4,s="4.0",o=4):d>=38?(e=3,s="3.0",o=3):(e=2,s="2.0",o=2):(s="Unknown",e=void 0);u=void 0!==e&&e<3}else if(/Tizen/i.test(i)){var f,v;if(a="Samsung Tizen",l=!0,"Unknown"!==(s=(f=i.match(/Tizen[/\s]*([\d.]+)/i))&&f[1]?f[1]:"Unknown"))t=o=(v=s.split("."))[0]?parseInt(v[0],10):0;u=void 0!==t&&t<3}else/SMART-TV|SmartTV/i.test(i)?(a="Smart TV",l=!0,u=d>0&&d<53):/NetCast/i.test(i)?(a="LG NetCast",l=!0,u=!0):/BRAVIA/i.test(i)?(a="Sony BRAVIA",l=!0,u=d>0&&d<53):(d>0&&(a="Chrome",s=d.toString(),o=d,d<50&&(c=!1)),h>0&&h<600&&(c=!1));return"undefined"!=typeof Promise&&"undefined"!=typeof Map&&"undefined"!=typeof Set||(c=!1),"undefined"==typeof URLSearchParams&&(c=!1),{name:a,version:s,majorVersion:o,isSmartTV:l,isLegacyTV:u,platform:n,supportsModernJS:c,webOSVersion:e,tizenVersion:t,chromeVersion:r}}function kd(){var e,t=yd();return"Samsung Tizen"===t.name&&(null!==(e=t.tizenVersion)&&void 0!==e?e:0)>=5}function Ed(){var e={};return yd().isSmartTV&&(e.allowNativeHls=!0,e.pauseContentDuringAds=!0),e}function Sd(e){if(void 0===e&&(e=!1),e){var t=yd();console.log("[StormcloudVideoPlayer] Browser Compatibility Info:",_(_(_(_({browser:"".concat(t.name," ").concat(t.version),platform:t.platform,isSmartTV:t.isSmartTV,isLegacyTV:t.isLegacyTV,supportsModernJS:t.supportsModernJS},void 0!==t.webOSVersion?{webOSVersion:t.webOSVersion}:{}),void 0!==t.tizenVersion?{tizenVersion:t.tizenVersion}:{}),void 0!==t.chromeVersion?{chromeVersion:t.chromeVersion}:{}),{userAgent:navigator.userAgent}))}}md.defaultConfig=void 0;var Td=/\[([A-Z][A-Z0-9_]*)\]/g,Ad=/\[CACHEBUSTER\]|\[cachebuster\]|\[timestamp\]|\[random\]|\[INSERT_RANDOM_NUMBER\]|%%CACHEBUSTER%%|%%CACHEBUST%%|\$\{CACHEBUSTER\}|\$\{CACHEBUSTING\}|\{cachebuster\}|\{random\}/g,bd=new Set(["ADCATEGORIES","ADCOUNT","ADPLAYHEAD","ADSERVINGID","ADTYPE","APIFRAMEWORKS","APPBUNDLE","ASSETURI","BLOCKEDADCATEGORIES","BREAKMAXADLENGTH","BREAKMAXADS","BREAKMAXDURATION","BREAKMINADLENGTH","BREAKPOSITION","CACHEBUSTING","CLICKPOS","CLICKTYPE","CLIENTUA","CONTENTID","CONTENTPLAYHEAD","CONTENTURI","DEVICEIP","DEVICEUA","DOMAIN","ERRORCODE","EXTENSIONS","GDPRCONSENT","IFA","IFATYPE","INVENTORYSTATE","LATLONG","LIMITADTRACKING","MEDIAMIME","MEDIAPLAYHEAD","OMIDPARTNER","PAGEURL","PLACEMENTTYPE","PLAYERCAPABILITIES","PLAYERSIZE","PLAYERSTATE","PODSEQUENCE","REASON","REGULATIONS","SERVERSIDE","SERVERUA","TIMESTAMP","TRANSACTIONID","UNIVERSALADID","VASTVERSIONS","VERIFICATIONVENDORS"]);function Id(){return String(Math.floor(9e7*Math.random())+1e7)}function Rd(e){if(null!=e&&Number.isFinite(e)&&!(e<0)){var t=Math.floor(e),r=String(Math.floor(t/3600)).padStart(2,"0"),i=String(Math.floor(t%3600/60)).padStart(2,"0"),n=String(t%60).padStart(2,"0"),a=String(Math.floor(1e3*(e-t))).padStart(3,"0");return"".concat(r,":").concat(i,":").concat(n,".").concat(a)}}function Ld(e,t){if(void 0===t&&(t={}),!e)return e;var r=function(e){var t=new Map,r=function(e,r){null!=r&&""!==r&&t.set(e,r)},i=Rd(e.adPlayheadSeconds);if(r("ADPLAYHEAD",i),r("MEDIAPLAYHEAD",i),r("CONTENTPLAYHEAD",Rd(e.contentPlayheadSeconds)),r("ASSETURI",e.assetUri),r("MEDIAMIME",e.mediaMime),r("TIMESTAMP",(new Date).toISOString()),r("SERVERSIDE","0"),null!=e.errorCode&&""!==e.errorCode&&r("ERRORCODE",String(e.errorCode)),null!=e.playerWidth&&null!=e.playerHeight&&r("PLAYERSIZE","".concat(Math.round(e.playerWidth),",").concat(Math.round(e.playerHeight))),r("IFA",e.deviceId),r("IFATYPE",e.deviceIdType),null!=e.limitAdTracking&&r("LIMITADTRACKING",e.limitAdTracking?"1":"0"),r("PAGEURL",e.pageUrl),e.pageUrl)try{r("DOMAIN",new URL(e.pageUrl).hostname)}catch(e){}return r("CLIENTUA",e.clientUa),r("DEVICEUA",e.clientUa),null!=e.podSequence&&r("PODSEQUENCE",String(e.podSequence)),r("ADSERVINGID",e.adServingId),null!=e.reason&&""!==e.reason&&r("REASON",String(e.reason)),t}(t);return e.replace(Ad,function(){return Id()}).replace(Td,function(e,t){if("CACHEBUSTING"===t)return Id();var i=r.get(t);return null!=i?encodeURIComponent(i):bd.has(t)?"":e})}var Pd=["creativeView","loaded","start","firstQuartile","midpoint","thirdQuartile","complete","mute","unmute","pause","resume","fullscreen","exitFullscreen","playerExpand","playerCollapse","notUsed"];function wd(e){var t,r=null===(t=null==e?void 0:e.textContent)||void 0===t?void 0:t.trim();return r||void 0}function Cd(e){if(e){var t=e.trim().split(":");if(3===t.length){var r=N(t.map(function(e){return parseFloat(e)}),3),i=r[0],n=r[1],a=r[2];if([i,n,a].every(function(e){return void 0!==e&&Number.isFinite(e)}))return 3600*i+60*n+a}}}var Dd=new Set,_d=405;function Md(e,t){var r,i,n,a,s,o,l,u,c=!1,d=!1,h=Math.max(0,Math.min(1,e.volume||1)),f=new Map,v=null==t?void 0:t.mainHlsInstance,g="__stormcloudAdContainer",p="__stormcloudAdVideo",m="__stormcloudFrameCounterReliable",y="__stormcloudRvfcReliable",k=null!==(r=e[p])&&void 0!==r?r:void 0,E=null!==(i=e[g])&&void 0!==i?i:void 0,S=[],T=[],A=[],b=0,I=new Map,R=new Map,L=[],P=0,w=0,C=!1;function D(){return{impression:!1,loaded:!1,start:!1,firstQuartile:!1,midpoint:!1,thirdQuartile:!1,complete:!1,viewabilitySettled:!1,lastMuted:void 0,progressFired:new Set}}var M,N,B=D(),U=new Set,V=0,G=0,H=!1,K=[];function j(e,t){var r,i,n=f.get(e);if(n)try{for(var a=F(Array.from(n)),s=a.next();!s.done;s=a.next()){var o=s.value;try{o(t)}catch(t){console.warn("[HlsAdPlayer] Error in event listener for ".concat(e,":"),t)}}}catch(e){r={error:e}}finally{try{s&&!s.done&&(i=a.return)&&i.call(a)}finally{if(r)throw r.error}}}function q(t,r){if(t&&0!==t.length){var i=function(t){var r;void 0===t&&(t={});var i=t.errorCode,n=t.reason,o=null!==(r=t.ad)&&void 0!==r?r:a,l={adPlayheadSeconds:null==k?void 0:k.currentTime,contentPlayheadSeconds:e.currentTime,assetUri:null==s?void 0:s.url,mediaMime:null==s?void 0:s.type,playerWidth:(null==k?void 0:k.clientWidth)||(null==E?void 0:E.clientWidth),playerHeight:(null==k?void 0:k.clientHeight)||(null==E?void 0:E.clientHeight)};return null!=i&&(l.errorCode=i),"undefined"!=typeof navigator&&navigator.userAgent&&(l.clientUa=navigator.userAgent),"undefined"!=typeof location&&location.href&&(l.pageUrl=location.href),A.length>0&&(l.podSequence=b+1),(null==o?void 0:o.adServingId)&&(l.adServingId=o.adServingId),null!=n&&(l.reason=n),l}(r);t.forEach(function(e){try{var t,r=Ld(e,i),n=new Image(1,1);Dd.add(n);var a=function(){void 0!==t&&clearTimeout(t),n.onload=null,n.onerror=null,Dd.delete(n)};n.onload=a,n.onerror=a,t=setTimeout(a,3e4),n.src=r,console.log("[HlsAdPlayer] Fired tracking pixel: ".concat(r))}catch(e){console.warn("[HlsAdPlayer] Error firing tracking pixel:",e)}})}}function W(e){if(0===e.length)throw new Error("No media files available");var t=e[0];if(!t)throw new Error("No media files available");if(1===e.length)return t;var r=function(){if(!v||!v.levels)return null;var e=v.currentLevel;if(-1===e||!v.levels[e]){var t=v.loadLevel;if(-1!==t&&v.levels[t]){var r=v.levels[t];return{width:r.width||1920,height:r.height||1080,bitrate:r.bitrate||5e6}}return null}var i=v.levels[e];return{width:i.width||1920,height:i.height||1080,bitrate:i.bitrate||5e6}}();if(!r)return console.log("[HlsAdPlayer] No main stream quality info, using first media file"),t;console.log("[HlsAdPlayer] Main stream quality:",r);var i=e.map(function(e){var t=Math.abs(e.width-r.width)+Math.abs(e.height-r.height),i=1e3*(e.bitrate||5e3),n=Math.abs(i-r.bitrate);return{file:e,score:2*t+n/1e3,resolutionDiff:t,bitrateDiff:n}});i.sort(function(e,t){return e.score-t.score});var n=i[0];return n?(console.log("[HlsAdPlayer] Selected media file:",{url:n.file.url,resolution:"".concat(n.file.width,"x").concat(n.file.height),bitrate:n.file.bitrate,score:n.score,resolutionDiff:n.resolutionDiff,bitrateDiff:n.bitrateDiff}),n.file):(console.log("[HlsAdPlayer] No best match found, using first media file"),t)}function Y(e){var t=e.type.toLowerCase(),r=e.url.toLowerCase();return"application/x-mpegurl"===t||"application/vnd.apple.mpegurl"===t||t.includes("mpegurl")||r.includes(".m3u8")}function z(e){var t=e.type.toLowerCase(),r=e.url.toLowerCase();return t.startsWith("video/")||r.endsWith(".mp4")||r.includes(".mp4?")}function X(e,t){var r=e.querySelectorAll(":scope > MediaFiles > MediaFile"),i=[];return t&&console.log("[HlsAdPlayer] Found ".concat(r.length," MediaFile element(s) in VAST XML")),r.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(t&&console.log("[HlsAdPlayer] MediaFile ".concat(r,': type="').concat(a,'", url="').concat(s,'", width="').concat(o,'", height="').concat(l,'"')),s)if("VPAID"!==(e.getAttribute("apiFramework")||"").toUpperCase()){var u=e.getAttribute("bitrate"),c=u?parseInt(u,10):void 0,d={url:s,type:a,width:parseInt(o||"1920",10),height:parseInt(l||"1080",10),bitrate:c&&c>0?c:void 0};if(function(e){var t=e.type.toLowerCase(),r=(e.url.toLowerCase().split("?")[0]||"").trim();return t.startsWith("audio/")||r.endsWith(".mp3")||r.endsWith(".aac")||r.endsWith(".m4a")||r.endsWith(".ogg")||r.endsWith(".oga")||r.endsWith(".opus")||r.endsWith(".wav")||r.endsWith(".weba")}(d))console.warn("[HlsAdPlayer] MediaFile ".concat(r,' skipped (audio-only, type="').concat(a,'") — audio ads are not played to avoid a black screen'));else{var h=null!=e.getAttribute("width")&&null!=e.getAttribute("height");!Y(d)&&h&&(d.width<=1||d.height<=1)?console.warn("[HlsAdPlayer] MediaFile ".concat(r," skipped (degenerate dimensions ").concat(d.width,"x").concat(d.height,', type="').concat(a,'") — likely an audio-only placeholder rendition')):Y(d)||z(d)?(i.push(d),t&&console.log("[HlsAdPlayer] Added ".concat(Y(d)?"HLS":"progressive"," MediaFile: ").concat(s))):t&&console.log("[HlsAdPlayer] MediaFile ".concat(r,' ignored (type="').concat(a,'" is not supported)'))}}else t&&console.log("[HlsAdPlayer] MediaFile ".concat(r," ignored (VPAID creatives are not supported)"));else t&&console.warn("[HlsAdPlayer] MediaFile ".concat(r," has empty URL"))}),i}function Q(){var e,t,r={impression:[],clickTracking:[],error:[],viewable:[],notViewable:[],viewUndetermined:[],verificationNotExecuted:[],progress:[]};try{for(var i=F(Pd),n=i.next();!n.done;n=i.next()){r[n.value]=[]}}catch(t){e={error:t}}finally{try{n&&!n.done&&(t=i.return)&&t.call(i)}finally{if(e)throw e.error}}return r}function $(e,t){t.forEach(function(t){var r=wd(t);r&&e.push(r)})}function J(e,t){e.querySelectorAll(":scope > TrackingEvents > Tracking").forEach(function(e){var r=e.getAttribute("event"),i=wd(e);if(r&&i)if("progress"!==r)-1!==Pd.indexOf(r)&&t[r].push(i);else{var n=function(e){if(e){var t=e.trim();if(t.endsWith("%")){var r=parseFloat(t);return Number.isFinite(r)?{offsetPercent:r}:void 0}var i=Cd(t);return void 0!==i?{offsetSeconds:i}:void 0}}(e.getAttribute("offset"));n&&t.progress.push(_({url:i},n))}}),$(t.clickTracking,e.querySelectorAll(":scope > VideoClicks > ClickTracking"))}function Z(e,t){$(t.impression,e.querySelectorAll(":scope > Impression")),$(t.error,e.querySelectorAll(":scope > Error")),$(t.viewable,e.querySelectorAll(":scope > ViewableImpression > Viewable")),$(t.notViewable,e.querySelectorAll(":scope > ViewableImpression > NotViewable")),$(t.viewUndetermined,e.querySelectorAll(":scope > ViewableImpression > ViewUndetermined")),e.querySelectorAll(':scope > AdVerifications > Verification, :scope > Extensions > Extension[type="AdVerifications"] > AdVerifications > Verification').forEach(function(e){$(t.verificationNotExecuted,e.querySelectorAll(':scope > TrackingEvents > Tracking[event="verificationNotExecuted"]'))})}function ee(e,t){var r,i,n=e,a=t;try{for(var s=F(Object.keys(n)),o=s.next();!o.done;o=s.next()){var l=o.value,u=a[l];u&&u.length>0&&(n[l]=n[l].concat(u))}}catch(e){r={error:e}}finally{try{o&&!o.done&&(i=s.return)&&i.call(s)}finally{if(r)throw r.error}}return e}function te(e){var t=(new DOMParser).parseFromString(e,"text/xml"),r=t.querySelector("parsererror");return r?(console.error("[HlsAdPlayer] XML parsing error (malformed VAST XML):",r.textContent),null):t}function re(e){var t=parseInt(e.getAttribute("sequence")||"",10);return Number.isFinite(t)?t:void 0}function ie(e){var t=[];return $(t,e.querySelectorAll(":scope > Error")),{type:"empty",errorUrls:t,errorCode:303}}function ne(e,t){var r,i,n;void 0===t&&(t=!1);try{var a=e.querySelector(":scope > Wrapper");if(a){var s=wd(a.querySelector(":scope > VASTAdTagURI"));if(!s)return console.warn("[HlsAdPlayer] <Wrapper> has no VASTAdTagURI"),{type:"empty"};var o=Q();return Z(a,o),a.querySelectorAll(":scope > Creatives > Creative > Linear").forEach(function(e){return J(e,o)}),{type:"wrapper",vastAdTagUri:s,trackingUrls:o,rules:{followAdditionalWrappers:"false"!==a.getAttribute("followAdditionalWrappers")}}}var l=e.querySelector(":scope > InLine");if(!l)return console.warn("[HlsAdPlayer] <Ad> has neither <InLine> nor <Wrapper>"),{type:"empty"};var u=[];if($(u,l.querySelectorAll(":scope > Error")),"true"===e.getAttribute("conditionalAd"))return console.warn("[HlsAdPlayer] Skipping conditional <Ad> (VPAID-only)"),{type:"empty",errorUrls:u,errorCode:403};var c=void 0,d=[];try{for(var h=F(Array.from(l.querySelectorAll(":scope > Creatives > Creative > Linear"))),f=h.next();!f.done;f=h.next()){var v=f.value,g=X(v,t);if(g.length>0){c=v,d=g;break}}}catch(e){r={error:e}}finally{try{f&&!f.done&&(i=h.return)&&i.call(h)}finally{if(r)throw r.error}}if(!c)return console.warn("[HlsAdPlayer] No supported linear media files in <Ad>"),{type:"empty",errorUrls:u,errorCode:403};var p=Q();return Z(l,p),J(c,p),{type:"inline",ad:{id:e.getAttribute("id")||"unknown",title:wd(l.querySelector(":scope > AdTitle"))||"Ad",duration:null!==(n=Cd(wd(c.querySelector(":scope > Duration"))))&&void 0!==n?n:30,mediaFiles:d,trackingUrls:p,clickThrough:wd(c.querySelector(":scope > VideoClicks > ClickThrough")),adServingId:wd(l.querySelector(":scope > AdServingId"))}}}catch(e){return console.error("[HlsAdPlayer] Error parsing <Ad> element:",e),{type:"empty"}}}function ae(e){return x(this,arguments,void 0,function(e,t){var r,i,n;return void 0===t&&(t="include"),O(this,function(a){switch(a.label){case 0:r=function(t){return fetch(e,{mode:"cors",credentials:t,headers:{Accept:"application/xml, text/xml, */*"},referrerPolicy:"no-referrer-when-downgrade"})},a.label=1;case 1:return a.trys.push([1,3,,7]),[4,r(t)];case 2:return i=a.sent(),[3,7];case 3:return n=a.sent(),"omit"===t?[3,5]:(console.warn('[HlsAdPlayer] VAST fetch failed with credentials="'.concat(t,'", retrying without credentials:'),n),[4,r("omit")]);case 4:return i=a.sent(),[3,6];case 5:throw n;case 6:return[3,7];case 7:if(!i.ok)throw new Error("Failed to fetch VAST: ".concat(i.statusText));return[2,i.text()]}})})}function se(e){return x(this,arguments,void 0,function(e,t,r,i){var n,a,s,o,l;return void 0===t&&(t=0),void 0===r&&(r=Q()),void 0===i&&(i={followAdditionalWrappers:!0}),O(this,function(u){switch(u.label){case 0:return u.trys.push([0,2,,3]),[4,ae(e,0===t?"include":"omit")];case 1:return n=u.sent(),[3,3];case 2:if(a=u.sent(),0===t)throw a;return console.warn("[HlsAdPlayer] Wrapped VAST request failed:",a),q(r.error,{errorCode:301}),[2,null];case 3:return console.log("[HlsAdPlayer] VAST XML received"),console.log("[HlsAdPlayer] VAST XML content (first 2000 chars):",n.substring(0,2e3)),s=function(e){var t,r;try{var i=te(e);if(!i)return{type:"empty"};var n=i.documentElement,a=Array.from(n.querySelectorAll(":scope > Ad")),s=null!==(t=a.find(function(e){return void 0===re(e)}))&&void 0!==t?t:a[0];if(!s)return console.warn("[HlsAdPlayer] No Ad element found in VAST ".concat(null!==(r=n.getAttribute("version"))&&void 0!==r?r:""," response")),ie(n);var o=ne(s,!0);return"wrapper"===o.type&&console.log("[HlsAdPlayer] VAST wrapper detected, following VASTAdTagURI: ".concat(o.vastAdTagUri)),o}catch(e){return console.error("[HlsAdPlayer] Error parsing VAST XML:",e),{type:"empty"}}}(n),"empty"===s.type?(q((null!==(o=s.errorUrls)&&void 0!==o?o:[]).concat(r.error),{errorCode:null!==(l=s.errorCode)&&void 0!==l?l:303}),[2,null]):"wrapper"===s.type?t>=5||!i.followAdditionalWrappers?(console.warn(i.followAdditionalWrappers?"[HlsAdPlayer] VAST wrapper depth limit (".concat(5,") reached, aborting redirect chain"):'[HlsAdPlayer] Parent wrapper set followAdditionalWrappers="false"; rejecting nested wrapper'),q(r.error.concat(s.trackingUrls.error),{errorCode:302}),[2,null]):(ee(r,s.trackingUrls),[2,se(s.vastAdTagUri,t+1,r,s.rules)]):(ee(s.ad.trackingUrls,r),[2,s.ad])}})})}function oe(e){return x(this,void 0,void 0,function(){var t,r,i,n,a,s,o,l,u,c,d,h,f,v,g,p,m,y,k,E,S,T,A,b,I,R=this;return O(this,function(L){switch(L.label){case 0:return[4,ae(e)];case 1:if(t=L.sent(),console.log("[HlsAdPlayer] Pod VAST XML received (length=".concat(t.length,")")),0===t.trim().length)return console.warn("[HlsAdPlayer] Pod VAST response body is empty (no fill)"),[2,[]];if(!(r=te(t)))return console.error("[HlsAdPlayer] Pod VAST XML content (first 2000 chars):",t.substring(0,2e3)),[2,[]];if(i=r.documentElement,0===(n=Array.from(i.querySelectorAll(":scope > Ad"))).length)return console.warn("[HlsAdPlayer] No <Ad> elements in VAST ".concat(null!==(T=i.getAttribute("version"))&&void 0!==T?T:""," pod response (no fill)")),"empty"===(a=ie(i)).type&&(null===(A=a.errorUrls)||void 0===A?void 0:A.length)&&q(a.errorUrls,{errorCode:null!==(b=a.errorCode)&&void 0!==b?b:303}),[2,[]];if(s=function(e){return x(R,void 0,void 0,function(){var t,r,i;return O(this,function(n){return"inline"===(t=ne(e)).type?[2,t.ad]:"wrapper"===t.type?[2,se(t.vastAdTagUri,1,t.trackingUrls,t.rules)]:((null===(r=t.errorUrls)||void 0===r?void 0:r.length)&&q(t.errorUrls,{errorCode:null!==(i=t.errorCode)&&void 0!==i?i:403}),[2,null])})})},o=n.filter(function(e){return void 0!==re(e)}).sort(function(e,t){return re(e)-re(t)}),l=n.filter(function(e){return void 0===re(e)}),u=[],0!==o.length)return[3,10];L.label=2;case 2:L.trys.push([2,7,8,9]),c=F(l),d=c.next(),L.label=3;case 3:return d.done?[3,6]:(g=d.value,[4,s(g)]);case 4:(p=L.sent())&&u.push(p),L.label=5;case 5:return d=c.next(),[3,3];case 6:return[3,9];case 7:return h=L.sent(),y={error:h},[3,9];case 8:try{d&&!d.done&&(k=c.return)&&k.call(c)}finally{if(y)throw y.error}return[7];case 9:return[3,20];case 10:L.trys.push([10,18,19,20]),f=F(o),v=f.next(),L.label=11;case 11:return v.done?[3,17]:(g=v.value,[4,s(g)]);case 12:p=L.sent(),L.label=13;case 13:return!p&&l.length>0?[4,s(l.shift())]:[3,15];case 14:return p=L.sent(),[3,13];case 15:p&&u.push(p),L.label=16;case 16:return v=f.next(),[3,11];case 17:return[3,20];case 18:return m=L.sent(),E={error:m},[3,20];case 19:try{v&&!v.done&&(S=f.return)&&S.call(f)}finally{if(E)throw E.error}return[7];case 20:return console.log("[HlsAdPlayer] Parsed ".concat(u.length," ad(s) from VAST ").concat(null!==(I=i.getAttribute("version"))&&void 0!==I?I:""," pod response")),[2,u]}})})}function le(){var e=document.createElement("video");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e.style.objectFit="contain",e.style.backgroundColor="#000",e.playsInline=!0,e.muted=!1,e.volume=1,console.log("[HlsAdPlayer] Created ad video element with volume ".concat(e.volume)),e}function ue(){var r,i;if(k&&a&&!(S.length>0)){var n=function(){return c&&!!a&&!!k&&B.start&&!B.complete&&!k.ended};S=[{type:"timeupdate",handler:function(){var e,t,r,i;if(a&&k){Ae(),fe();var n=k.currentTime;if(B.start)try{for(var s=F(a.trackingUrls.progress),o=s.next();!o.done;o=s.next()){var l=o.value;if(!B.progressFired.has(l))n>=(null!==(r=l.offsetSeconds)&&void 0!==r?r:(null!==(i=l.offsetPercent)&&void 0!==i?i:0)/100*a.duration)&&(B.progressFired.add(l),q([l.url]))}}catch(t){e={error:t}}finally{try{o&&!o.done&&(t=s.return)&&t.call(s)}finally{if(e)throw e.error}}if(a.duration>0){var u=n/a.duration;u>=.25&&!B.firstQuartile&&(B.firstQuartile=!0,q(a.trackingUrls.firstQuartile)),u>=.5&&!B.midpoint&&(B.midpoint=!0,q(a.trackingUrls.midpoint)),u>=.75&&!B.thirdQuartile&&(B.thirdQuartile=!0,q(a.trackingUrls.thirdQuartile))}}}},{type:"loadedmetadata",handler:function(){if(c&&k){var e=k.videoWidth,t=k.videoHeight;(e<=1||t<=1)&&(console.warn("[HlsAdPlayer] Ad creative has no usable video dimensions (".concat(e,"x").concat(t,") - skipping this creative")),Ie())}}},{type:"canplay",handler:function(){a&&!B.loaded&&(B.loaded=!0,q(a.trackingUrls.loaded))}},{type:"playing",handler:function(){!function(){Te(),Ae(),C=!1,function(){if(be(),!k)return;var t=k.requestVideoFrameCallback;if("function"!=typeof t)return;var r=function(){l=void 0,c&&(C=!0,e[y]=!0)};try{l=t.call(k,r)}catch(e){console.warn("[HlsAdPlayer] Error requesting video frame callback:",e),l=void 0}}();var t=!kd();o=window.setInterval(function(){if(c&&k){if(t&&!C&&!k.paused){var r=function(e){try{if("function"==typeof e.getVideoPlaybackQuality){var t=e.getVideoPlaybackQuality();if(t&&"number"==typeof t.totalVideoFrames)return t.totalVideoFrames}var r=e.webkitDecodedFrameCount;if("number"==typeof r)return r}catch(e){console.warn("[HlsAdPlayer] Unable to read decoded video frame count:",e)}return}(k);if(void 0!==r&&r>0)C=!0,e[m]=!0;else if(k.currentTime>=1.5){var i=k.currentTime>w+.05;if("function"==typeof k.requestVideoFrameCallback&&i&&!0===e[y])return void Ie();if(0===r&&i&&!0===e[m])return void Ie()}}k.currentTime>w+.05||k.paused?Ae():Date.now()-P>=4e3&&function(){if(console.warn("[HlsAdPlayer] Ad playback stalled (no progress) - recovering to avoid a blank frame"),Te(),de(_d),b<A.length-1&&Se())return;Le()}()}},1e3)}(),a&&k&&(B.impression||(B.impression=!0,U.add(a),q(a.trackingUrls.impression),q(a.trackingUrls.creativeView),q(a.trackingUrls.verificationNotExecuted,{reason:2}),j("ad_impression",{adId:a.id,index:b,total:A.length||1})),B.start||(B.start=!0,B.lastMuted=k.muted||0===k.volume,q(a.trackingUrls.start),console.log("[HlsAdPlayer] Ad started playing")))}},{type:"ended",handler:function(){a&&!B.complete&&(fe(),ve(),B.complete=!0,q(a.trackingUrls.complete),console.log("[HlsAdPlayer] Ad completed"),b<A.length-1&&Se()||function(){console.log("[HlsAdPlayer] Handling ad completion"),ve(),Te(),c=!1,pe(!1),e.muted=!0,Re(),(null==t?void 0:t.continueLiveStreamDuringAds)||(e.style.visibility="visible",e.style.opacity="1");(null==t?void 0:t.continueLiveStreamDuringAds)&&(e.paused?(console.log("[HlsAdPlayer] Content video paused in live mode, resuming playback"),e.play().catch(function(e){console.error("[HlsAdPlayer] Error resuming content playback in live mode:",e)})):console.log("[HlsAdPlayer] Content video already playing in live mode"));j("content_resume")}())}},{type:"error",handler:function(e){c&&(console.error("[HlsAdPlayer] Ad video error:",e),de(function(e){switch(null==e?void 0:e.code){case 1:return 400;case 2:return 401;case 4:return 403;default:return 405}}(null==k?void 0:k.error)),b<A.length-1&&Se()||Le())}},{type:"volumechange",handler:function(){if(a&&k){var e=k.muted||0===k.volume;B.start?e!==B.lastMuted&&(B.lastMuted=e,q(e?a.trackingUrls.mute:a.trackingUrls.unmute)):B.lastMuted=e}}},{type:"pause",handler:function(){G=0,n()&&q(a.trackingUrls.pause)}},{type:"play",handler:function(){n()&&q(a.trackingUrls.resume)}}];try{for(var s=F(S),u=s.next();!u.done;u=s.next()){var d=u.value,h=d.type,f=d.handler;k.addEventListener(h,f)}}catch(e){r={error:e}}finally{try{u&&!u.done&&(i=s.return)&&i.call(s)}finally{if(r)throw r.error}}}}function ce(){var e,t;if(k)try{for(var r=F(S),i=r.next();!i.done;i=r.next()){var n=i.value,a=n.type,s=n.handler;k.removeEventListener(a,s)}}catch(t){e={error:t}}finally{try{i&&!i.done&&(t=r.return)&&t.call(r)}finally{if(e)throw e.error}}S=[]}function de(e){a&&(U.add(a),q(a.trackingUrls.error,{errorCode:e}))}function he(){var e,t;try{for(var r=F(A),i=r.next();!i.done;i=r.next()){var n=i.value;U.has(n)||(U.add(n),q(n.trackingUrls.notUsed,{ad:n}))}}catch(t){e={error:t}}finally{try{i&&!i.done&&(t=r.return)&&t.call(r)}finally{if(e)throw e.error}}}function fe(){if(a&&k&&M&&B.impression&&!B.viewabilitySettled){var e=k.currentTime;V>=.5&&"visible"===document.visibilityState&&!k.paused?void 0!==N&&e>=N&&(G+=e-N):G=0,N=e,G>=2&&(B.viewabilitySettled=!0,q(a.trackingUrls.viewable))}}function ve(){a&&B.impression&&!B.viewabilitySettled&&(B.viewabilitySettled=!0,q(M?a.trackingUrls.notViewable:a.trackingUrls.viewUndetermined))}function ge(){var e,t,r,i;if(E&&!(T.length>0)){var n=function(e){c&&j("ad_interaction",e)};T=[{type:"click",handler:function(){return function(){if(c&&a&&(q(a.trackingUrls.clickTracking),j("ad_click",{adId:a.id,clickThrough:a.clickThrough}),a.clickThrough))try{window.open(a.clickThrough,"_blank","noopener")}catch(e){console.warn("[HlsAdPlayer] Failed to open ClickThrough URL:",e)}}()}},{type:"mousedown",handler:n},{type:"touchstart",handler:n}];try{for(var s=F(T),o=s.next();!o.done;o=s.next()){var l=o.value,u=l.type,d=l.handler;E.addEventListener(u,d)}}catch(t){e={error:t}}finally{try{o&&!o.done&&(t=s.return)&&t.call(s)}finally{if(e)throw e.error}}var h=function(){return function(){var e;if(c&&a&&E&&B.start){var t=null!==(e=document.fullscreenElement)&&void 0!==e?e:document.webkitFullscreenElement,r=!!t&&t.contains(E);if(r!==H){H=r;var i=a.trackingUrls;q(r?i.fullscreen.concat(i.playerExpand):i.exitFullscreen.concat(i.playerCollapse))}}}()};K=[{type:"fullscreenchange",handler:h},{type:"webkitfullscreenchange",handler:h}];try{for(var f=F(K),v=f.next();!v.done;v=f.next()){var g=v.value;u=g.type,d=g.handler;document.addEventListener(u,d)}}catch(e){r={error:e}}finally{try{v&&!v.done&&(i=f.return)&&i.call(f)}finally{if(r)throw r.error}}"undefined"!=typeof IntersectionObserver&&(M=new IntersectionObserver(function(e){var t=e[e.length-1];t&&(V=t.isIntersecting?t.intersectionRatio:0)},{threshold:[0,.25,.5,.75,1]})).observe(E)}}function pe(t){t?e.dataset.stormcloudAdPlaying="true":delete e.dataset.stormcloudAdPlaying}function me(){B=D(),G=0,N=void 0}function ye(e){if(k){var t=k.play();u=t,t.catch(function(r){u===t&&(console.error("[HlsAdPlayer] Error starting ".concat(e,":"),r),Le())}).finally(function(){u===t&&(u=void 0)})}}function ke(){if(u=void 0,n&&(n.destroy(),n=void 0),k)try{k.pause(),k.removeAttribute("src"),k.load()}catch(e){console.warn("[HlsAdPlayer] Error preparing ad video for new source:",e)}}function Ee(){if(!k||!a)throw new Error("No ad video element or ad to load");var e=W(a.mediaFiles);if(!e)throw new Error("No media file available for ad");s=e;var t=Y(e);if(console.log("[HlsAdPlayer] Loading ".concat(t?"HLS":"progressive"," ad (pod ").concat(b+1,"/").concat(A.length||1,") from: ").concat(e.url)),t&&md.isSupported())n&&n.destroy(),(n=new md({enableWorker:!0,lowLatencyMode:!1})).loadSource(e.url),n.attachMedia(k),n.on(md.Events.MANIFEST_PARSED,function(){console.log("[HlsAdPlayer] HLS manifest parsed, starting playback"),ye("HLS ad playback")}),n.on(md.Events.ERROR,function(e,t){console.error("[HlsAdPlayer] HLS error:",t),t.fatal&&Le()});else if(t&&k.canPlayType("application/vnd.apple.mpegurl"))k.src=e.url,ye("native HLS ad playback");else{if(t||!z(e))throw new Error("Unsupported ad media file type: ".concat(e.type));n&&(n.destroy(),n=void 0),k.src=e.url,k.load(),ye("progressive ad playback")}}function Se(){if(b>=A.length-1)return!1;ve(),b++,a=A[b],s=void 0,me(),a&&console.log("[HlsAdPlayer] Advancing to next pod ad (".concat(b+1,"/").concat(A.length,"): ").concat(a.title,", duration: ").concat(a.duration,"s")),Te(),kd()?(!function(){if(console.log("[HlsAdPlayer] Recreating ad video element (single-decoder platform)"),ce(),ke(),k)try{k.remove()}catch(e){console.warn("[HlsAdPlayer] Error removing ad video element:",e)}k=le(),null==E||E.appendChild(k),e[p]=k,k.volume=Math.max(0,Math.min(1,h)),k.muted=d}(),ue()):ke();try{return Ee(),j("pod_ad_started",{index:b,total:A.length}),!0}catch(e){return console.error("[HlsAdPlayer] Failed to load next pod ad:",e),!1}}function Te(){null!=o&&(clearInterval(o),o=void 0),be()}function Ae(){P=Date.now(),k&&(w=k.currentTime)}function be(){if(null!=l&&k&&"function"==typeof k.cancelVideoFrameCallback)try{k.cancelVideoFrameCallback(l)}catch(e){console.warn("[HlsAdPlayer] Error cancelling video frame callback:",e)}l=void 0}function Ie(){console.warn("[HlsAdPlayer] Ad audio is advancing but no video frames decoded (black screen) - skipping this creative"),Te(),de(_d),b<A.length-1&&Se()||Le()}function Re(){ke(),E&&(E.style.display="none",E.style.pointerEvents="none")}function Le(){console.log("[HlsAdPlayer] Handling ad error"),ve(),Te(),c=!1,pe(!1),e.muted=!0,Re(),(null==t?void 0:t.continueLiveStreamDuringAds)||(e.style.visibility="visible",e.style.opacity="1"),j("ad_error")}return{initialize:function(){var t;if(console.log("[HlsAdPlayer] Initializing"),!E){var r=document.createElement("div");r.style.position="absolute",r.style.left="0",r.style.top="0",r.style.right="0",r.style.bottom="0",r.style.display="none",r.style.alignItems="center",r.style.justifyContent="center",r.style.pointerEvents="none",r.style.zIndex="30",r.style.backgroundColor="#000",null===(t=e.parentElement)||void 0===t||t.appendChild(r),E=r}e[g]=E,ge()},requestAds:function(e){return x(this,void 0,void 0,function(){var t,r,i;return O(this,function(n){switch(n.label){case 0:if(console.log("[HlsAdPlayer] Requesting ads:",e),c)return console.warn("[HlsAdPlayer] Cannot request new ads while an ad is playing"),[2,Promise.reject(new Error("Ad already playing"))];n.label=1;case 1:return n.trys.push([1,5,,6]),t=[],I.has(e)?(r=I.get(e),I.delete(e),r&&(t=[r]),console.log("[HlsAdPlayer] Using preloaded VAST response:",e),[3,4]):[3,2];case 2:return[4,oe(e)];case 3:t=n.sent(),n.label=4;case 4:return t.length?(A=t,b=0,a=t[0],s=void 0,console.log("[HlsAdPlayer] Pod parsed: ".concat(t.length,' ad(s), first="').concat(null==a?void 0:a.title,'", duration=').concat(null==a?void 0:a.duration,"s")),[2,Promise.resolve()]):(console.warn("[HlsAdPlayer] No ads available from VAST response"),j("ad_error"),[2,Promise.reject(new Error("No ads available from VAST response"))]);case 5:return i=n.sent(),console.error("[HlsAdPlayer] Error requesting ads:",i),j("ad_error"),[2,Promise.reject(i)];case 6:return[2]}})})},play:function(){return x(this,void 0,void 0,function(){var r;return O(this,function(i){if(!a)return console.warn("[HlsAdPlayer] Cannot play: No ad loaded (no ads available)"),[2,Promise.reject(new Error("No ad loaded"))];console.log("[HlsAdPlayer] Starting ad playback");try{return k||(k=le(),null==E||E.appendChild(k),e[p]=k),ue(),me(),r=e.volume,h=Math.max(0,Math.min(1,r||h)),(null==t?void 0:t.continueLiveStreamDuringAds)?console.log("[HlsAdPlayer] Content continues (Live mode)"):(e.pause(),console.log("[HlsAdPlayer] Content paused (VOD mode)")),console.log("[HlsAdPlayer] FORCE MUTING main video"),e.muted=!0,c=!0,pe(!0),k&&(k.volume=Math.max(0,Math.min(1,h)),k.muted=d,console.log("[HlsAdPlayer] Set ad video volume to ".concat(k.volume,", muted: ").concat(k.muted,", originalMutedState: ").concat(d,", contentVolume: ").concat(r))),E&&(E.style.display="flex",E.style.pointerEvents="auto"),j("content_pause"),Ee(),[2,Promise.resolve()]}catch(e){return console.error("[HlsAdPlayer] Error playing ad:",e),Le(),[2,Promise.reject(e)]}return[2]})})},pause:function(){if(c&&k)try{k&&!k.paused&&k.pause()}catch(e){console.warn("[HlsAdPlayer] Error pausing ad:",e)}},resume:function(){if(c&&k)try{k&&k.paused&&k.play().catch(function(){})}catch(e){console.warn("[HlsAdPlayer] Error resuming ad:",e)}},stop:function(){return x(this,void 0,void 0,function(){var r;return O(this,function(i){return console.log("[HlsAdPlayer] Stopping ad"),ve(),he(),Te(),c=!1,pe(!1),r=e.muted,e.muted=d,e.volume=Math.max(0,Math.min(1,h)),console.log("[HlsAdPlayer] Restored mute state on stop: ".concat(r," -> ").concat(d,", volume: ").concat(e.volume)),Re(),e.style.visibility="visible",e.style.opacity="1",(null==t?void 0:t.continueLiveStreamDuringAds)&&e.paused&&(console.log("[HlsAdPlayer] Content video paused in live mode, resuming playback on stop"),e.play().catch(function(e){console.error("[HlsAdPlayer] Error resuming content playback in live mode on stop:",e)})),a=void 0,s=void 0,A=[],b=0,[2]})})},destroy:function(){var t,r;console.log("[HlsAdPlayer] Destroying"),ve(),he(),Te();try{for(var i=F(L),n=i.next();!n.done;n=i.next()){var o=n.value;clearTimeout(o)}}catch(e){t={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}L=[],c=!1,pe(!1),e.muted=d,e.volume=Math.max(0,Math.min(1,h)),ce(),function(){var e,t,r,i;if(E)try{for(var n=F(T),a=n.next();!a.done;a=n.next()){var s=a.value,o=s.type,l=s.handler;E.removeEventListener(o,l)}}catch(t){e={error:t}}finally{try{a&&!a.done&&(t=n.return)&&t.call(n)}finally{if(e)throw e.error}}T=[];try{for(var u=F(K),c=u.next();!c.done;c=u.next()){var d=c.value;o=d.type,l=d.handler,document.removeEventListener(o,l)}}catch(e){r={error:e}}finally{try{c&&!c.done&&(i=u.return)&&i.call(u)}finally{if(r)throw r.error}}K=[],null==M||M.disconnect(),M=void 0}(),Re(),a=void 0,s=void 0,A=[],b=0,f.clear(),I.clear(),R.clear()},isAdPlaying:function(){return c},resize:function(e,t){console.log("[HlsAdPlayer] Resizing to ".concat(e,"x").concat(t)),E&&(E.style.width="".concat(e,"px"),E.style.height="".concat(t,"px")),k&&(k.style.width="".concat(e,"px"),k.style.height="".concat(t,"px"))},on:function(e,t){f.has(e)||f.set(e,new Set),f.get(e).add(t)},off:function(e,t){var r;null===(r=f.get(e))||void 0===r||r.delete(t)},updateOriginalMutedState:function(e,t){var r="number"!=typeof t||Number.isNaN(t)?h:Math.max(0,Math.min(1,t));console.log("[HlsAdPlayer] updateOriginalMutedState called: { muted: ".concat(d," -> ").concat(e,", volume: ").concat(h," -> ").concat(r," }")),d=e,h=r},getOriginalMutedState:function(){return d},getOriginalVolume:function(){return h},setAdVolume:function(e){if(k&&c){var t=Math.max(0,Math.min(1,e));k.volume=t,k.muted=0===t}},getAdVolume:function(){return k&&c?k.volume:1},showPlaceholder:function(){var t;if(e.style.opacity="0",e.style.visibility="hidden",!E){var r=document.createElement("div");r.style.position="absolute",r.style.left="0",r.style.top="0",r.style.right="0",r.style.bottom="0",r.style.display="none",r.style.alignItems="center",r.style.justifyContent="center",r.style.pointerEvents="none",r.style.zIndex="10",r.style.backgroundColor="#000",null===(t=e.parentElement)||void 0===t||t.appendChild(r),E=r}E&&(E.style.display="flex",E.style.pointerEvents="auto")},hidePlaceholder:function(){E&&!c&&(E.style.display="none",E.style.pointerEvents="none"),c||(e.style.visibility="visible",e.style.opacity="1")},getLoadedAdDuration:function(){return null==a?void 0:a.duration},getLoadedAdId:function(){return null==a?void 0:a.id},getPodAdCount:function(){return A.length},getPodTotalDurationMs:function(){return A.reduce(function(e,t){return e+(t.duration>0?1e3*t.duration:0)},0)}}}var xd=[/^localhost$/i,/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,/^0\.0\.0\.0$/,/^::1$/,/^10\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,/^192\.168\.\d{1,3}\.\d{1,3}$/,/^172\.(1[6-9]|2\d|3[0-1])\.\d{1,3}\.\d{1,3}$/];function Od(e){if(!e)return null!=e?e:"";var t,r,i;try{t=new URL(e)}catch(t){return e}if("http:"!==t.protocol&&"https:"!==t.protocol)return e;if(r=t.hostname,!(i=r.replace(/^\[/,"").replace(/\]$/,"").toLowerCase())||!(i.endsWith(".local")||i.endsWith(".localhost")||xd.some(function(e){return e.test(i)})))return e;var n=t.pathname.replace(/\/{2,}/g,"/")||"/index.html";return"file://".concat(n)}var Fd,Nd,Bd;function Ud(){var e;return"undefined"!=typeof window&&(null===(e=window.goog)||void 0===e?void 0:e.pal)?Promise.resolve():Bd||(Bd=new Promise(function(e,t){var r,i=document.querySelector('script[data-pal="true"]');if(i){if(null===(r=window.goog)||void 0===r?void 0:r.pal)return void e();var n=setTimeout(function(){return t(new Error("PAL SDK load timeout"))},1e4);return i.addEventListener("load",function(){clearTimeout(n),e()}),void i.addEventListener("error",function(){clearTimeout(n),t(new Error("PAL SDK load failed"))})}var a=document.createElement("script");a.src="https://imasdk.googleapis.com/pal/sdkloader/pal.js",a.async=!0,a.setAttribute("data-pal","true"),a.onload=function(){return e()},a.onerror=function(){return t(new Error("PAL SDK load failed"))},document.head.appendChild(a)}),Bd)}function Vd(){var e,t="";return{generateNonce:function(){return x(this,arguments,void 0,function(r){var i,n,a,s,o,l,u,c,d,h;return void 0===r&&(r={}),O(this,function(f){switch(f.label){case 0:return f.trys.push([0,3,,4]),[4,Ud()];case 1:return f.sent(),i=function(e){if(Fd&&Nd===e)return Fd;var t=window.goog,r=new t.pal.ConsentSettings;return r.allowStorage=e,Fd=new t.pal.NonceLoader(r),Nd=e,Fd}(null===(l=r.allowStorage)||void 0===l||l),n=window.goog,(a=new n.pal.NonceRequest).adWillAutoPlay=null===(u=r.adWillAutoPlay)||void 0===u||u,a.adWillPlayMuted=null!==(c=r.adWillPlayMuted)&&void 0!==c&&c,a.playerVolume=null!==(d=r.playerVolume)&&void 0!==d?d:a.adWillPlayMuted?0:1,a.continuousPlayback=null===(h=r.continuousPlayback)||void 0===h||h,a.descriptionUrl=Od(r.descriptionUrl||("undefined"!=typeof window?window.location.href:"")),a.iconsSupported=!0,a.playerType="StormcloudVideoPlayer",a.playerVersion="1.0",a.supportedApiFrameworks="2,7,9",a.url=Od(r.descriptionUrl||("undefined"!=typeof window?window.location.href:"")),a.videoWidth=r.videoWidth||640,a.videoHeight=r.videoHeight||480,r.ppid&&(a.ppid=r.ppid),r.sessionId&&(a.sessionId=r.sessionId),console.log("[PAL] NonceRequest before generateNonce:",JSON.stringify({adWillAutoPlay:a.adWillAutoPlay,adWillPlayMuted:a.adWillPlayMuted,playerVolume:a.playerVolume,continuousPlayback:a.continuousPlayback,descriptionUrl:a.descriptionUrl,iconsSupported:a.iconsSupported,playerType:a.playerType,playerVersion:a.playerVersion,supportedApiFrameworks:a.supportedApiFrameworks,url:a.url,videoWidth:a.videoWidth,videoHeight:a.videoHeight,ppid:a.ppid,sessionId:a.sessionId},null,2)),[4,i.loadNonceManager(a)];case 2:return s=f.sent(),e=s,t=s.getNonce(),console.log("[PAL] Nonce generated successfully"),[2,t];case 3:return o=f.sent(),console.warn("[PAL] Failed to generate nonce:",o),t="",e=void 0,[2,""];case 4:return[2]}})})},getCurrentNonce:function(){return t},injectNonce:function(e){if(!t||!e)return e;try{var r=new URL(e);return r.searchParams.delete("paln"),r.searchParams.set("givn",t),r.toString()}catch(r){var i=e.replace(/([?&])paln=[^&]*/g,"").replace(/[?&]$/,""),n=i.includes("?")?"&":"?";return"".concat(i).concat(n,"givn=").concat(encodeURIComponent(t))}},sendPlaybackStart:function(){try{null==e||e.sendPlaybackStart()}catch(e){}},sendPlaybackEnd:function(){try{null==e||e.sendPlaybackEnd()}catch(e){}},sendAdClick:function(){try{null==e||e.sendAdClick()}catch(e){}},sendAdTouch:function(t){try{null==e||e.sendAdTouch(t)}catch(e){}},reset:function(){t="",e=void 0}}}var Gd={enabled:!0,baseUrl:"https://player-analytics-ingest-api-760490581852.us-central1.run.app/api/adstorm/player-tracking"},Hd=_({},Gd);function Kd(e){Object.assign(Hd,e)}function jd(){return!0===Hd.enabled}function qd(e){var t=Hd.baseUrl.replace(/\/+$/,"");return"".concat(t,"impressions"===e?"/impressions/ingest":"/metrics/ingest")}function Wd(e,t,r){return x(this,void 0,void 0,function(){var i,n;return O(this,function(a){switch(a.label){case 0:if(!jd()||!e)return[2,!1];a.label=1;case 1:return a.trys.push([1,3,,4]),[4,fetch(qd(t),{method:"POST",headers:{"Content-Type":"application/json",Authorization:"License-Key ".concat(e)},body:JSON.stringify(r)})];case 2:return(i=a.sent()).ok?[2,!0]:(console.warn("[StormcloudVideoPlayer] Tracking ingest failed (".concat(i.status,") for ").concat(t)),[2,!1]);case 3:return n=a.sent(),console.warn("[StormcloudVideoPlayer] Tracking ingest error for ".concat(t,":"),n),[2,!1];case 4:return[2]}})})}var Yd,zd="stormcloud.ctv.sid",Xd="stormcloud.web.sid",Qd="stormcloud.player.id",$d=["rdid","ifa","advertisingId","advertising_id","deviceAdvertisingId","aaid","adid","rida","tifa","lgudid"],Jd=new Set(["aaid","adid"]);function Zd(e){var t,r,i=kh(),n=gh(),a=i.deviceId||(e?Ah():void 0)||n.deviceId,s=i.deviceIdType||bh("deviceIdType")||bh("idtype")||n.deviceIdType||lh(),o=i.deviceId?i.limitAdTracking:n.limitAdTracking,l=null!=a?null!==(t=null!=o?o:Ih())&&void 0!==t&&t:void 0;if(!a&&e){var u=uh(Qd);u&&(a=u,s="dpid",l=null!==(r=null!=o?o:Ih())&&void 0!==r&&r)}var c=function(e){var t=function(e){var t,r,i,n,a,s;if("undefined"==typeof window)return;var o=["dth","deviceTypeHint"],l=sh(window.__STORMCLOUD_DTH__);if(null!=l)return l;try{for(var u=F(Eh()),c=u.next();!c.done;c=u.next()){var d=c.value;try{for(var h=(i=void 0,F(o)),f=h.next();!f.done;f=h.next()){var v=f.value,g=null==d?void 0:d[v];if(null!=(y=sh("function"==typeof g?oh(g,d):g)))return y}}catch(e){i={error:e}}finally{try{f&&!f.done&&(n=h.return)&&n.call(h)}finally{if(i)throw i.error}}}}catch(e){t={error:e}}finally{try{c&&!c.done&&(r=u.return)&&r.call(u)}finally{if(t)throw t.error}}if(!e)return;try{for(var p=F(["stormcloud.dth","dth"]),m=p.next();!m.done;m=p.next()){var y;if(null!=(y=sh(bh(v=m.value))))return y}}catch(e){a={error:e}}finally{try{m&&!m.done&&(s=p.return)&&s.call(p)}finally{if(a)throw a.error}}return}(e);return null!=t?t:function(e){var t=e?eh.CONNECTED_TV:eh.DESKTOP;if("undefined"==typeof navigator)return t;var r=navigator.userAgent||"",i=navigator.maxTouchPoints||0;if(rh.test(r))return eh.SET_TOP_BOX;if(ih.test(r))return eh.GAME_CONSOLE;if(nh.test(r)&&!/Mobile/i.test(r))return eh.CONNECTED_TV;if(ah.test(r))return eh.FEATURE_PHONE;if(/iPad/i.test(r)||/Macintosh/i.test(r)&&i>1)return eh.TABLET;if(/iPhone|iPod/i.test(r))return eh.SMARTPHONE;if(/Android/i.test(r))return/Mobile/i.test(r)?eh.SMARTPHONE:0===i?eh.SET_TOP_BOX:eh.TABLET;return/Mobile|Windows Phone|BlackBerry/i.test(r)?eh.SMARTPHONE:t}(e)}(e);if(e)return _(_(_(_({isCtv:!0,sessionId:ch()},a?{deviceId:a}:{}),a&&s?{deviceIdType:s}:{}),a&&null!=l?{limitAdTracking:l}:{}),{deviceTypeHint:c});var d=function(){var e,t;if("undefined"==typeof window)return;try{var r=null===(e=window.sessionStorage)||void 0===e?void 0:e.getItem(Xd);if(r&&!mh(r))return r}catch(e){}var i=Yd||vh();Yd=i;try{null===(t=window.sessionStorage)||void 0===t||t.setItem(Xd,i)}catch(e){}return i}();return _(_(_(_(_({isCtv:!1},d?{sessionId:d}:{}),a?{deviceId:a}:{}),a&&s?{deviceIdType:s}:{}),a&&null!=l?{limitAdTracking:l}:{}),{deviceTypeHint:c})}var eh={FEATURE_PHONE:1,SMARTPHONE:2,DESKTOP:3,TABLET:4,CONNECTED_TV:5,GAME_CONSOLE:6,SET_TOP_BOX:7},th={featurephone:eh.FEATURE_PHONE,smartphone:eh.SMARTPHONE,mobile:eh.SMARTPHONE,phone:eh.SMARTPHONE,desktop:eh.DESKTOP,pc:eh.DESKTOP,tablet:eh.TABLET,ctv:eh.CONNECTED_TV,tv:eh.CONNECTED_TV,connectedtv:eh.CONNECTED_TV,smarttv:eh.CONNECTED_TV,console:eh.GAME_CONSOLE,gameconsole:eh.GAME_CONSOLE,stb:eh.SET_TOP_BOX,settopbox:eh.SET_TOP_BOX},rh=/LGSTB|\bSTB\b|STB\d|Set-?Top|SetTopBox|TV ?Box|Kaon|Humax|Arris|Technicolor|Sagemcom|Infomir|MAG\d{3}|KreaTV|Amino|Formuler|Dune ?HD|TiVo|MiBOX|Mi Box|SHIELD Android TV|\bAFT[A-Z]|Roku|AppleTV|Apple TV|CrKey/i,ih=/PlayStation|Xbox|Nintendo/i,nh=/Web0S|webOS|Tizen|SMART-TV|SmartTV|NetCast|BRAVIA|HbbTV|VIDAA|Hisense|Philips|Viera|AQUOS|Android TV|Google TV|\bTV\b/i,ah=/KAIOS|MIDP|J2ME|Series40|Opera Mini/i;function sh(e){if("number"==typeof e)return Number.isInteger(e)&&e>=1&&e<=7?e:void 0;if("string"==typeof e){var t=e.trim();return/^[1-7]$/.test(t)?parseInt(t,10):th[t.toLowerCase().replace(/[\s_-]/g,"")]}}function oh(e,t){try{return e.call(t)}catch(e){return}}function lh(){if("undefined"!=typeof navigator){var e=navigator.userAgent;return/Roku/i.test(e)?"rida":/Tizen|Samsung/i.test(e)?"tifa":/AppleTV|Apple TV/i.test(e)?"tvOS":/AFT|Fire TV|Amazon/i.test(e)?"afai":/Web0S|webOS|LG Browser|LGSTB|LGE/i.test(e)?"lgudid":/Android|Google TV/i.test(e)?"aaid":/iPhone|iPad|iPod/i.test(e)?"idfa":void 0}}function uh(e){if("undefined"!=typeof window){var t=dh(e);if(t)return hh(e,t),t;var r=vh();return hh(e,r),r}}function ch(){var e=dh(zd);if(e)return hh(zd,e),e;var t=vh();return hh(zd,t),t}function dh(e){return bh(e)||function(e){var t,r;if("undefined"==typeof document)return;try{var i=encodeURIComponent(e)+"=",n=document.cookie?document.cookie.split(";"):[];try{for(var a=F(n),s=a.next();!s.done;s=a.next()){var o=s.value.trim();if(o.startsWith(i))return decodeURIComponent(o.slice(i.length))||void 0}}catch(e){t={error:e}}finally{try{s&&!s.done&&(r=a.return)&&r.call(a)}finally{if(t)throw t.error}}}catch(e){}return}(e)}function hh(e,t){var r;try{null===(r=window.localStorage)||void 0===r||r.setItem(e,t)}catch(e){}!function(e,t){if("undefined"==typeof document)return;try{document.cookie=encodeURIComponent(e)+"="+encodeURIComponent(t)+";path=/;max-age="+fh+";SameSite=Lax"}catch(e){}}(e,t)}var fh=15768e4;function vh(){var e,t,r;if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return crypto.randomUUID();var i=new Uint8Array(16);if("undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues)crypto.getRandomValues(i);else for(var n=Date.now()^Math.floor(1e3*function(){try{if("undefined"!=typeof performance&&"function"==typeof performance.now)return performance.now()}catch(e){}return 0}()),a=0;a<16;a++)n=1103515245*n+12345&2147483647,i[a]=255&(n^Math.floor(256*Math.random()));i[6]=15&(null!==(e=i[6])&&void 0!==e?e:0)|64,i[8]=63&(null!==(t=i[8])&&void 0!==t?t:0)|128;var s="";for(a=0;a<16;a++)s+=(null!==(r=i[a])&&void 0!==r?r:0).toString(16).padStart(2,"0");return s.slice(0,8)+"-"+s.slice(8,12)+"-"+s.slice(12,16)+"-"+s.slice(16,20)+"-"+s.slice(20,32)}function gh(){var e,t;if("undefined"==typeof window)return{};try{var r=null===(e=window.webapis)||void 0===e?void 0:e.adinfo;if(r){var i="function"==typeof r.getTIFA?r.getTIFA():r.tifa;if("string"==typeof i&&i&&!mh(i)){var n="function"==typeof r.isLATEnabled?r.isLATEnabled():void 0;return _({deviceId:i,deviceIdType:"tifa"},"boolean"==typeof n?{limitAdTracking:n}:{})}}}catch(e){}try{var a=window.webOSDev;if(a){var s="function"==typeof a.LGUDID?a.LGUDID():null!==(t=a.lgudid)&&void 0!==t?t:a.LGUDID;if("string"==typeof s&&s){if(yh(s))return{deviceIdType:"lgudid",limitAdTracking:!0};if(!mh(s))return{deviceId:s,deviceIdType:"lgudid",limitAdTracking:!1}}}}catch(e){}try{var o=window.Roku;if(o){var l="function"==typeof o.getPublisherUniqueId?o.getPublisherUniqueId():o.rida;if("string"==typeof l&&l&&!mh(l))return{deviceId:l,deviceIdType:"rida",limitAdTracking:!1}}}catch(e){}return{}}var ph=new Set(["38400000-8cf0-11bd-b23e-10b96e40000d","00000000-0000-0000-0000-000000000000"]);function mh(e){var t=e.trim();return!t||/^(\[[^\]]*\]|\{[^}]*\}|%%[^%]*%%)$/.test(t)||/^(unknown|null|undefined|none|n\/a|\$\{[^}]+\})$/i.test(t)||ph.has(t.toLowerCase())}function yh(e){return ph.has(e.trim().toLowerCase())}function kh(){var e,t;try{for(var r=F(Eh()),i=r.next();!i.done;i=r.next()){var n=i.value,a=Sh(n,["contentUrl","url","videoUrl","canonicalUrl"])||void 0,s=Sh(n,["appId","msid","applicationId","packageName"])||void 0,o=Sh(n,["appName","an","applicationName"])||void 0,l=Sh(n,["rdid","ifa","advertisingId","adId","deviceId","lgudid","LGUDID","tifa","rida","afai","aaid"])||void 0;if(a||l||s||o){var u=Sh(n,["idtype","deviceIdType","advertisingIdType","idType"])||lh(),c=Th(n,["is_lat","limitAdTracking","limitedAdTracking","lat"]);return _(_(_(_(_(_({},a?{contentUrl:a}:{}),s?{appId:s}:{}),o?{appName:o}:{}),l?{deviceId:l}:{}),l&&u?{deviceIdType:u}:{}),l&&null!=c?{limitAdTracking:c}:{})}}}catch(t){e={error:t}}finally{try{i&&!i.done&&(t=r.return)&&t.call(r)}finally{if(e)throw e.error}}return{}}function Eh(){return"undefined"==typeof window?[]:[window.__STORMCLOUD_CTV_AD_INFO__,window.__STORMCLOUD_CTV__,window.stormcloudCtv,window.AiryTV,window.Android,window.webOS,window.tizen,window.amazon].filter(Boolean)}function Sh(e,t){var r,i;try{for(var n=F(t),a=n.next();!a.done;a=n.next()){var s=a.value,o=null==e?void 0:e[s];if("string"==typeof o&&o)return o;if("function"==typeof o)try{var l=o.call(e);if("string"==typeof l&&l)return l}catch(e){}}}catch(e){r={error:e}}finally{try{a&&!a.done&&(i=n.return)&&i.call(n)}finally{if(r)throw r.error}}}function Th(e,t){var r,i;try{for(var n=F(t),a=n.next();!a.done;a=n.next()){var s=a.value,o=null==e?void 0:e[s],l=Rh(o);if(null!=l)return l;if("function"==typeof o)try{var u=Rh(o.call(e));if(null!=u)return u}catch(e){}}}catch(e){r={error:e}}finally{try{a&&!a.done&&(i=n.return)&&i.call(n)}finally{if(r)throw r.error}}}function Ah(){var e,t;try{for(var r=F($d),i=r.next();!i.done;i=r.next()){var n=bh(i.value);if(n)return n}}catch(t){e={error:t}}finally{try{i&&!i.done&&(t=r.return)&&t.call(r)}finally{if(e)throw e.error}}}function bh(e){var t;if("undefined"!=typeof window)try{return(null===(t=window.localStorage)||void 0===t?void 0:t.getItem(e))||void 0}catch(e){return}}function Ih(){return Rh(bh("limitAdTracking")||bh("limitedAdTracking")||bh("is_lat"))}function Rh(e){if("boolean"==typeof e)return e;if("number"==typeof e)return 1===e;if("string"==typeof e){var t=e.toLowerCase();if("1"===t||"true"===t||"yes"===t)return!0;if("0"===t||"false"===t||"no"===t)return!1}}var Lh=null;function Ph(e){var t={};return e.debugAdTiming&&(t.debugAdTiming=!0),void 0!==e.isLiveStream&&(t.inputStreamType=e.isLiveStream?"live":"vod"),t}function wh(){var e,t,r,i,n,a=navigator.userAgent,s=navigator.platform,o=navigator.vendor||"",l=navigator.maxTouchPoints||0,u=navigator.deviceMemory||null,c=navigator.hardwareConcurrency||1,d={width:null===screen||void 0===screen?void 0:screen.width,height:null===screen||void 0===screen?void 0:screen.height,availWidth:null===screen||void 0===screen?void 0:screen.availWidth,availHeight:null===screen||void 0===screen?void 0:screen.availHeight,orientation:(null===(e=null===screen||void 0===screen?void 0:screen.orientation)||void 0===e?void 0:e.type)||"",pixelDepth:null===screen||void 0===screen?void 0:screen.pixelDepth},h="desktop",f="Unknown",v="Unknown",g="",p=!1,m=!1,y=!1;if(a.includes("Web0S")){f="LG",v="webOS",p=!0,h="tv";var k=a.match(/Web0S\/([^\s]+)/);g=k?"webOS ".concat(k[1]):"webOS TV"}else if(a.includes("Tizen")){f="Samsung",v="Tizen",p=!0,h="tv";var E=a.match(/Tizen\/([^\s]+)/),S=a.match(/(?:Smart-TV|SMART-TV|TV)/i)?"Smart TV":"";g=E?"Tizen ".concat(E[1]," ").concat(S).trim():"Tizen TV"}else a.includes("Philips")?(f="Philips",v="Saphi",p=!0,h="tv"):a.includes("Sharp")||a.includes("AQUOS")?(f="Sharp",v="Android TV",p=!0,h="tv"):a.includes("Android")&&(a.includes("Sony")||o.includes("Sony"))?(f="Sony",v="Android TV",p=!0,h="tv"):a.includes("Android")&&(a.includes("NetCast")||a.includes("LG"))?(f="LG",v="Android TV",p=!0,h="tv"):a.includes(" Roku")||a.includes("Roku/")?(f="Roku",v="Roku OS",p=!0,h="tv"):a.includes("AppleTV")&&(f="Apple",v="tvOS",p=!0,h="tv");if(a.includes("Android")){m=!0,v="Android",h=/Mobile/.test(a)?"mobile":"tablet",a.includes("Android")&&(0===l||a.includes("Google TV")||a.includes("XiaoMi"))&&(h="tv",p=!0,f="Unknown"===f?"Android TV":f);var T=a.match(/\(([^)]*Android[^)]*)\)/);T&&T[1]&&(g=T[1])}return/iPad|iPhone|iPod/.test(a)&&(v="iOS",h="mobile",f="Apple",navigator.maxTouchPoints>1&&/iPad/.test(a)&&(h="tablet")),m||p||/Mobile/.test(a)||(a.includes("Windows")?(v="Windows",h="desktop"):a.includes("Mac")&&!/iPhone/.test(a)?(v="macOS",h="desktop",l>1&&(h="tablet")):a.includes("Linux")&&(v="Linux",h="desktop")),"Unknown"===f&&((o.includes("Google")||a.includes("Chrome"))&&(f="Google"),o.includes("Apple")&&(f="Apple"),(o.includes("Samsung")||a.includes("SM-"))&&(f="Samsung")),y=/wv|WebView|Linux; U;/.test(a),0===(null===window||void 0===window?void 0:window.outerHeight)&&0===(null===window||void 0===window?void 0:window.outerWidth)&&(y=!0),n=window.matchMedia("(display-mode: standalone)").matches||!0===window.navigator.standalone||void 0!==(null===(r=null===(t=window.screen)||void 0===t?void 0:t.orientation)||void 0===r?void 0:r.angle),{brand:f,os:v,model:g||a.substring(0,50)+"...",deviceType:h,isSmartTV:p,isAndroid:m,isWebView:y,isWebApp:n,domain:window.location.hostname,origin:window.location.origin,path:window.location.pathname,userAgent:a,vendor:o,platform:s,screen:d,hardwareConcurrency:c,deviceMemory:u,maxTouchPoints:l,language:navigator.language,languages:(null===(i=navigator.languages)||void 0===i?void 0:i.join(","))||"",cookieEnabled:navigator.cookieEnabled,doNotTrack:navigator.doNotTrack||"",referrer:document.referrer,visibilityState:document.visibilityState}}function Ch(e){return x(this,void 0,void 0,function(){var t,r,i,n,a,s,o,l,u,c,d;return O(this,function(h){switch(h.label){case 0:if("undefined"==typeof crypto||!(null===(d=crypto.subtle)||void 0===d?void 0:d.digest))return[3,5];h.label=1;case 1:return h.trys.push([1,4,,5]),[4,crypto.subtle.digest("SHA-256",new Uint8Array([1,2,3]))];case 2:if(h.sent(),t=void 0,"undefined"!=typeof TextEncoder)t=(new TextEncoder).encode(e);else{for(r=unescape(encodeURIComponent(e)),i=new Uint8Array(r.length),s=0;s<r.length;s++)i[s]=r.charCodeAt(s);t=i}return[4,crypto.subtle.digest("SHA-256",t)];case 3:return n=h.sent(),[2,Array.from(new Uint8Array(n)).map(function(e){return e.toString(16).padStart(2,"0")}).join("")];case 4:return h.sent(),console.warn("[StormcloudVideoPlayer] crypto.subtle not supported, using fallback hash"),[3,5];case 5:for(a=0,s=0;s<e.length;s++)o=e.charCodeAt(s),a=(a<<5)-a+o,a&=a;return l=Math.abs(a).toString(16).padStart(8,"0"),u=Date.now().toString(16).padStart(12,"0"),c=Math.random().toString(16).substring(2,14).padStart(12,"0"),[2,(l+u+c).padEnd(64,"0")]}})})}function Dh(e){var t=function(e){void 0===e&&(e=!0);var t=kh(),r=gh(),i=t.deviceId||(e?Ah():void 0)||r.deviceId;if(i&&!mh(i)&&!yh(i))return i}(e.isSmartTV);if(t)return"device:".concat(t);var r=uh(Qd);return r?"persisted:".concat(r):"fingerprint:".concat(JSON.stringify(e))}function _h(e){return x(this,void 0,void 0,function(){return O(this,function(t){switch(t.label){case 0:return Lh?[2,Lh]:[4,Ch(Dh(e))];case 1:return[2,Lh=t.sent()]}})})}function Mh(e){return Boolean(jd()&&e)}function xh(){return x(this,arguments,void 0,function(e,t){var r,i,n,a,s,o,l;return void 0===e&&(e={}),void 0===t&&(t={}),O(this,function(u){switch(u.label){case 0:return r=wh(),(i=!!e.debugAdTiming)&&console.log("[StormcloudVideoPlayer] clientInfo: ",JSON.stringify(r,null,2)),[4,_h(r)];case 1:return n=u.sent(),i&&console.log("[StormcloudVideoPlayer] playerId: ",n),a=null!==(s=t.captureAt)&&void 0!==s?s:(new Date).toISOString(),[2,_({player_id:n,device_type:r.deviceType,os:r.os.toLowerCase(),ad_loaded:null!==(o=t.adLoaded)&&void 0!==o&&o,ad_detect:null!==(l=t.adDetect)&&void 0!==l&&l,capture_at:a},e.inputStreamType?{input_stream_type:e.inputStreamType}:{})]}})})}function Oh(e){return x(this,arguments,void 0,function(e,t){var r,i;return void 0===t&&(t={}),O(this,function(n){switch(n.label){case 0:if(!Mh(e))return[2];n.label=1;case 1:return n.trys.push([1,4,,5]),[4,xh(t,{adLoaded:!1,adDetect:!1})];case 2:return r=n.sent(),[4,Wd(e,"metrics",{events:[r]})];case 3:return n.sent(),[3,5];case 4:return i=n.sent(),console.error("[StormcloudVideoPlayer] Error sending initial tracking data:",i),[3,5];case 5:return[2]}})})}function Fh(e,t){return x(this,arguments,void 0,function(e,t,r){var i;return void 0===r&&(r={}),O(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,Uh(e,r,{adDetect:!0,captureAt:t.timestamp})];case 1:return n.sent(),[3,3];case 2:return i=n.sent(),console.error("[StormcloudVideoPlayer] Error sending ad detect tracking:",i),[3,3];case 3:return[2]}})})}function Nh(e,t){return x(this,arguments,void 0,function(e,t,r){var i;return void 0===r&&(r={}),O(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,Uh(e,r,{adLoaded:!0,captureAt:t.timestamp})];case 1:return n.sent(),[3,3];case 2:return i=n.sent(),console.error("[StormcloudVideoPlayer] Error sending ad loaded tracking:",i),[3,3];case 3:return[2]}})})}function Bh(e,t){return x(this,arguments,void 0,function(e,t,r){var i,n;return void 0===r&&(r={}),O(this,function(a){switch(a.label){case 0:if(!Mh(e))return[2];a.label=1;case 1:return a.trys.push([1,5,,6]),[4,xh(r,{captureAt:t.timestamp})];case 2:return i=a.sent(),[4,Wd(e,"metrics",{events:[i]})];case 3:return a.sent(),[4,Wd(e,"impressions",{events:[{player_id:i.player_id,ad_played_count:1,ad_url:t.adUrl,capture_at:t.timestamp}]})];case 4:return a.sent(),[3,6];case 5:return n=a.sent(),console.error("[StormcloudVideoPlayer] Error sending ad impression tracking:",n),[3,6];case 6:return[2]}})})}function Uh(e){return x(this,arguments,void 0,function(e,t,r){var i,n;return void 0===t&&(t={}),void 0===r&&(r={}),O(this,function(a){switch(a.label){case 0:if(!Mh(e))return[2];a.label=1;case 1:return a.trys.push([1,4,,5]),[4,xh(t,r)];case 2:return i=a.sent(),[4,Wd(e,"metrics",{events:[i]})];case 3:return a.sent(),[3,5];case 4:return n=a.sent(),console.error("[StormcloudVideoPlayer] Error sending heartbeat:",n),[3,5];case 5:return[2]}})})}function Vh(){"function"!=typeof Object.assign&&(Object.assign=function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(null==e)throw new TypeError("Cannot convert undefined or null to object");for(var i=Object(e),n=0;n<t.length;n++){var a=t[n];if(null!=a)for(var s in a)Object.prototype.hasOwnProperty.call(a,s)&&(i[s]=a[s])}return i}),Array.from||(Array.from=function(e,t,r){var i=Object(e);if(null==e)throw new TypeError("Array.from requires an array-like object");for(var n=i.length>>>0,a=new Array(n),s=0;s<n;s++)a[s]=t?t.call(r,i[s],s):i[s];return a}),String.prototype.startsWith||(String.prototype.startsWith=function(e,t){return t=!t||t<0?0:+t,this.substring(t,t+e.length)===e}),String.prototype.endsWith||(String.prototype.endsWith=function(e,t){return(void 0===t||t>this.length)&&(t=this.length),this.substring(t-e.length,t)===e}),String.prototype.includes||(String.prototype.includes=function(e,t){return"number"!=typeof t&&(t=0),!(t+e.length>this.length)&&-1!==this.indexOf(e,t)}),function(){if("undefined"==typeof URLSearchParams){var e=function(){function e(t){var r=this;this.params=new Map,"string"==typeof t?this.parseQueryString(t):t instanceof e&&t.forEach(function(e,t){r.append(t,e)})}return e.prototype.parseQueryString=function(e){var t=this,r=e.startsWith("?")?e.slice(1):e;r&&r.split("&").forEach(function(e){var r=N(e.split("="),2),i=r[0],n=r[1];if(i){var a=t.safeDecodeURIComponent(i),s=n?t.safeDecodeURIComponent(n):"";t.append(a,s)}})},e.prototype.safeDecodeURIComponent=function(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch(t){return e}},e.prototype.append=function(e,t){var r=this.params.get(e)||[];r.push(String(t)),this.params.set(e,r)},e.prototype.delete=function(e){this.params.delete(e)},e.prototype.get=function(e){var t=this.params.get(e);return t&&t.length>0&&void 0!==t[0]?t[0]:null},e.prototype.getAll=function(e){return this.params.get(e)||[]},e.prototype.has=function(e){return this.params.has(e)},e.prototype.set=function(e,t){this.params.set(e,[String(t)])},e.prototype.forEach=function(e){var t=this;this.params.forEach(function(r,i){r.forEach(function(r){e(r,i,t)})})},e.prototype.toString=function(){var e=[];return this.params.forEach(function(t,r){t.forEach(function(t){e.push("".concat(encodeURIComponent(r),"=").concat(encodeURIComponent(t)))})}),e.join("&")},e}();window.URLSearchParams=e}}(),function(){if("undefined"==typeof TextEncoder){var e=function(){function e(){this.encoding="utf-8"}return e.prototype.encode=function(e){for(var t=[],r=0;r<e.length;r++){var i=e.charCodeAt(r);i<128?t.push(i):i<2048?t.push(192|i>>6,128|63&i):i<55296||i>=57344?t.push(224|i>>12,128|i>>6&63,128|63&i):(r++,i=65536+((1023&i)<<10|1023&e.charCodeAt(r)),t.push(240|i>>18,128|i>>12&63,128|i>>6&63,128|63&i))}return new Uint8Array(t)},e}();window.TextEncoder=e}}(),"undefined"==typeof Promise||Promise.prototype.finally||(Promise.prototype.finally=function(e){var t=this.constructor;return this.then(function(r){return t.resolve(e()).then(function(){return r})},function(r){return t.resolve(e()).then(function(){throw r})})})}var Gh=/^(\[[^\]]*\]|\{[^}]*\}|%%[^%]*%%)$/,Hh=/^\s|\s$/,Kh=/example\.com/i,jh=["tfcd","npa","min_ad_duration","max_ad_duration","unviewed_position_start","impl","vad_type","gdpr","gdpr_consent","us_privacy"],qh=[{pattern:/\[RDID\]/gi,getValue:function(e){return e.deviceId}},{pattern:/\[IFA\]/gi,getValue:function(e){return e.deviceId}},{pattern:/\[ADVERTISING[_-]?ID(?:ENTIFIER)?\]/gi,getValue:function(e){return e.deviceId}},{pattern:/\[DEVICE[_-]?ID\]/gi,getValue:function(e){return e.deviceId}},{pattern:/\[IDTYPE\]/gi,getValue:function(e){return e.deviceIdType}},{pattern:/\{rdid\}/gi,getValue:function(e){return e.deviceId}},{pattern:/\{device[_-]?id\}/gi,getValue:function(e){return e.deviceId}},{pattern:/\{idtype\}/gi,getValue:function(e){return e.deviceIdType}},{pattern:/%%ADVERTISING_IDENTIFIER_PLAIN%%/gi,getValue:function(e){return e.deviceId}},{pattern:/%%ADVERTISING_ID_OPT_OUT%%/gi,getValue:function(e){return null!=e.limitAdTracking?e.limitAdTracking?"1":"0":void 0}},{pattern:/%%ADVERTISING_ID_TYPE%%/gi,getValue:function(e){return e.deviceIdType}},{pattern:/%%ADVERTISING_ID%%/gi,getValue:function(e){return e.deviceId}},{pattern:/%%LIMIT_AD_TRACKING%%/gi,getValue:function(e){return null!=e.limitAdTracking?e.limitAdTracking?"1":"0":void 0}},{pattern:/%%SESSION_ID%%/gi,getValue:function(e){return e.sessionId}},{pattern:/%%CORRELATOR%%/gi,getValue:function(e){return e.correlator}}];function Wh(e){if(null==e)return!0;var t=e.trim();return!t||(!!Gh.test(t)||/^(unknown|null|undefined|none|n\/a|\$\{[^}]+\})$/i.test(t))}function Yh(){var e,t;if("undefined"!=typeof crypto&&crypto.getRandomValues)try{var r=new Uint32Array(2);crypto.getRandomValues(r);var i=2097152*(null!==(e=r[0])&&void 0!==e?e:0)+(2097151&(null!==(t=r[1])&&void 0!==t?t:0));if(i>0)return String(i)}catch(e){}return String(Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)+1)}function zh(e,t){var r,i,n=null===(r=t.deviceId)||void 0===r?void 0:r.trim(),a=(null===(i=t.deviceIdType)||void 0===i?void 0:i.trim())||lh(),s=e.get("rdid"),o=e.get("idtype"),l=e.get("is_lat"),u=null!=t.limitAdTracking?t.limitAdTracking?"1":"0":void 0;if(n)return e.set("rdid",n),e.set("idtype",a||o||"aaid"),void e.set("is_lat",null!=u?u:Wh(l)?"0":l);if(!t.isCtv)return e.delete("rdid"),e.delete("idtype"),void e.delete("is_lat");var c=Boolean(s&&!Wh(s)),d=Boolean(o&&!Wh(o));return c&&d&&a&&!function(e,t){if(!e||!t)return!1;var r=e.toLowerCase(),i=t.toLowerCase();return r===i||Jd.has(r)&&Jd.has(i)}(o,a)?(e.delete("rdid"),e.delete("idtype"),void e.delete("is_lat")):c?(Wh(o)&&a&&e.set("idtype",a),void(Wh(l)&&e.set("is_lat",null!=u?u:"0"))):(e.delete("rdid"),e.delete("idtype"),void e.delete("is_lat"))}function Xh(e,t){var r,i,n,a,s=[];if(e.forEach(function(e,t){t&&!Hh.test(t)||s.push(t)}),t&&t.includes("&"))try{for(var o=F(t.split("&").slice(1)),l=o.next();!l.done;l=o.next()){var u=l.value,c=u.replace(/^\s+/,"");c&&s.push(u," ".concat(c),c)}}catch(e){r={error:e}}finally{try{l&&!l.done&&(i=o.return)&&i.call(o)}finally{if(r)throw r.error}}try{for(var d=F(new Set(s)),h=d.next();!h.done;h=d.next()){var f=h.value;f&&e.delete(f)}}catch(e){n={error:e}}finally{try{h&&!h.done&&(a=d.return)&&a.call(d)}finally{if(n)throw n.error}}}function Qh(e){if(!e)return e;try{var t=new URL(e),r=t.searchParams.get("an");if(null!==r){var i=[];if(t.searchParams.forEach(function(e,t){t&&Hh.test(t)&&i.push(t.trim())}),i.length>0){var n=B([r.replace(/\s+$/,"")],N(i),!1).filter(Boolean).join(" & ");return t.searchParams.forEach(function(e,r){r&&Hh.test(r)&&t.searchParams.delete(r)}),t.searchParams.set("an",n),t.toString().replace(/([?&]an=)([^&]*)/,function(e,t,r){return t+r.replace(/\+/g,"%20")})}}return Xh(t.searchParams),t.toString()}catch(t){return e}}function $h(e,t){var r,i,n,a,s,o=function(e,t){var r,i,n=e;try{for(var a=F(qh),s=a.next();!s.done;s=a.next()){var o=s.value,l=o.pattern,u=(0,o.getValue)(t);null!=u&&""!==u&&(n=n.replace(l,encodeURIComponent(u)))}}catch(e){r={error:e}}finally{try{s&&!s.done&&(i=a.return)&&i.call(a)}finally{if(r)throw r.error}}return n}(e,t);try{s=new URL(Qh(o))}catch(e){return function(e,t){var r=/([?&])correlator=([^&]*)/;if(r.test(e))return e.replace(r,"$1correlator=".concat(t));var i=e.includes("?")?"&":"?";return"".concat(e).concat(i,"correlator=").concat(t)}(o,t.correlator)}var l=s.searchParams;if(Xh(l),l.set("correlator",t.correlator),l.set("scor",t.streamCorrelator),t.isCtv)try{for(var u=F(jh),c=u.next();!c.done;c=u.next()){var d=c.value;l.delete(d)}}catch(e){r={error:e}}finally{try{c&&!c.done&&(i=u.return)&&i.call(u)}finally{if(r)throw r.error}}null!=t.pod&&l.set("pod",String(t.pod)),l.delete("ppos"),l.delete("lip"),null!=t.podMinDurationMs&&l.set("pmnd",String(Math.max(0,Math.round(t.podMinDurationMs)))),null!=t.podMaxDurationMs&&l.set("pmxd",String(Math.max(0,Math.round(t.podMaxDurationMs)))),null!=t.podMaxAds&&l.set("pmad",String(Math.max(1,Math.round(t.podMaxAds))));var h=l.get("url")||"";if(Kh.test(h)&&(l.delete("url"),l.delete("description_url")),!t.isCtv&&t.pageUrl&&(Wh(l.get("url"))&&l.set("url",t.pageUrl),Wh(l.get("description_url"))&&l.set("description_url",l.get("url")||t.pageUrl)),t.isCtv||(l.delete("an"),l.delete("msid"),l.delete("sid")),null!=t.adWillPlayMuted&&l.set("vpmute",t.adWillPlayMuted?"1":"0"),null!=t.adWillAutoPlay&&l.set("vpa",t.adWillAutoPlay?"auto":"click"),t.sessionId&&l.set("sid",t.sessionId),null!=t.deviceTypeHint?l.set("dth",String(t.deviceTypeHint)):t.isCtv&&l.set("dth","5"),zh(l,t),!t.isCtv){var f=t.consent;null!=(null==f?void 0:f.gdpr)&&l.set("gdpr",f.gdpr),null!=(null==f?void 0:f.gdprConsent)&&l.set("gdpr_consent",f.gdprConsent),null!=(null==f?void 0:f.usPrivacy)&&l.set("us_privacy",f.usPrivacy)}t.adTest&&l.set("adtest","on"),t.programTitle&&l.set("ct_ti",t.programTitle),t.channelName&&l.set("ct_ch",t.channelName);var v=[];l.forEach(function(e,t){Wh(e)&&v.push(t)});try{for(var g=F(v),p=g.next();!p.done;p=g.next()){d=p.value;l.delete(d)}}catch(e){n={error:e}}finally{try{p&&!p.done&&(a=g.return)&&a.call(g)}finally{if(n)throw n.error}}return Xh(l),s.toString()}function Jh(e){var t=parseFloat(e.trim());if(!Number.isNaN(t))return t;var r=e.match(/(?:^|[,\s])DURATION\s*=\s*([0-9.]+)/i)||e.match(/Duration\s*=\s*([0-9.]+)/i);if(r&&null!=r[1]){var i=r[1],n=parseFloat(i);return Number.isNaN(n)?void 0:n}}function Zh(e){var t={},r=e.match(/Elapsed\s*=\s*([0-9.]+)/i),i=e.match(/Duration\s*=\s*([0-9.]+)/i);if(r&&null!=r[1]){var n=parseFloat(r[1]);Number.isNaN(n)||(t.elapsed=n)}if(i&&null!=i[1]){var a=parseFloat(i[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}function ef(e){for(var t,r,i,n,a={},s=/([A-Z0-9-]+)=(("[^"]*")|([^",]*))(?:,|$)/gi;null!==(n=s.exec(e));){var o=null!==(t=n[1])&&void 0!==t?t:"",l=null!==(i=null!==(r=n[3])&&void 0!==r?r:n[4])&&void 0!==i?i:"";l.startsWith('"')&&l.endsWith('"')&&(l=l.slice(1,-1)),o&&(a[o]=l)}return a}function tf(e){if(null!=e){var t="string"==typeof e?parseFloat(e):Number(e);return Number.isNaN(t)?void 0:t}}function rf(e){var t,r,i=[null==e?void 0:e.start,null==e?void 0:e.startPTS];try{for(var n=F(i),a=n.next();!a.done;a=n.next()){var s=a.value;if("number"==typeof s&&Number.isFinite(s))return s}}catch(e){t={error:e}}finally{try{a&&!a.done&&(r=n.return)&&r.call(n)}finally{if(t)throw t.error}}}function nf(e){var t,r,i,n,a=function(e){try{if("string"==typeof e)return e;var t=new TextDecoder("utf-8",{fatal:!1}).decode(e);if(t&&/[\x20-\x7E]/.test(t))return t;for(var r="",i=0;i<e.length;i++)r+=String.fromCharCode(e[i]);return r}catch(e){return}}(e.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=Jh((null!==(t=s[1])&&void 0!==t?t:"").trim());return _(_(_({type:"start"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),void 0!==o?{durationSeconds:o}:{}),{raw:{id3:a}})}var l=a.match(/EXT-X-CUE-OUT-CONT:([^\r\n]*)/i);if(l){var u=Zh((null!==(r=l[1])&&void 0!==r?r:"").trim());return _(_(_({type:"progress"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),void 0!==(null==u?void 0:u.duration)?{durationSeconds:u.duration}:{}),{raw:{id3:a}})}if(a.match(/EXT-X-CUE-IN\b/i)||a.match(/CUE-IN\b/i))return _(_({type:"end"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),{raw:{id3:a}});var c=a.match(/EXT-X-DATERANGE:([^\r\n]*)/i);if(c){var d=ef(null!==(i=c[1])&&void 0!==i?i:""),h="SCTE35-OUT"in d||void 0!==d["SCTE35-OUT"],f="SCTE35-IN"in d||void 0!==d["SCTE35-IN"],v=String(null!==(n=d.CLASS)&&void 0!==n?n:""),g=tf(d.DURATION);if(h||/com\.apple\.hls\.cue/i.test(v))return _(_(_({type:"start"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),void 0!==g?{durationSeconds:g}:{}),{raw:{id3:a,attrs:d}});if(f)return _(_({type:"end"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),{raw:{id3:a,attrs:d}})}if(/SCTE35-OUT/i.test(a))return _(_({type:"start"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),{raw:{id3:a}});if(/SCTE35-IN/i.test(a))return _(_({type:"end"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),{raw:{id3:a}});if(e.value instanceof Uint8Array){var p=mf(e.value);if(p)return p}}}function af(e,t){if(t){var r=e[0];if(null!=r){var i=1+r;return i<e.length?i:void 0}}}function sf(e,t){var r,i;return(15&(null!==(r=e[t+1])&&void 0!==r?r:0))<<8|(null!==(i=e[t+2])&&void 0!==i?i:0)}function of(e,t,r){var i,n,a,s,o=af(e,t);if(!(null==o||o+8>=e.length)&&0===e[o])for(var l=sf(e,o),u=Math.min(e.length,o+3+l),c=o+8;c+4<=u-4;c+=4){var d=(null!==(i=e[c])&&void 0!==i?i:0)<<8|(null!==(n=e[c+1])&&void 0!==n?n:0),h=(31&(null!==(a=e[c+2])&&void 0!==a?a:0))<<8|(null!==(s=e[c+3])&&void 0!==s?s:0);0!==d&&r.add(h)}}function lf(e,t,r){for(var i,n,a,s,o,l,u=t;u+2<=r;){var c=null!==(i=e[u])&&void 0!==i?i:0,d=null!==(n=e[u+1])&&void 0!==n?n:0,h=u+2,f=h+d;if(f>r)return!1;var v=d>=4?String.fromCharCode(null!==(a=e[h])&&void 0!==a?a:0,null!==(s=e[h+1])&&void 0!==s?s:0,null!==(o=e[h+2])&&void 0!==o?o:0,null!==(l=e[h+3])&&void 0!==l?l:0):"";if(138===c||"CUEI"===v||"SCTE"===v)return!0;u=f}return!1}function uf(e,t,r){var i,n,a,s,o,l,u,c=af(e,t);if(!(null==c||c+12>=e.length)&&2===e[c])for(var d=sf(e,c),h=Math.min(e.length,c+3+d),f=c+12+((15&(null!==(i=e[c+10])&&void 0!==i?i:0))<<8|(null!==(n=e[c+11])&&void 0!==n?n:0));f+5<=h-4;){var v=null!==(a=e[f])&&void 0!==a?a:0,g=(31&(null!==(s=e[f+1])&&void 0!==s?s:0))<<8|(null!==(o=e[f+2])&&void 0!==o?o:0),p=(15&(null!==(l=e[f+3])&&void 0!==l?l:0))<<8|(null!==(u=e[f+4])&&void 0!==u?u:0),m=f+5,y=Math.min(m+p,h-4);(134===v||6===v&&lf(e,m,y))&&r.add(g),f=m+p}}function cf(e,t,r){if(252===e[0]&&!function(e,t){for(var r,i=0,n=0;n<e.length;n++)i=31*i+(null!==(r=e[n])&&void 0!==r?r:0)>>>0;var a="".concat(e.length,":").concat(i);if(t.has(a))return!0;if(t.add(a),t.size>200){var s=t.values().next().value;s&&t.delete(s)}return!1}(e,r)){var i=mf(e);i&&(i.raw=_(_({},"object"===R(i.raw)&&i.raw?i.raw:{}),{source:"ts-packet"}),t.push(i))}}function df(e,t,r,i,n){var a,s=r.get(e);if(s){for(var o=0;o<t.length&&s.bytes.length<s.expectedLength;o++)s.bytes.push(null!==(a=t[o])&&void 0!==a?a:0);s.bytes.length>=s.expectedLength&&(r.delete(e),cf(new Uint8Array(s.bytes),i,n))}}function hf(e,t,r,i,n,a){var s;if(0!==t.length){var o=0;if(r){var l=null!==(s=t[0])&&void 0!==s?s:0;for(i.get(e)&&l>0&&df(e,t.subarray(1,Math.min(1+l,t.length)),i,n,a),i.delete(e),o=1+l;o+3<=t.length;){var u=t[o];if(null==u||255===u)return;var c=sf(t,o),d=3+c;if(c<=0||d<=3)return;if(!(o+d<=t.length))return void i.set(e,{bytes:Array.from(t.subarray(o)),expectedLength:d});cf(t.subarray(o,o+d),n,a),o+=d}}else df(e,t,i,n,a)}}function ff(e,t,r,i){var n=function(e){var t,r;try{for(var i=F([188,192,204]),n=i.next();!n.done;n=i.next())for(var a=n.value,s=192===a?4:0,o=0;o<a;o++){for(var l=0,u=o;u+s<e.length&&l<5&&71===e[u+s];u+=a)l++;if(l>=2)return{offset:o,packetSize:a,tsPayloadOffset:s}}}catch(e){t={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}}(e);if(!n)return[];for(var a=[],s=new Map,o=n.offset;o+n.packetSize<=e.length;o+=n.packetSize){var l=o+n.tsPayloadOffset;if(71===e[l]){var u=e[l+1],c=e[l+2],d=e[l+3];if(!(null==u||null==c||null==d||128&u)){var h=!!(64&u),f=(31&u)<<8|c,v=d>>4&3;if(1===v||3===v){var g=l+4;if(3===v){var p=e[g];if(null==p)continue;g+=1+p}var m=Math.min(l+188,e.length);if(!(g>=m||g>=e.length)){var y=e.subarray(g,m);0===f?of(y,h,r):r.has(f)?uf(y,h,t):t.has(f)&&hf(f,y,h,s,a,i)}}}}}return a}var vf=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 r=8-this.bitPos,i=Math.min(e,r);t=t<<i|this.buf[this.bytePos]>>r-i&((1<<i)-1&255),this.bitPos+=i,this.bitPos>=8&&(this.bitPos=0,this.bytePos+=1),e-=i}return t>>>0},e.prototype.skipBits=function(e){this.readBits(e)},Object.defineProperty(e.prototype,"bytePosition",{get:function(){return 0===this.bitPos?this.bytePos:this.bytePos+1},enumerable:!1,configurable:!0}),e}();function gf(e,t){if(1===e.readBits(1))return e.readBits(6),(4294967296*e.readBits(1)+e.readBits(32)+t)%8589934592/9e4;e.readBits(7)}function pf(e){var t,r,i,n,a,s,o,l,u,c,d,h,f,v,g,p,m,y;if(!(e.length<11)&&"CUEI"===String.fromCharCode(null!==(t=e[0])&&void 0!==t?t:0,null!==(r=e[1])&&void 0!==r?r:0,null!==(i=e[2])&&void 0!==i?i:0,null!==(n=e[3])&&void 0!==n?n:0)){var k=16777216*(null!==(a=e[4])&&void 0!==a?a:0)+((null!==(s=e[5])&&void 0!==s?s:0)<<16)+((null!==(o=e[6])&&void 0!==o?o:0)<<8)+(null!==(l=e[7])&&void 0!==l?l:0);if(!!!(128&(null!==(u=e[8])&&void 0!==u?u:0))){var E=null!==(c=e[9])&&void 0!==c?c:0,S=!!(64&E),T=10;if(!!!(128&E))if((T+=1+6*(null!==(d=e[T])&&void 0!==d?d:0))>e.length)return;var A=void 0;if(S){if(T+5>e.length)return;A=(4294967296*(null!==(h=e[T])&&void 0!==h?h:0)+16777216*(null!==(f=e[T+1])&&void 0!==f?f:0)+((null!==(v=e[T+2])&&void 0!==v?v:0)<<16)+((null!==(g=e[T+3])&&void 0!==g?g:0)<<8)+(null!==(p=e[T+4])&&void 0!==p?p:0))/9e4,T+=5}if(!(T+2>e.length))if(T+=1,!((T+=1+(null!==(m=e[T])&&void 0!==m?m:0))>=e.length)){var b=function(e){switch(e){case 16:case 34:case 48:case 50:case 52:case 54:return"start";case 17:case 35:case 49:case 51:case 53:case 55:return"end";default:return}}(null!==(y=e[T])&&void 0!==y?y:0);if(b)return _(_({type:b},void 0!==A?{durationSeconds:A}:{}),{segmentationEventId:k})}}}}function mf(e){var t=new vf(e);if(252===t.readBits(8)){t.readBits(1),t.readBits(1),t.readBits(2);var r=t.readBits(12);if(!(r<=0||e.length<3+r)){t.readBits(8),t.readBits(1),t.readBits(6);var i=4294967296*t.readBits(1)+t.readBits(32);t.readBits(8),t.readBits(12);var n,a=t.readBits(12),s=t.readBits(8),o=void 0,l=void 0,u=void 0,c=t.bytePosition;if(5===s){u=t.readBits(32);var d=1===t.readBits(1);if(t.readBits(7),d)return;var h=1===t.readBits(1),f=1===t.readBits(1),v=1===t.readBits(1),g=1===t.readBits(1);if(t.readBits(4),n=h?"start":"end",f&&!g)l=gf(t,i);else if(!f)for(var p=t.readBits(8),m=0;m<p;m++)if(t.readBits(8),!g){var y=gf(t,i);void 0===l&&(l=y)}if(v)t.readBits(6),t.readBits(1),o=(4294967296*t.readBits(1)+t.readBits(32))/9e4;t.readBits(16),t.readBits(8),t.readBits(8)}else{if(6!==s)return;l=gf(t,i)}var k=function(e,t){var r,i,n,a;if(!(t+2>e.length))for(var s=(null!==(r=e[t])&&void 0!==r?r:0)<<8|(null!==(i=e[t+1])&&void 0!==i?i:0),o=t+2,l=Math.min(e.length,o+s);o+2<=l;){var u=null!==(n=e[o])&&void 0!==n?n:0,c=o+2,d=c+(null!==(a=e[o+1])&&void 0!==a?a:0);if(d>l)return;if(2===u){var h=pf(e.subarray(c,d));if(h)return h}o=d}}(e,4095===a?t.bytePosition:c+a);if(k&&(n=k.type,void 0===o&&(o=k.durationSeconds)),n)return _(_(_({type:n},void 0!==l?{ptsSeconds:l}:{}),void 0!==o?{durationSeconds:o}:{}),{raw:_(_({splice_command_type:s},void 0!==u?{splice_event_id:u}:{}),void 0!==(null==k?void 0:k.segmentationEventId)?{segmentation_event_id:k.segmentationEventId}:{})})}}}var yf=function(){function e(e,t){this.pendingScte35Cues=new Map,this.recentScte35CueKeys=new Map,this.recentScte35CueLimit=200,this.tsScte35Pids=new Set,this.pmtPids=new Set,this.processedTsScte35Sections=new Set,this.debug=e,this.callbacks=t}return Object.defineProperty(e.prototype,"pendingScte35CueKey",{get:function(){return this.pendingScte35CueKeyValue},set:function(e){this.pendingScte35CueKeyValue=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"activeScte35BreakKey",{get:function(){return this.activeScte35BreakKeyValue},set:function(e){this.activeScte35BreakKeyValue=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"scheduledScte35BreakKey",{get:function(){return this.scheduledScte35BreakKeyValue},set:function(e){this.scheduledScte35BreakKeyValue=e},enumerable:!1,configurable:!0}),e.prototype.createScte35CueContext=function(e,t,r){var i={source:e,readiness:t};"number"==typeof(null==r?void 0:r.sn)&&(i.fragmentSn=r.sn);var n=rf(r);return void 0!==n&&(i.fragmentStartSeconds=n),i},e.prototype.onScte35Cue=function(e,t){var r=this.createScte35Cue(e,t),i=this.getPendingScte35CueKey(r);if("early"===t.readiness)return this.pendingScte35Cues.set(i,r),this.trimRecentScte35CueMaps(),void("start"===e.type&&this.callbacks.onEarlyStartCue(e,t.fragmentSn,r.key));"end"!==e.type||this.shouldAcceptScte35EndCue(r)?"start"===e.type&&this.hasRecentlyHandledScte35Cue(r)?this.debug&&console.log("[StormcloudVideoPlayer] Ignoring duplicate SCTE-35 start cue",{key:r.key,source:r.source}):(this.pendingScte35Cues.delete(i),this.markScte35CueHandled(r),this.callbacks.onPlaybackCue(e,r.key)):this.debug&&console.log("[StormcloudVideoPlayer] Ignoring SCTE-35 end cue",{key:r.key,activeScte35BreakKey:this.activeScte35BreakKeyValue,inAdBreak:this.callbacks.isInAdBreak(),source:r.source})},e.prototype.activatePendingScte35CuesForFragment=function(e){var t=this,r="number"==typeof(null==e?void 0:e.sn)?e.sn:void 0;void 0!==r&&Array.from(this.pendingScte35Cues.entries()).filter(function(e){return N(e,2)[1].fragmentSn===r}).forEach(function(i){var n,a=N(i,2),s=a[0],o=a[1];t.pendingScte35Cues.delete(s);var l={source:o.source,readiness:"playback"};l.fragmentSn=r;var u=null!==(n=o.fragmentStartSeconds)&&void 0!==n?n:rf(e);void 0!==u&&(l.fragmentStartSeconds=u),t.onScte35Cue(o.marker,l)})},e.prototype.createScte35Cue=function(e,t){var r={marker:e,source:t.source,readiness:t.readiness,key:this.getScte35CueKey(e,t)};return void 0!==t.fragmentSn&&(r.fragmentSn=t.fragmentSn),void 0!==t.fragmentStartSeconds&&(r.fragmentStartSeconds=t.fragmentStartSeconds),r},e.prototype.getScte35CueKey=function(e,t){var r,i,n,a=this.getScte35MarkerRaw(e),s=this.toIdentityString(null==a?void 0:a.splice_event_id);if(s)return"splice:".concat(s);var o=this.toIdentityString(null==a?void 0:a.segmentation_event_id);if(o)return"segmentation:".concat(o);var l=this.toIdentityString(null===(r=null==a?void 0:a.attrs)||void 0===r?void 0:r.ID);if(l)return"daterange:".concat(l);var u=this.toIdentityString(null===(i=null==a?void 0:a.attrs)||void 0===i?void 0:i["SCTE35-OUT"])||this.toIdentityString(null===(n=null==a?void 0:a.attrs)||void 0===n?void 0:n["SCTE35-IN"]);return u?"daterange-scte:".concat(u):"number"==typeof e.ptsSeconds&&Number.isFinite(e.ptsSeconds)?"pts:".concat(Math.round(2*e.ptsSeconds)/2):void 0!==t.fragmentSn?"fragment:".concat(t.fragmentSn):"".concat(t.source,":wallclock:").concat(Math.floor(Date.now()/1e3))},e.prototype.getPendingScte35CueKey=function(e){return"".concat(e.marker.type,":").concat(e.key,":").concat(void 0!==e.fragmentSn?e.fragmentSn:"unknown")},e.prototype.getScte35MarkerRaw=function(e){return"object"===R(e.raw)&&null!==e.raw?e.raw:{}},e.prototype.toIdentityString=function(e){return"number"==typeof e&&Number.isFinite(e)?String(e):"string"==typeof e&&e.trim().length>0?e.trim():void 0},e.prototype.isStrongScte35CueKey=function(e){return!(!e||!(e.startsWith("splice:")||e.startsWith("segmentation:")||e.startsWith("daterange:")||e.startsWith("daterange-scte:")))},e.prototype.hasRecentlyHandledScte35Cue=function(e){if(this.activeScte35BreakKeyValue===e.key||this.scheduledScte35BreakKeyValue===e.key)return!0;var t="".concat(e.marker.type,":").concat(e.key);return this.recentScte35CueKeys.has(t)},e.prototype.markScte35CueHandled=function(e){this.recentScte35CueKeys.set("".concat(e.marker.type,":").concat(e.key),Date.now()),this.trimRecentScte35CueMaps()},e.prototype.trimRecentScte35CueMaps=function(){for(;this.recentScte35CueKeys.size>this.recentScte35CueLimit;){if(!(e=this.recentScte35CueKeys.keys().next().value))break;this.recentScte35CueKeys.delete(e)}for(;this.pendingScte35Cues.size>this.recentScte35CueLimit;){var e;if(!(e=this.pendingScte35Cues.keys().next().value))break;this.pendingScte35Cues.delete(e)}},e.prototype.shouldAcceptScte35EndCue=function(e){return!!this.callbacks.isInAdBreak()&&(!this.isStrongScte35CueKey(this.activeScte35BreakKeyValue)||!this.isStrongScte35CueKey(e.key)||this.activeScte35BreakKeyValue===e.key)},e}(),kf=function(){function e(e,t){this.vmapBreaks=[],this.consumedVmapBreakIds=new Set,this.streamCorrelator=Yh(),this.viewCorrelator=Yh(),this.consentSignals={},this.podCounter=0,this.podAssignedByPrefetch=!1,this.lastHeartbeatTime=0,this.defaultPodMaxAds=6,this.defaultPodMaxDurationMs=12e4,this.config=e,this.video=t}return Object.defineProperty(e.prototype,"debug",{get:function(){return!!this.config.debugAdTiming},enumerable:!1,configurable:!0}),e.prototype.isVmapEnabled=function(){var e;return!(!this.config.isVmap||!(null===(e=this.config.vmapUrl)||void 0===e?void 0:e.trim()))},e.prototype.fetchAdConfiguration=function(){return x(this,void 0,void 0,function(){var e,t,r,i,n,a,s,o,l,u,c,d,h,f,v,g;return O(this,function(p){switch(p.label){case 0:return this.isVmapEnabled()?[4,this.fetchAndParseVmap(this.config.vmapUrl)]:[3,2];case 1:return p.sent(),this.debug&&console.log("[StormcloudVideoPlayer] VMAP mode enabled"),[2];case 2:return e=this.config.vastMode||"default",this.debug&&console.log("[StormcloudVideoPlayer] VAST mode:",e),"adstorm"===e?this.config.licenseKey?(t="https://adstorm.co/api-adstorm-dev/adstorm/vast/".concat(this.config.licenseKey),this.apiVastTagUrl=t,this.debug&&console.log("[StormcloudVideoPlayer] Using AdStorm VAST endpoint (adstorm mode):",t),[2]):(this.debug&&console.warn("[StormcloudVideoPlayer] AdStorm mode requires a license key"),[2]):this.config.vastTagUrl?(this.apiVastTagUrl=Qh(this.config.vastTagUrl),this.debug&&console.log("[StormcloudVideoPlayer] Using custom VAST tag URL:",this.apiVastTagUrl),[2]):(r="https://adstorm.co/api-adstorm-dev/adstorm/ads/web",this.debug&&console.log("[StormcloudVideoPlayer] Fetching ad configuration from:",r),i={},this.config.licenseKey&&(i.Authorization="Bearer ".concat(this.config.licenseKey)),[4,fetch(r,{headers:i})]);case 3:return(n=p.sent()).ok?[4,n.json()]:(this.debug&&console.warn("[StormcloudVideoPlayer] Failed to fetch ad configuration: ".concat(n.status)),[2]);case 4:if(a=p.sent(),s=null===(d=null===(c=null===(u=a.response)||void 0===u?void 0:u.ima)||void 0===c?void 0:c["publisherdesk.ima"])||void 0===d?void 0:d.payload){o=s;try{o=decodeURIComponent(s)}catch(e){console.warn("[StormcloudVideoPlayer] imaPayload was not URI-encoded; using as-is:",s)}console.log("[StormcloudVideoPlayer] Raw VAST tag URL (from API):",o),this.apiVastTagUrl=Qh(o),this.debug&&console.log("[StormcloudVideoPlayer] Normalized VAST tag URL:",this.apiVastTagUrl)}else this.debug&&console.warn("[StormcloudVideoPlayer] No VAST tag URL found in /ads/web response");return null!=(l=null===(g=null===(v=null===(f=null===(h=a.response)||void 0===h?void 0:h.options)||void 0===f?void 0:f.vast)||void 0===v?void 0:v.cue_tones)||void 0===g?void 0:g.number_ads)&&l>0&&(this.apiNumberAds=l,this.debug&&console.log("[StormcloudVideoPlayer] Number of ads per break from API:",this.apiNumberAds)),[2]}})})},e.prototype.fetchAndParseVmap=function(e){return x(this,void 0,void 0,function(){var t,r,i;return O(this,function(n){switch(n.label){case 0:if(!e.trim())return[2];n.label=1;case 1:return n.trys.push([1,4,,5]),[4,fetch(e)];case 2:if(!(t=n.sent()).ok)throw new Error("Failed to fetch VMAP (".concat(t.status,")"));return[4,t.text()];case 3:return r=n.sent(),this.vmapBreaks=this.parseVmapToBreaks(r),this.consumedVmapBreakIds.clear(),this.debug&&console.log("[StormcloudVideoPlayer] Loaded ".concat(this.vmapBreaks.length," VMAP ad break(s) from:"),e),[3,5];case 4:return i=n.sent(),this.vmapBreaks=[],this.consumedVmapBreakIds.clear(),this.debug&&console.warn("[StormcloudVideoPlayer] Failed to load VMAP:",i),[3,5];case 5:return[2]}})})},e.prototype.parseVmapToBreaks=function(e){var t=this;if("undefined"==typeof DOMParser)return[];var r=(new DOMParser).parseFromString(e,"application/xml");if(r.querySelector("parsererror"))return this.debug&&console.warn("[StormcloudVideoPlayer] Invalid VMAP XML received"),[];var i="http://www.iab.net/videosuite/vmap",n=Array.from(r.getElementsByTagNameNS(i,"AdBreak"));0===n.length&&(n=Array.from(r.querySelectorAll("AdBreak, vmap\\:AdBreak"))),0===n.length&&(n=Array.from(r.getElementsByTagName("*")).filter(function(e){return"AdBreak"===e.localName}));var a=[];return n.forEach(function(e,r){var n,s=(e.getAttribute("timeOffset")||"").trim(),o=t.parseVmapTimeOffsetToMs(s);if(null!=o){var l=e.getElementsByTagNameNS(i,"AdTagURI")[0];l||(l=null!==(n=e.querySelector("AdTagURI, vmap\\:AdTagURI"))&&void 0!==n?n:void 0);var u=((null==l?void 0:l.textContent)||"").trim();if(u){var c=e.getAttribute("breakId")||"vmap-break-".concat(r,"-").concat(s||"unknown");a.push({id:c,startTimeMs:o,vastTagUrl:u})}}}),a.sort(function(e,t){return(e.startTimeMs<0?Number.MAX_SAFE_INTEGER:e.startTimeMs)-(t.startTimeMs<0?Number.MAX_SAFE_INTEGER:t.startTimeMs)}),a},e.prototype.parseVmapTimeOffsetToMs=function(e){if(e){var t=e.trim().toLowerCase();if("start"===t)return 0;if("end"===t)return-1;var r=e.match(/^(\d{1,2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?$/);if(r){var i=N(r,5),n=i[1],a=i[2],s=i[3],o=i[4],l=void 0===o?"0":o;return 1e3*(3600*Number(n)+60*Number(a)+Number(s))+Number(l.padEnd(3,"0").slice(0,3))}var u=e.match(/^(\d+(?:\.\d+)?)%$/);if(u){var c=Number(u[1])/100,d=this.video.duration;return Number.isFinite(d)&&d>0?Math.floor(1e3*d*c):void 0}}},e.prototype.getAdBreakKey=function(e){return e.id?e.id:"".concat(e.startTimeMs,"-").concat(e.vastTagUrl||"")},e.prototype.resolveBreakStartMs=function(e){if(e.startTimeMs>=0)return e.startTimeMs;if(-1===e.startTimeMs){var t=this.video.duration;if(Number.isFinite(t)&&t>0)return Math.floor(1e3*t)}},e.prototype.findCurrentOrNextBreak=function(e){var t,r,i,n,a,s=this.vmapBreaks,o=null!==(i=this.config.driftToleranceMs)&&void 0!==i?i:1e3;try{for(var l=F(s),u=l.next();!u.done;u=l.next()){var c=u.value;if(!this.consumedVmapBreakIds.has(this.getAdBreakKey(c))){var d=this.resolveBreakStartMs(c);null!=d&&d<=e+o&&(null==a||d>(null!==(n=this.resolveBreakStartMs(a))&&void 0!==n?n:0))&&(a=c)}}}catch(e){t={error:e}}finally{try{u&&!u.done&&(r=l.return)&&r.call(l)}finally{if(t)throw t.error}}return a},e.prototype.findBreakForTime=function(e){var t,r,i=this.vmapBreaks;try{for(var n=F(i),a=n.next();!a.done;a=n.next()){var s=a.value;if(!this.consumedVmapBreakIds.has(this.getAdBreakKey(s))){var o=this.resolveBreakStartMs(s);if(null!=o)if(s.durationMs){var l=o+s.durationMs;if(e>=o&&e<l)return s}else if(e>=o)return s}}}catch(e){t={error:e}}finally{try{a&&!a.done&&(r=n.return)&&r.call(n)}finally{if(t)throw t.error}}},e.prototype.selectVastTagsForBreak=function(e){if(e&&e.vastTagUrl)return e.vastTagUrl.includes(",")?e.vastTagUrl.split(",").map(function(e){return e.trim()}).filter(function(e){return e.length>0}):[e.vastTagUrl]},e.prototype.beginNewAdPod=function(){this.podCounter++},e.prototype.resolvePodParams=function(e){var t=null!=e&&e>0?e:null!=this.config.podMaxDurationMs&&this.config.podMaxDurationMs>0?this.config.podMaxDurationMs:this.defaultPodMaxDurationMs;return{maxAds:this.config.podMaxAds&&this.config.podMaxAds>0?this.config.podMaxAds:this.apiNumberAds&&this.apiNumberAds>0?this.apiNumberAds:this.defaultPodMaxAds,minDurationMs:this.config.podExactDuration&&null!=t?t:0,maxDurationMs:t}},e.prototype.getPalDescriptionUrl=function(){if(this.apiVastTagUrl)try{var e=new URL(this.apiVastTagUrl).searchParams;return e.get("description_url")||e.get("url")||void 0}catch(e){return}},e.prototype.generatePodVastUrl=function(e,t,r,i,n){var a,s=n?r.getOriginalMutedState():this.video.muted,o=Zd(!!this.config.ctvAdRequest),l=$h(e,_(_(_({correlator:this.viewCorrelator,streamCorrelator:this.streamCorrelator,pod:this.podCounter>0?this.podCounter:void 0,podMaxAds:t.maxAds,podMinDurationMs:t.minDurationMs,podMaxDurationMs:t.maxDurationMs,isCtv:o.isCtv,pageUrl:o.isCtv||"undefined"==typeof window?void 0:Od(window.location.href),adWillPlayMuted:s,adWillAutoPlay:!!this.config.autoplay,sessionId:o.isCtv||!1!==this.consentSignals.storageAllowed?o.sessionId:void 0,deviceId:o.deviceId,deviceIdType:o.deviceIdType,limitAdTracking:o.limitAdTracking,deviceTypeHint:o.deviceTypeHint,adTest:this.config.adTest},this.config.programTitle?{programTitle:this.config.programTitle}:{}),this.config.channelName?{channelName:this.config.channelName}:{}),{consent:this.consentSignals})),u=i.injectNonce(l);return console.log("[StormcloudVideoPlayer] Resolved optimized-pod request URL (pod=".concat(this.podCounter,", pmad=").concat(t.maxAds,", pmnd=").concat(t.minDurationMs,", pmxd=").concat(null!==(a=t.maxDurationMs)&&void 0!==a?a:"?","):"),u),u},e.prototype.initializeTracking=function(){var e=this;Oh(this.config.licenseKey,Ph(this.config)).then(function(){e.heartbeatInterval=window.setInterval(function(){e.sendHeartbeatIfNeeded()},5e3)}).catch(function(t){e.debug&&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,Uh(this.config.licenseKey,Ph(this.config)).catch(function(t){e.debug&&console.warn("[StormcloudVideoPlayer] Failed to send heartbeat:",t)}))},e.prototype.destroyTracking=function(){this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=void 0)},e}(),Ef=function(){function e(e,t,r){this.adRequestWatchdogToken=null,this.adFailsafeToken=null,this.ptsDriftEmaMs=0,this.adBreakPlayedDurationMs=0,this.adBreakEpoch=0,this.adRequestTokenCounter=0,this.activeAdRequestToken=null,this.currentAdIndex=0,this.totalAdsInBreak=0,this.totalAdRequestsInBreak=0,this.maxTotalAdRequestsPerBreak=10,this.lastAdRequestTime=0,this.consecutiveFailures=0,this.maxConsecutiveFailures=5,this.minAdRequestIntervalMs=3e3,this.backoffBaseMs=1e3,this.maxBackoffMs=15e3,this.defaultMinRemainingMsToStartAd=4e3,this.failedVastUrls=new Set,this.temporaryFailureUrls=new Map,this.temporaryFailureCooldownMs=3e4,this.globalConsecutiveNoFills=0,this.globalNoFillThreshold=3,this.globalNoFillCooldownUntil=0,this.globalNoFillBackoffBaseMs=5e3,this.globalNoFillBackoffMaxMs=6e4,this.globalLastGamRequestTime=0,this.globalMinGamIntervalMs=3e3,this.config=e,this.video=t,this.callbacks=r}return Object.defineProperty(e.prototype,"debug",{get:function(){return!!this.config.debugAdTiming},enumerable:!1,configurable:!0}),e.prototype.scheduleAdStopCountdown=function(e){var t=this;this.clearAdStopTimer();var r=Math.max(0,Math.floor(e));0!==r?this.adStopTimerId=window.setTimeout(function(){t.ensureAdStoppedByTimer()},r):this.ensureAdStoppedByTimer()},e.prototype.clearAdStopTimer=function(){null!=this.adStopTimerId&&(clearTimeout(this.adStopTimerId),this.adStopTimerId=void 0)},e.prototype.ensureAdStoppedByTimer=function(){this.adStopTimerId=void 0,this.callbacks.onAdStopTimerFired()},e.prototype.scheduleAdStartIn=function(e,t,r){var i=this;void 0===t&&(t={type:"start"}),this.clearAdStartTimer();var n=Math.max(0,Math.floor(e));0!==n?this.adStartTimerId=window.setTimeout(function(){i.callbacks.onAdStartTimerFired(t,r)},n):this.callbacks.onAdStartTimerFired(t,r)},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.resolveScteBreakStartWallClockMs=function(e){var t=Date.now();if("number"!=typeof e.ptsSeconds)return t;var r=1e3*this.video.currentTime-this.ptsDriftEmaMs,i=1e3*e.ptsSeconds-r;return Number.isFinite(i)?t+Math.floor(i):t},e.prototype.setAdBreakDurationBoundary=function(e){this.expectedAdBreakDurationMs=e,null!=e&&null!=this.currentAdBreakStartWallClockMs?this.scteAdBreakEndWallClockMs=this.currentAdBreakStartWallClockMs+e:this.scteAdBreakEndWallClockMs=void 0},e.prototype.scheduleAdStopAtBreakBoundary=function(){null!=this.expectedAdBreakDurationMs&&this.scheduleAdStopCountdown(this.getWallClockRemainingAdMs())},e.prototype.getWallClockRemainingAdMs=function(){var e=this.getAdBreakEndWallClockMs();return null!=e?Math.max(0,e-Date.now()):0},e.prototype.getAdBreakEndWallClockMs=function(){return null!=this.scteAdBreakEndWallClockMs?this.scteAdBreakEndWallClockMs:null!=this.expectedAdBreakDurationMs&&null!=this.currentAdBreakStartWallClockMs?this.currentAdBreakStartWallClockMs+this.expectedAdBreakDurationMs:void 0},e.prototype.getDurationBudgetRemainingMs=function(){return null==this.expectedAdBreakDurationMs?0:Math.max(0,this.expectedAdBreakDurationMs-this.adBreakPlayedDurationMs)},e.prototype.getLoadedAdDurationMs=function(e){var t,r=null===(t=e.getLoadedAdDuration)||void 0===t?void 0:t.call(e);return null==r||r<=0?0:Math.round(1e3*r)},e.prototype.adFitsRemainingBudget=function(e){return e<=0||e<=this.getDurationBudgetRemainingMs()},e.prototype.logAdDurationDecision=function(e,t,r){var i,n;if(this.debug){var a=this.getDurationBudgetRemainingMs(),s=null!==(n=null===(i=r.getLoadedAdId)||void 0===i?void 0:i.call(r))&&void 0!==n?n:"unknown";e?console.log("[AD-DURATION] Accepted ad id=".concat(s,", duration=").concat(t,"ms, budget remaining after play=").concat(Math.max(0,a-t),"ms")):console.log("[AD-DURATION] Rejected ad id=".concat(s,", duration=").concat(t,"ms exceeds remaining budget=").concat(a,"ms — requesting another ad"))}},e.prototype.recordPlayedAdDuration=function(e){var t,r=this.getLoadedAdDurationMs(e);r<=0||(this.adBreakPlayedDurationMs+=r,this.debug&&console.log("[AD-DURATION] Played ".concat(r,"ms — total played=").concat(this.adBreakPlayedDurationMs,"ms / ").concat(null!==(t=this.expectedAdBreakDurationMs)&&void 0!==t?t:"?","ms")))},e.prototype.ensureLoadedAdFitsBudget=function(e){var t=this.getLoadedAdDurationMs(e),r=this.adFitsRemainingBudget(t);return this.logAdDurationDecision(r,t,e),r},e.prototype.rejectLoadedAdForDuration=function(e){try{e.destroy()}catch(e){}},e.prototype.markAdStarted=function(){this.currentAdIndex++,this.totalAdsInBreak=this.currentAdIndex,this.totalAdRequestsInBreak++,this.lastAdRequestTime=Date.now()},e.prototype.notePodAdStarted=function(){this.currentAdIndex++,this.totalAdsInBreak=this.currentAdIndex},e.prototype.getRemainingAdMs=function(){var e=this.getWallClockRemainingAdMs(),t=this.getDurationBudgetRemainingMs();return null==this.expectedAdBreakDurationMs?e:Math.min(e,t)},e.prototype.getMinRemainingMsToStartAd=function(){var e=this.config.minRemainingMsToStartAd;return"number"==typeof e&&e>=0?e:this.defaultMinRemainingMsToStartAd},e.prototype.hasTimeToStartAnotherAd=function(){var e=this.getMinRemainingMsToStartAd();return this.getWallClockRemainingAdMs()>e&&this.getDurationBudgetRemainingMs()>e},e.prototype.isTemporaryAdError=function(e){var t,r=(null===(t=null==e?void 0:e.message)||void 0===t?void 0:t.toLowerCase())||"";return!!(r.includes("no ads available")||r.includes("no fill")||r.includes("nofill"))||(!!r.includes("timeout")||(!(!r.includes("rate limit")&&!r.includes("too many requests"))||!!r.includes("ad playback error")))},e.prototype.isUrlInCooldown=function(e){var t=this.temporaryFailureUrls.get(e);return null!=t&&(!(Date.now()-t>=this.temporaryFailureCooldownMs)||(this.temporaryFailureUrls.delete(e),!1))},e.prototype.cleanupTemporaryFailures=function(){var e,t,r=Date.now();try{for(var i=F(this.temporaryFailureUrls),n=i.next();!n.done;n=i.next()){var a=N(n.value,2),s=a[0];r-a[1]>=this.temporaryFailureCooldownMs&&this.temporaryFailureUrls.delete(s)}}catch(t){e={error:t}}finally{try{n&&!n.done&&(t=i.return)&&t.call(i)}finally{if(e)throw e.error}}},e.prototype.isGamInCooldown=function(){return Date.now()<this.globalNoFillCooldownUntil},e.prototype.recordGamNoFill=function(){if(this.globalConsecutiveNoFills++,this.globalConsecutiveNoFills>=this.globalNoFillThreshold){var e=this.globalConsecutiveNoFills-this.globalNoFillThreshold,t=Math.min(this.globalNoFillBackoffBaseMs*Math.pow(2,e),this.globalNoFillBackoffMaxMs);this.globalNoFillCooldownUntil=Date.now()+t,this.debug&&console.log("[CIRCUIT-BREAKER] GAM cooldown activated: ".concat(t,"ms (").concat(this.globalConsecutiveNoFills," consecutive no-fills)"))}},e.prototype.resetGamNoFillCounter=function(){this.globalConsecutiveNoFills>0&&this.debug&&console.log("[CIRCUIT-BREAKER] Resetting no-fill counter (was ".concat(this.globalConsecutiveNoFills,")")),this.globalConsecutiveNoFills=0,this.globalNoFillCooldownUntil=0},e.prototype.enforceGlobalRateLimit=function(){return x(this,void 0,void 0,function(){var e,t,r;return O(this,function(i){switch(i.label){case 0:return e=Date.now(),(t=e-this.globalLastGamRequestTime)<this.globalMinGamIntervalMs?(r=this.globalMinGamIntervalMs-t,this.debug&&console.log("[RATE-LIMIT] Waiting ".concat(r,"ms before next GAM request")),[4,new Promise(function(e){return setTimeout(e,r)})]):[3,2];case 1:i.sent(),i.label=2;case 2:return this.globalLastGamRequestTime=Date.now(),[2]}})})},e.prototype.startAdRequestWatchdog=function(e){var t,r=this;this.clearAdRequestWatchdog();var i=null!==(t=this.config.adFailsafeTimeoutMs)&&void 0!==t?t:1e4;this.adRequestWatchdogToken=e,this.adRequestWatchdogId=window.setTimeout(function(){r.adRequestWatchdogToken===e&&(r.adRequestWatchdogId=void 0,r.adRequestWatchdogToken=null,r.activeAdRequestToken===e&&(r.activeAdRequestToken=null),r.logAdState("ad_request_timeout",{token:e,timeoutMs:i}),r.callbacks.onWatchdogTimeout())},i),this.logAdState("ad_request_watchdog_started",{token:e,timeoutMs:i})},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,r=this;this.clearAdFailsafeTimer();var i=null!==(t=this.config.adFailsafeTimeoutMs)&&void 0!==t?t:1e4;this.adFailsafeToken=e,this.adFailsafeTimerId=window.setTimeout(function(){r.adFailsafeToken===e&&(r.adFailsafeTimerId=void 0,r.adFailsafeToken=null,r.activeAdRequestToken===e&&(r.activeAdRequestToken=null),r.logAdState("ad_failsafe_triggered",{token:e,failsafeMs:i,videoPaused:r.video.paused}),r.callbacks.onFailsafeTimeout())},i),this.logAdState("ad_failsafe_started",{token:e,failsafeMs:i})},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){if(void 0===t&&(t={}),this.debug){var r=this.callbacks.getAdState(),i=r.inAdBreak,n=r.showAds,a=r.adPlaying;console.log("[StormcloudVideoPlayer][AdState]",_({event:e,timestamp:(new Date).toISOString(),showAds:n,adPlaying:a,inAdBreak:i,activeAdRequestToken:this.activeAdRequestToken},t))}},e.prototype.resetForBreakEnd=function(){this.clearAdStopTimer(),this.clearAdStartTimer(),this.clearAdRequestWatchdog(),this.clearAdFailsafeTimer(),this.activeAdRequestToken=null,this.expectedAdBreakDurationMs=void 0,this.currentAdBreakStartWallClockMs=void 0,this.scteAdBreakEndWallClockMs=void 0,this.adBreakPlayedDurationMs=0,this.currentAdIndex=0,this.totalAdsInBreak=0,this.consecutiveFailures=0,this.globalConsecutiveNoFills=0,this.adBreakEpoch++},e.prototype.destroy=function(){this.clearAdStopTimer(),this.clearAdStartTimer(),this.clearAdFailsafeTimer(),this.clearAdRequestWatchdog()},e}(),Sf=function(){function e(e,t){this.video=e,this.debug=t}return e.prototype.ensureContainer=function(){if(!this.container){var e=document.createElement("div");e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.right="0",e.style.bottom="0",e.style.display="none",e.style.alignItems="center",e.style.justifyContent="center",e.style.pointerEvents="none",e.style.zIndex="5",e.style.backgroundColor="#000",e.style.transition="opacity 0.3s ease-in-out",e.style.opacity="0",this.video.parentElement?(this.video.parentElement.appendChild(e),this.container=e):this.debug&&console.warn("[StormcloudVideoPlayer] Video element has no parent for placeholder container")}},e.prototype.show=function(){var e=this;if(this.ensureContainer(),this.container){this.video.muted||(this.video.muted=!0,this.debug&&console.log("[StormcloudVideoPlayer] Muted video when showing placeholder"));var t="none"===this.container.style.display||"0"===this.container.style.opacity;this.container.style.transition=t?"none":"opacity 0.3s ease-in-out",this.container.style.backgroundColor="#000",this.container.style.display="flex",this.container.offsetHeight,this.container.style.opacity="1",this.container.style.pointerEvents="auto",t&&requestAnimationFrame(function(){e.container&&(e.container.style.transition="opacity 0.3s ease-in-out")}),this.debug&&console.log("[StormcloudVideoPlayer] Showing placeholder layer (between content and ad layer)")}},e.prototype.hide=function(){var e=this;this.container&&(this.container.style.opacity="0",setTimeout(function(){e.container&&(e.container.style.display="none",e.container.style.pointerEvents="none",e.container.style.backgroundColor="#000")},300),this.debug&&console.log("[StormcloudVideoPlayer] Hiding placeholder layer"))},e.prototype.destroy=function(){this.container&&(this.container.parentElement&&this.container.parentElement.removeChild(this.container),this.container=void 0)},e}(),Tf=function(){function e(e,t,r,i,n){this.isLiveStream=!1,this.nativeHlsMode=!1,this.videoSrcProtection=null,this.reloadingLiveStream=!1,this.bufferedSegmentsCount=0,this.shouldAutoplayAfterBuffering=!1,this.hasInitialBufferCompleted=!1,this.latencyProfileApplied=!1,this.config=e,this.video=t,this.cueManager=r,this.timing=i,this.callbacks=n}return Object.defineProperty(e.prototype,"debug",{get:function(){return!!this.config.debugAdTiming},enumerable:!1,configurable:!0}),e.prototype.shouldUseNativeHls=function(e){if("other"===e())return!0;var t=this.video.canPlayType("application/vnd.apple.mpegurl");return!(!this.config.allowNativeHls||!t)},e.prototype.setupNativeHls=function(){return x(this,void 0,void 0,function(){var e,t,r,i;return O(this,function(n){switch(n.label){case 0:return this.nativeHlsMode=!0,this.videoSrcProtection=this.config.src,this.video.src=this.config.src,this.isLiveStream=null!==(t=this.config.isLiveStream)&&void 0!==t?t:null!==(r=this.config.lowLatencyMode)&&void 0!==r&&r,this.debug&&(e=this.isLiveStream?"live (main video continues muted during ads)":"vod (main video pauses during ads)",console.log("[StormcloudVideoPlayer] Using native HLS playback:",{isLive:this.isLiveStream,allowNativeHls:this.config.allowNativeHls,adBehavior:e})),this.config.autoplay?[4,null===(i=this.video.play())||void 0===i?void 0:i.catch(function(){})]:[3,2];case 1:n.sent(),n.label=2;case 2:return[2]}})})},e.prototype.setupHls=function(){var e=this;this.hls=new md({enableWorker:!0,backBufferLength:30,liveDurationInfinity:!0,lowLatencyMode:!!this.config.lowLatencyMode,maxLiveSyncPlaybackRate:1.1,maxBufferLength:30,maxMaxBufferLength:600,maxBufferSize:6e7,maxBufferHole:1,highBufferWatchdogPeriod:2,nudgeOffset:.2,nudgeMaxRetry:5,startPosition:-1}),this.hls.on(md.Events.MEDIA_ATTACHED,function(){var t;null===(t=e.hls)||void 0===t||t.loadSource(e.config.src)}),this.hls.on(md.Events.MANIFEST_PARSED,function(t,r){return x(e,void 0,void 0,function(){var e,t,r,i,n,a,s;return O(this,function(o){switch(o.label){case 0:return this.isLiveStream=null!==(t=this.config.isLiveStream)&&void 0!==t?t:null!==(n=null===(i=null===(r=this.hls)||void 0===r?void 0:r.levels)||void 0===i?void 0:i.some(function(e){var t,r;return!0===(null===(t=null==e?void 0:e.details)||void 0===t?void 0:t.live)||"LIVE"===(null===(r=null==e?void 0:e.details)||void 0===r?void 0:r.type)}))&&void 0!==n&&n,[4,this.callbacks.onManifestParsed(this.isLiveStream)];case 1:return o.sent(),this.bufferedSegmentsCount=0,this.hasInitialBufferCompleted=!1,this.shouldAutoplayAfterBuffering=!!this.config.autoplay,this.latencyProfileApplied=!1,this.detectedLowLatencyStream=void 0,e=null!==(a=this.config.minSegmentsBeforePlay)&&void 0!==a?a:2,this.debug&&console.log("[StormcloudVideoPlayer] Waiting for",e,"segments to buffer before playback"),0!==e&&this.config.autoplay?[3,3]:(this.hasInitialBufferCompleted=!0,this.config.autoplay?[4,null===(s=this.video.play())||void 0===s?void 0:s.catch(function(){})]:[3,3]);case 2:o.sent(),o.label=3;case 3:return this.reloadingLiveStream=!1,[2]}})})}),this.hls.on(md.Events.LEVEL_LOADED,function(t,r){var i,n,a,s;if(e.applyStreamLatencyProfile(null==r?void 0:r.details),!e.callbacks.isInAdBreak()&&!e.callbacks.hasPendingAdBreak()){var o=null==r?void 0:r.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=(i=void 0,F(d)),f=h.next();!f.done;f=h.next()){var v=f.value,g="",p="";if(Array.isArray(v))g=String(null!==(a=v[0])&&void 0!==a?a:""),p=String(null!==(s=v[1])&&void 0!==s?s:"");else if("string"==typeof v){var m=v.indexOf(":");m>=0?(g=v.substring(0,m),p=v.substring(m+1)):g=v}if(g&&(g.includes("EXT-X-CUE-OUT")||g.includes("EXT-X-DATERANGE"))){var y=g.includes("EXT-X-DATERANGE")?ef(p):{};if(g.includes("EXT-X-CUE-OUT")||"SCTE35-OUT"in y||void 0!==y["SCTE35-OUT"]){var k=Jh(p),E=_(_({type:"start"},void 0!==k?{durationSeconds:k}:{}),{raw:{tag:g,value:p,earlyDetection:!0}});return e.debug&&console.log("[StormcloudVideoPlayer] EARLY SCTE-35 DETECTION: Ad break marker found in fragment",u,"- starting pre-fetch (NOT playing yet)"),void e.callbacks.onScte35Cue(E,_({},e.cueManager.createScte35CueContext("manifest","early",c)))}}}}catch(e){i={error:e}}finally{try{f&&!f.done&&(n=h.return)&&n.call(h)}finally{if(i)throw i.error}}}}}),this.hls.on(md.Events.FRAG_BUFFERED,function(t,r){return x(e,void 0,void 0,function(){var e,t,r,i=this;return O(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.debug&&console.log("[StormcloudVideoPlayer] Buffered segment ".concat(this.bufferedSegmentsCount,"/").concat(e)),this.bufferedSegmentsCount>=e?(this.hasInitialBufferCompleted=!0,this.shouldAutoplayAfterBuffering?(this.debug&&console.log("[StormcloudVideoPlayer] Initial buffer complete (".concat(this.bufferedSegmentsCount," segments). Starting playback.")),[4,null===(r=this.video.play())||void 0===r?void 0:r.catch(function(e){i.debug&&console.warn("[StormcloudVideoPlayer] Autoplay failed:",e)})]):[3,2]):[3,2]);case 1:n.sent(),n.label=2;case 2:return[2]}})})}),this.hls.on(md.Events.FRAG_PARSING_METADATA,function(t,r){((null==r?void 0:r.samples)||[]).map(function(e){return{key:"ID3",value:null==e?void 0:e.data,ptsSeconds:null==e?void 0:e.pts}}).forEach(function(t){return e.onId3Tag(t)})}),this.hls.on(md.Events.FRAG_LOADED,function(t,r){var i;e.processFragmentScte35Payload(null==r?void 0:r.payload,"number"==typeof(null===(i=null==r?void 0:r.frag)||void 0===i?void 0:i.sn)?r.frag.sn:void 0,rf(null==r?void 0:r.frag))}),this.hls.on(md.Events.FRAG_DECRYPTED,function(t,r){var i;e.processFragmentScte35Payload(null==r?void 0:r.payload,"number"==typeof(null===(i=null==r?void 0:r.frag)||void 0===i?void 0:i.sn)?r.frag.sn:void 0,rf(null==r?void 0:r.frag))}),this.hls.on(md.Events.FRAG_CHANGED,function(t,r){var i,n,a,s,o,l=null==r?void 0:r.frag,u=null==l?void 0:l.tagList;if(Array.isArray(u)){try{for(var c=F(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 p=Zh(v),m=_(_(_({type:"progress"},void 0!==(null==p?void 0:p.duration)?{durationSeconds:p.duration}:{}),void 0!==(null==p?void 0:p.elapsed)?{ptsSeconds:p.elapsed}:{}),{raw:{tag:f,value:v}});e.callbacks.onScte35Cue(m,_({},e.cueManager.createScte35CueContext("manifest","playback",l)))}else if(f.includes("EXT-X-CUE-OUT")){var y=Jh(v);m=_(_({type:"start"},void 0!==y?{durationSeconds:y}:{}),{raw:{tag:f,value:v}});e.callbacks.onScte35Cue(m,_({},e.cueManager.createScte35CueContext("manifest","playback",l)))}else if(f.includes("EXT-X-CUE-IN"))e.callbacks.onScte35Cue({type:"end",raw:{tag:f,value:v}},_({},e.cueManager.createScte35CueContext("manifest","playback",l)));else if(f.includes("EXT-X-DATERANGE")){var k=ef(v),E="SCTE35-OUT"in k||void 0!==k["SCTE35-OUT"],S="SCTE35-IN"in k||void 0!==k["SCTE35-IN"],T=String(null!==(o=k.CLASS)&&void 0!==o?o:""),A=tf(k.DURATION);if(E||/com\.apple\.hls\.cue/i.test(T)){m=_(_({type:"start"},void 0!==A?{durationSeconds:A}:{}),{raw:{tag:f,value:v,attrs:k}});e.callbacks.onScte35Cue(m,_({},e.cueManager.createScte35CueContext("manifest","playback",l)))}S&&e.callbacks.onScte35Cue({type:"end",raw:{tag:f,value:v,attrs:k}},_({},e.cueManager.createScte35CueContext("manifest","playback",l)))}}}catch(e){i={error:e}}finally{try{d&&!d.done&&(n=c.return)&&n.call(c)}finally{if(i)throw i.error}}e.callbacks.activatePendingCuesForFragment(l)}else e.callbacks.activatePendingCuesForFragment(l)}),this.hls.on(md.Events.ERROR,function(t,r){var i,n;if(null==r?void 0:r.fatal)switch(r.type){case md.ErrorTypes.NETWORK_ERROR:null===(i=e.hls)||void 0===i||i.startLoad();break;case md.ErrorTypes.MEDIA_ERROR:null===(n=e.hls)||void 0===n||n.recoverMediaError();break;default:e.callbacks.onFatalDestroy()}}),this.hls.attachMedia(this.video)},e.prototype.isLowLatencyStream=function(){return this.detectedLowLatencyStream},e.prototype.applyStreamLatencyProfile=function(e){var t;if(!this.latencyProfileApplied&&this.hls&&e){if(!0!==e.live)return this.latencyProfileApplied=!0,void(this.detectedLowLatencyStream=!1);var r=this.isLowLatencyManifest(e),i=r&&!!this.config.lowLatencyMode;this.detectedLowLatencyStream=i,this.latencyProfileApplied=!0;var n=this.hls.config;i?(n.maxLiveSyncPlaybackRate=1.5,n.maxBufferHole=.5,delete n.liveSyncDuration):(n.maxLiveSyncPlaybackRate=1.1,n.maxBufferHole=1,delete n.liveSyncDuration,n.liveSyncDurationCount=3),this.debug&&console.log("[StormcloudVideoPlayer] Live latency profile: ".concat(i?"LL-HLS (low latency)":"standard live (stability)"),{isLowLatencyManifest:r,lowLatencyModeRequested:!!this.config.lowLatencyMode,canBlockReload:e.canBlockReload,partTarget:e.partTarget,partHoldBack:e.partHoldBack,partListLength:Array.isArray(e.partList)?e.partList.length:0,targetDuration:null!==(t=e.targetduration)&&void 0!==t?t:e.targetDuration,maxLiveSyncPlaybackRate:n.maxLiveSyncPlaybackRate,maxBufferHole:n.maxBufferHole})}},e.prototype.isLowLatencyManifest=function(e){if(!e)return!1;var t=Array.isArray(e.partList)&&e.partList.length>0,r="number"==typeof e.partTarget&&e.partTarget>0,i="number"==typeof e.partHoldBack&&e.partHoldBack>0,n=!0===e.canBlockReload;return t||r||i||n},e.prototype.onId3Tag=function(e){"number"==typeof e.ptsSeconds&&this.timing.updatePtsDrift(e.ptsSeconds);var t=nf(e);t&&this.callbacks.onScte35Cue(t,{source:"id3",readiness:"playback"})},e.prototype.processFragmentScte35Payload=function(e,t,r){var i=this,n=function(e){if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e)){var t=e;return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}}(e);n&&ff(n,this.cueManager.tsScte35Pids,this.cueManager.pmtPids,this.cueManager.processedTsScte35Sections).forEach(function(e){var n={source:"ts",readiness:"early"};void 0!==t&&(n.fragmentSn=t),void 0!==r&&(n.fragmentStartSeconds=r),i.callbacks.onScte35Cue(e,n)})},e.prototype.getLiveSyncPosition=function(){var e,t=null===(e=this.hls)||void 0===e?void 0:e.liveSyncPosition;return"number"==typeof t&&Number.isFinite(t)?t:void 0},e.prototype.restartLoadAt=function(e){if(this.hls)try{this.hls.stopLoad(),this.hls.startLoad(e)}catch(e){this.debug&&console.warn("[StormcloudVideoPlayer] Failed to restart HLS load at live edge:",e)}},e.prototype.recoverMediaError=function(){if(this.hls)try{this.hls.recoverMediaError()}catch(e){this.debug&&console.warn("[StormcloudVideoPlayer] recoverMediaError() failed:",e)}},e.prototype.reloadLiveStream=function(){var e=this,t=this.hls;if(t){this.debug&&console.log("[StormcloudVideoPlayer] Hard-reloading live stream (destroy hls → reset video → fresh setupHls)");try{this.reloadingLiveStream=!0,t.stopLoad(),t.detachMedia(),t.destroy(),this.hls=void 0;try{this.video.removeAttribute("src"),this.video.load()}catch(e){console.warn("[StormcloudVideoPlayer] video.load() threw after src removal:",e)}}catch(e){return this.reloadingLiveStream=!1,this.hls=void 0,void(this.debug&&console.warn("[StormcloudVideoPlayer] Failed to tear down during hard-reload:",e))}window.setTimeout(function(){if(e.hls)e.reloadingLiveStream=!1;else try{e.setupHls()}catch(t){e.reloadingLiveStream=!1,e.debug&&console.warn("[StormcloudVideoPlayer] Failed to rebuild pipeline during hard-reload:",t)}},600)}},e.prototype.destroy=function(){var e;null===(e=this.hls)||void 0===e||e.destroy(),this.hls=void 0},e}();function Af(e){return e.getOriginalMutedState()?0:e.getOriginalVolume()}var bf=function(){function e(e,t,r,i,n){this.inAdBreak=!1,this.showAds=!1,this.isShowingPlaceholder=!1,this.adDetectSentForCurrentBreak=!1,this.continuousFetchingActive=!1,this.continuousFetchLoopRunning=!1,this.adRequestQueue=[],this.adPodQueue=[],this.maxPlaceholderDurationMs=5e3,this.pendingAdBreak=null,this.host=e,this.timing=t,this.adConfig=r,this.cueManager=i,this.placeholder=n}return Object.defineProperty(e.prototype,"debug",{get:function(){return!!this.host.config.debugAdTiming},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"analyticsContext",{get:function(){return Ph(this.host.config)},enumerable:!1,configurable:!0}),e.prototype.nextAdRequestUrl=function(e){var t=Math.min(this.timing.getWallClockRemainingAdMs(),this.timing.getDurationBudgetRemainingMs()),r=t>0?t:void 0;return this.host.generatePodVastUrl(e,r)},e.prototype.attachImaEventListeners=function(){var e=this,t=this.host.getAdPlayer();t.on("pod_ad_started",function(t){var r;e.timing.notePodAdStarted(),e.debug&&console.log("[POD] Playing pod ad ".concat(null!=(null==t?void 0:t.index)?t.index+1:"?","/").concat(null!==(r=null==t?void 0:t.total)&&void 0!==r?r:"?"))}),t.on("ad_click",function(){e.host.onAdClick()}),t.on("ad_interaction",function(t){t&&e.host.onAdInteraction(t)}),t.on("all_ads_completed",function(){Bh(e.host.config.licenseKey,{source:"hls",adIndex:e.timing.currentAdIndex,timestamp:(new Date).toISOString()},e.analyticsContext).catch(function(){}),e.timing.recordPlayedAdDuration(e.host.getAdPlayer());var t=e.timing.getRemainingAdMs();e.timing.consecutiveFailures=0,e.debug&&console.log("[StormcloudVideoPlayer] all_ads_completed event received - remaining=".concat(t,"ms, queued ads=").concat(e.adRequestQueue.length),e.adRequestQueue.length>0?{queuedUrls:B([],N(e.adRequestQueue),!1)}:{}),e.inAdBreak&&(e.timing.hasTimeToStartAnotherAd()?e.tryNextAvailableAdWithRateLimit():e.handleAdPodComplete())}),t.on("ad_error",function(t){var r="Ad playback failed";if(t){var i=t.code||t.errorCode||"unknown",n=t.vastErrorCode,a=t.message||t.errorMessage||"Unknown error",s=t.cause||t.innerError||t.error;if(r="Ad error: AdError ".concat(i,": ").concat(a),n&&"N/A"!==n&&n!==i&&(r+=" (VAST Error Code: ".concat(n,")")),s){var o="string"==typeof s?s:s.message||String(s);r+=". Caused by: ".concat(o)}}console.error("[AD-ERROR]",r,t||""),e.handleAdFailure()}),t.on("content_pause",function(){e.timing.clearAdFailsafeTimer(),e.timing.clearAdRequestWatchdog(),e.timing.activeAdRequestToken=null,e.showAds=!0,e.timing.resetGamNoFillCounter(),e.inAdBreak&&null!=e.timing.expectedAdBreakDurationMs&&null==e.timing.getAdBreakEndWallClockMs()&&(e.timing.scheduleAdStopAtBreakBoundary(),e.debug&&console.log("[StormcloudVideoPlayer] Starting ad break timer on content_pause (first ad starting)")),e.host.getAdPlayer().setAdVolume(Af(e.host.getAdPlayer())),e.isShowingPlaceholder&&(e.debug&&console.log("[StormcloudVideoPlayer] Hiding placeholder - new ads starting"),e.host.getAdPlayer().hidePlaceholder(),e.isShowingPlaceholder=!1)}),t.on("content_resume",function(){if(Bh(e.host.config.licenseKey,{source:"hls",adIndex:e.timing.currentAdIndex,timestamp:(new Date).toISOString()},e.analyticsContext).catch(function(){}),e.host.video.muted||(e.host.video.muted=!0,e.debug&&console.log("[StormcloudVideoPlayer] Muted video on content_resume (ad ended, gap between ads)")),e.timing.clearAdFailsafeTimer(),e.timing.clearAdRequestWatchdog(),e.timing.activeAdRequestToken=null,e.showAds=!1,e.inAdBreak){e.timing.consecutiveFailures=0,e.timing.recordPlayedAdDuration(e.host.getAdPlayer());var t=e.timing.getRemainingAdMs();e.debug&&console.log("[CONTINUOUS-FETCH] content_resume event: remaining=".concat(t,"ms, queued ads=").concat(e.adRequestQueue.length),e.adRequestQueue.length>0?{queuedUrls:B([],N(e.adRequestQueue),!1)}:{}),e.timing.hasTimeToStartAnotherAd()?e.tryNextAvailableAdWithRateLimit():e.handleAdPodComplete()}})},e.prototype.recreateAdController=function(){this.debug&&console.log("[StormcloudVideoPlayer] Recreating AdController for new ad");var e=this.inAdBreak&&this.showAds,t=this.host.getAdPlayer();e&&t&&(this.debug&&console.log("[StormcloudVideoPlayer] Showing placeholder before destroying old AdController"),this.placeholder.show(),t.showPlaceholder(),this.isShowingPlaceholder=!0);var r=t.getOriginalMutedState(),i=t.getOriginalVolume();if(t)try{t.destroy(),this.host.video.muted=!0}catch(e){this.debug&&console.warn("[StormcloudVideoPlayer] Error destroying old AdController:",e)}var n=this.host.shouldContinueLiveStreamDuringAds(),a=this.host.createAdPlayer(n);this.host.setAdPlayer(a),a.initialize(),a.updateOriginalMutedState(r,i),this.attachImaEventListeners(),e&&(this.placeholder.show(),a.showPlaceholder(),this.isShowingPlaceholder=!0)},e.prototype.clearPendingAdBreak=function(){null!=this.prefetchTimerId&&(clearTimeout(this.prefetchTimerId),this.prefetchTimerId=void 0),this.pendingAdBreak=null,this.cueManager.pendingScte35CueKey=void 0,this.adConfig.podAssignedByPrefetch=!1},e.prototype.handleAdStart=function(e){return x(this,void 0,void 0,function(){var t,r,i,n,a,s,o;return O(this,function(l){switch(l.label){case 0:if((t=this.adConfig.findCurrentOrNextBreak(1e3*this.host.video.currentTime))&&this.adConfig.consumedVmapBreakIds.add(this.adConfig.getAdBreakKey(t)),(r=this.adConfig.selectVastTagsForBreak(t))&&r.length>0&&r[0])i=r[0];else{if(!this.adConfig.apiVastTagUrl)return this.clearPendingAdBreak(),[2];i=this.adConfig.apiVastTagUrl}return n=null!=e.durationSeconds?1e3*e.durationSeconds:null==t?void 0:t.durationMs,this.debug&&(a=this.host.config.isLiveStream?"LIVE":"VOD",console.log("[CONTINUOUS-FETCH] ".concat(a," MODE: Target duration=").concat(n,"ms"))),this.timing.failedVastUrls.clear(),this.timing.temporaryFailureUrls.clear(),this.timing.consecutiveFailures=0,this.continuousFetchingActive=!0,this.isShowingPlaceholder=!1,this.timing.totalAdRequestsInBreak=0,this.adConfig.podAssignedByPrefetch?this.adConfig.podAssignedByPrefetch=!1:this.adConfig.beginNewAdPod(),s=this.host.video.muted,o=this.host.video.volume,this.host.getAdPlayer().updateOriginalMutedState(s,o),this.inAdBreak=!0,this.timing.adBreakPlayedDurationMs=0,this.timing.currentAdIndex=0,this.timing.totalAdsInBreak=0,this.adPodQueue=[],this.showAds=!1,null==this.timing.expectedAdBreakDurationMs&&null!=n&&(this.timing.expectedAdBreakDurationMs=n),[4,this.startOptimizedPod(i,n,s,o)];case 1:return l.sent()?[3,3]:(this.debug&&console.log("[POD] Initial pod request did not fill; attempting top-up pod request"),this.continuousFetchingActive=!0,this.startContinuousFetching(i),[4,this.tryNextAvailableAdWithRateLimit()]);case 2:l.sent(),l.label=3;case 3:return[2]}})})},e.prototype.startOptimizedPod=function(e,t,r,i){return x(this,void 0,void 0,function(){var n,a,s,o,l,u,c;return O(this,function(d){switch(d.label){case 0:if(this.pendingAdBreak&&this.pendingAdBreak.vastUrls.length>0?(n=this.pendingAdBreak.vastUrls[0],this.clearPendingAdBreak()):n=this.host.generatePodVastUrl(e,t),!n)return[2,!1];this.continuousFetchingActive=!1,this.recreateAdController(),a=this.host.getAdPlayer(),s=++this.timing.adRequestTokenCounter,this.timing.activeAdRequestToken=s,this.timing.startAdRequestWatchdog(s),d.label=1;case 1:return d.trys.push([1,5,,6]),[4,this.timing.enforceGlobalRateLimit()];case 2:return d.sent(),this.timing.lastAdRequestTime=Date.now(),[4,a.requestAds(n)];case 3:return d.sent(),this.timing.clearAdRequestWatchdog(),this.timing.activeAdRequestToken!==s?[2,!0]:(o=null!==(c=null===(u=a.getPodAdCount)||void 0===u?void 0:u.call(a))&&void 0!==c?c:1)<1?[2,!1]:(this.debug&&console.log(1===o?"[POD] Response contained a single ad; playing it and enabling pod top-up":"[POD] Optimized pod returned ".concat(o," ads; playing pod in one controller")),Nh(this.host.config.licenseKey,{source:"hls",vastUrl:n,timestamp:(new Date).toISOString()},this.analyticsContext).catch(function(){}),this.timing.startAdFailsafeTimer(s),[4,a.play()]);case 4:return d.sent(),this.timing.markAdStarted(),null!=this.timing.expectedAdBreakDurationMs&&null==this.timing.getAdBreakEndWallClockMs()&&this.timing.scheduleAdStopAtBreakBoundary(),a.setAdVolume(r?0:i),this.timing.consecutiveFailures=0,this.continuousFetchingActive=!0,this.startContinuousFetching(e),[2,!0];case 5:return l=d.sent(),this.timing.clearAdRequestWatchdog(),this.timing.clearAdFailsafeTimer(),this.timing.activeAdRequestToken===s&&(this.timing.activeAdRequestToken=null),this.debug&&console.warn("[POD] Optimized pod request/play failed:",l),this.timing.isTemporaryAdError(l)&&this.timing.temporaryFailureUrls.set(n,Date.now()),this.continuousFetchingActive=!0,this.recreateAdController(),[2,!1];case 6:return[2]}})})},e.prototype.startContinuousFetching=function(e){this.continuousFetchingActive&&(this.continuousFetchLoopRunning?this.debug&&console.log("[CONTINUOUS-FETCH] Fetch loop already running, skipping duplicate start"):(this.debug&&console.log("[CONTINUOUS-FETCH] Starting continuous ad fetching loop"),this.continuousFetchLoopRunning=!0,this.continuousFetchLoop(e)))},e.prototype.continuousFetchLoop=function(e){return x(this,void 0,void 0,function(){var t,r,i;return O(this,function(n){switch(n.label){case 0:t=this.timing.adBreakEpoch,r=function(){var t,r,n;return O(this,function(a){switch(a.label){case 0:return Math.min(i.timing.getWallClockRemainingAdMs(),i.timing.getDurationBudgetRemainingMs())<=i.timing.getMinRemainingMsToStartAd()?(i.debug&&console.log("[CONTINUOUS-FETCH] Not enough ad break time left (wall=".concat(i.timing.getWallClockRemainingAdMs(),"ms, budget=").concat(i.timing.getDurationBudgetRemainingMs(),"ms), stopping URL generation")),[2,"break"]):i.timing.isGamInCooldown()?(i.debug&&console.log("[CIRCUIT-BREAKER] GAM in cooldown, stopping URL generation"),[2,"break"]):i.timing.consecutiveFailures>=i.timing.maxConsecutiveFailures?(i.debug&&console.log("[CONTINUOUS-FETCH] Too many consecutive failures (".concat(i.timing.consecutiveFailures,"), stopping URL generation")),[2,"break"]):i.timing.totalAdRequestsInBreak>=i.timing.maxTotalAdRequestsPerBreak?(i.debug&&console.log("[CONTINUOUS-FETCH] Maximum ad requests reached (".concat(i.timing.maxTotalAdRequestsPerBreak,"), stopping")),[2,"break"]):i.adRequestQueue.length>=5?(i.debug&&console.log("[CONTINUOUS-FETCH] URL queue full (".concat(i.adRequestQueue.length,"), waiting...")),[4,new Promise(function(e){return setTimeout(e,1e3)})]):[3,2];case 1:case 3:return a.sent(),[2,"continue"];case 2:return!(t=i.nextAdRequestUrl(e))||i.timing.failedVastUrls.has(t)||i.timing.isUrlInCooldown(t)?[4,new Promise(function(e){return setTimeout(e,500)})]:[3,4];case 4:return i.debug&&(r=B(B([],N(i.adRequestQueue),!1),[t],!1),console.log("[CONTINUOUS-FETCH] Queued VAST URL (queue size: ".concat(r.length,")"),{queuedUrls:r})),i.adRequestQueue.push(t),n=i.timing.consecutiveFailures>0?Math.min(1e3*Math.pow(2,i.timing.consecutiveFailures),5e3):500,[4,new Promise(function(e){return setTimeout(e,n)})];case 5:return a.sent(),[2]}})},i=this,n.label=1;case 1:return this.continuousFetchingActive&&this.inAdBreak&&t===this.timing.adBreakEpoch?[5,r()]:[3,3];case 2:return"break"===n.sent()?[3,3]:[3,1];case 3:return this.continuousFetchLoopRunning=!1,this.debug&&console.log("[CONTINUOUS-FETCH] URL generation loop ended (queued: ".concat(this.adRequestQueue.length,")"),this.adRequestQueue.length>0?{queuedUrls:B([],N(this.adRequestQueue),!1)}:{}),[2]}})})},e.prototype.stopContinuousFetching=function(){this.continuousFetchingActive=!1,this.continuousFetchLoopRunning=!1,this.placeholder.hide(),this.debug&&console.log("[CONTINUOUS-FETCH] Stopping continuous ad fetching")},e.prototype.tryNextAvailableAdWithRateLimit=function(){return x(this,void 0,void 0,function(){var e,t,r,i,n,a;return O(this,function(s){switch(s.label){case 0:return this.inAdBreak?(e=this.timing.adBreakEpoch,this.timing.consecutiveFailures>=this.timing.maxConsecutiveFailures?(this.debug&&console.log("[CONTINUOUS-FETCH] Too many consecutive failures (".concat(this.timing.consecutiveFailures,"), ending ad break gracefully")),this.handleAdPodComplete(),[2]):(t=Math.pow(2,this.timing.consecutiveFailures),r=Math.min(this.timing.backoffBaseMs*t,this.timing.maxBackoffMs),i=this.timing.minAdRequestIntervalMs+(this.timing.consecutiveFailures>0?r:0),(n=Date.now()-this.timing.lastAdRequestTime)<i?(a=i-n,this.debug&&console.log("[CONTINUOUS-FETCH] Rate limiting: waiting ".concat(a,"ms before next request (backoff: ").concat(this.timing.consecutiveFailures," failures)")),[4,new Promise(function(e){return setTimeout(e,a)})]):[3,2])):[2];case 1:s.sent(),s.label=2;case 2:return this.inAdBreak&&e===this.timing.adBreakEpoch?[2,this.tryNextAvailableAd(0)]:[2]}})})},e.prototype.tryNextAvailableAd=function(){return x(this,arguments,void 0,function(e){var t,r,i,n;return void 0===e&&(e=0),O(this,function(a){switch(a.label){case 0:if(!this.inAdBreak)return[2];if(t=this.timing.getRemainingAdMs(),!this.timing.hasTimeToStartAnotherAd())return this.debug&&console.log("[CONTINUOUS-FETCH] Not enough time remaining (".concat(t,"ms) to start another ad, ending ad break")),this.handleAdPodComplete(),[2];if(this.timing.isGamInCooldown())return this.debug&&console.log("[CIRCUIT-BREAKER] GAM in cooldown, ending ad break gracefully"),this.handleAdPodComplete(),[2];if(this.timing.consecutiveFailures>=this.timing.maxConsecutiveFailures)return this.debug&&console.log("[CONTINUOUS-FETCH] Too many consecutive failures (".concat(this.timing.consecutiveFailures,"), ending ad break")),this.handleAdPodComplete(),[2];this.timing.cleanupTemporaryFailures(),a.label=1;case 1:if(!(this.adRequestQueue.length>0))return[3,9];if(!(r=this.adRequestQueue.shift()))return[3,1];if(this.timing.failedVastUrls.has(r))return this.debug&&console.log("[CONTINUOUS-FETCH] Skipping permanently-failed URL, trying next..."),[3,1];if(this.timing.isUrlInCooldown(r))return this.debug&&console.log("[CONTINUOUS-FETCH] Skipping URL in cooldown (recent no-fill), trying next..."),[3,1];this.debug&&console.log("[CONTINUOUS-FETCH] Requesting next ad via HLS ad player (".concat(this.timing.currentAdIndex+1,", ").concat(this.adRequestQueue.length," remaining in queue)")),a.label=2;case 2:return a.trys.push([2,4,,8]),[4,this.playSingleAd(r)];case 3:return a.sent(),this.timing.consecutiveFailures=0,[3,8];case 4:return i=a.sent(),n=i.message,this.debug&&console.log("[CONTINUOUS-FETCH] Ad request failed:",n),n.includes("ad_duration_exceeds_budget")?[4,this.tryNextAvailableAdWithRateLimit()]:[3,6];case 5:return a.sent(),[2];case 6:return n.includes("permanently failed")||n.includes("in cooldown")||this.timing.consecutiveFailures++,[4,this.tryNextAvailableAdWithRateLimit()];case 7:return a.sent(),[3,8];case 8:return[2];case 9:return this.continuousFetchingActive&&e<3&&t>2e3?(this.debug&&console.log("[CONTINUOUS-FETCH] Queue empty, waiting for URLs... (".concat(e+1,"/").concat(3,")")),[4,new Promise(function(e){return setTimeout(e,500)})]):[3,12];case 10:return a.sent(),[4,this.tryNextAvailableAd(e+1)];case 11:return a.sent(),[2];case 12:return!this.isShowingPlaceholder&&t>1e3?this.showPlaceholderAndWaitForAds():(this.debug&&console.log("[CONTINUOUS-FETCH] No more ads available, ending ad break"),this.handleAdPodComplete()),[2]}})})},e.prototype.playSingleAd=function(e){return x(this,void 0,void 0,function(){var t,r,i,n,a;return O(this,function(s){switch(s.label){case 0:if(this.host.getAdPlayer().isAdPlaying())return[2];if(this.timing.failedVastUrls.has(e))throw this.debug&&console.warn("[AD-ERROR] Skipping permanently-failed VAST URL:",e),new Error("VAST URL permanently failed");if(this.timing.isUrlInCooldown(e))throw this.debug&&console.warn("[AD-ERROR] Skipping URL in cooldown (recent no-fill):",e),new Error("VAST URL in cooldown after no-fill");if(this.timing.consecutiveFailures>=this.timing.maxConsecutiveFailures)throw this.debug&&console.warn("[AD-ERROR] Too many consecutive failures, not requesting more ads"),new Error("Too many consecutive failures");if(this.timing.isGamInCooldown())throw this.debug&&console.warn("[CIRCUIT-BREAKER] GAM in cooldown, skipping ad request"),new Error("GAM in cooldown");this.recreateAdController(),t=++this.timing.adRequestTokenCounter,this.timing.activeAdRequestToken=t,this.timing.startAdRequestWatchdog(t),s.label=1;case 1:return s.trys.push([1,8,,9]),[4,this.timing.enforceGlobalRateLimit()];case 2:return s.sent(),this.timing.lastAdRequestTime=Date.now(),[4,(r=this.host.getAdPlayer()).requestAds(e)];case 3:if(s.sent(),Nh(this.host.config.licenseKey,{source:"hls",vastUrl:e,timestamp:(new Date).toISOString()},this.analyticsContext).catch(function(){}),this.timing.clearAdRequestWatchdog(),this.timing.activeAdRequestToken!==t)return[2];if(!this.timing.ensureLoadedAdFitsBudget(r))throw this.timing.rejectLoadedAdForDuration(r),this.recreateAdController(),new Error("ad_duration_exceeds_budget");s.label=4;case 4:return s.trys.push([4,6,,7]),this.timing.startAdFailsafeTimer(t),[4,r.play()];case 5:return s.sent(),this.timing.markAdStarted(),null!=this.timing.expectedAdBreakDurationMs&&null==this.timing.getAdBreakEndWallClockMs()&&this.timing.scheduleAdStopAtBreakBoundary(),r.setAdVolume(Af(r)),this.timing.consecutiveFailures=0,this.timing.temporaryFailureUrls.delete(e),[3,7];case 6:throw i=s.sent(),this.debug&&console.error("[AD-ERROR] Failed to play ad:",i),this.timing.isTemporaryAdError(i)?(this.timing.temporaryFailureUrls.set(e,Date.now()),this.debug&&console.log("[AD-ERROR] Temporary play error - URL can be retried after cooldown")):(this.timing.failedVastUrls.add(e),this.debug&&console.log("[AD-ERROR] Permanent play error - URL blacklisted")),this.timing.clearAdFailsafeTimer(),this.timing.activeAdRequestToken===t&&(this.timing.activeAdRequestToken=null),i;case 7:return[3,9];case 8:throw n=s.sent(),a=(null==n?void 0:n.message)||"",this.debug&&console.error("[AD-ERROR] Ad request failed:",a),this.timing.isTemporaryAdError(n)?(this.timing.temporaryFailureUrls.set(e,Date.now()),this.debug&&console.log("[AD-ERROR] Temporary error (no-fill/timeout) - URL can be retried after cooldown")):(this.timing.failedVastUrls.add(e),this.debug&&console.log("[AD-ERROR] Permanent error - URL blacklisted:",a)),this.timing.clearAdRequestWatchdog(),this.timing.clearAdFailsafeTimer(),this.timing.activeAdRequestToken===t&&(this.timing.activeAdRequestToken=null),n;case 9:return[2]}})})},e.prototype.showPlaceholderAndWaitForAds=function(){return x(this,void 0,void 0,function(){var e,t,r,i,n,a,s,o;return O(this,function(l){switch(l.label){case 0:if(e=this.timing.getRemainingAdMs(),t=Math.min(this.maxPlaceholderDurationMs,e),this.timing.isGamInCooldown())return this.debug&&console.log("[CIRCUIT-BREAKER] GAM in cooldown, skipping placeholder wait"),this.handleAdPodComplete(),[2];if(this.timing.consecutiveFailures>=this.timing.maxConsecutiveFailures)return this.debug&&console.log("[CONTINUOUS-FETCH] Skipping placeholder - too many consecutive failures"),this.handleAdPodComplete(),[2];if(t<1e3)return this.handleAdPodComplete(),[2];this.debug&&console.log("[CONTINUOUS-FETCH] Showing placeholder for ".concat(t,"ms while waiting for ad URLs")),this.isShowingPlaceholder=!0,this.host.getAdPlayer().showPlaceholder(),r=300,i=Math.floor(t/r),n=0,l.label=1;case 1:return n<i?[4,new Promise(function(e){return setTimeout(e,r)})]:[3,12];case 2:if(l.sent(),!this.inAdBreak)return[2];if(this.timing.consecutiveFailures>=this.timing.maxConsecutiveFailures)return this.debug&&console.log("[CONTINUOUS-FETCH] Too many failures during placeholder wait"),[3,12];if(!this.timing.hasTimeToStartAnotherAd())return this.debug&&console.log("[CONTINUOUS-FETCH] Not enough time remaining during placeholder wait, ending ad break"),[3,12];l.label=3;case 3:if(!(this.adRequestQueue.length>0))return[3,11];if(!this.timing.hasTimeToStartAnotherAd())return[3,11];if(!(a=this.adRequestQueue.shift()))return[3,3];if(this.timing.failedVastUrls.has(a))return[3,3];if(this.timing.isUrlInCooldown(a))return[3,3];this.debug&&console.log("[CONTINUOUS-FETCH] Ad URL available, requesting via HLS ad player"),this.isShowingPlaceholder=!1,this.host.getAdPlayer().hidePlaceholder(),l.label=4;case 4:return l.trys.push([4,6,,10]),[4,this.playSingleAd(a)];case 5:return l.sent(),this.timing.consecutiveFailures=0,[3,10];case 6:return s=l.sent(),(o=s.message).includes("ad_duration_exceeds_budget")?[4,this.tryNextAvailableAdWithRateLimit()]:[3,8];case 7:return l.sent(),[2];case 8:return o.includes("permanently failed")||o.includes("in cooldown")||this.timing.consecutiveFailures++,[4,this.tryNextAvailableAdWithRateLimit()];case 9:return l.sent(),[3,10];case 10:return[2];case 11:return n++,[3,1];case 12:return this.debug&&console.log("[CONTINUOUS-FETCH] Placeholder timeout, ending ad break"),this.isShowingPlaceholder=!1,this.host.getAdPlayer().hidePlaceholder(),this.handleAdPodComplete(),[2]}})})},e.prototype.handleAdPodComplete=function(){this.debug&&console.log("[StormcloudVideoPlayer] Ad pod complete - cleaning up"),this.timing.resetForBreakEnd(),this.stopContinuousFetching(),this.clearPendingAdBreak(),this.isShowingPlaceholder&&(this.host.getAdPlayer().hidePlaceholder(),this.isShowingPlaceholder=!1),this.adRequestQueue=[],this.inAdBreak=!1,this.adDetectSentForCurrentBreak=!1,this.cueManager.activeScte35BreakKey=void 0,this.cueManager.scheduledScte35BreakKey=void 0,this.adPodQueue=[],this.showAds=!1,this.host.getAdPlayer().stop().catch(function(){});var e=this.host.getAdPlayer().getOriginalMutedState(),t=this.host.getAdPlayer().getOriginalVolume();if(this.host.video.muted!==e&&(this.host.video.muted=e),Math.abs(this.host.video.volume-t)>.01&&(this.host.video.volume=t),this.host.video.style.visibility="visible",this.host.video.style.opacity="1",this.host.isLiveStream()){if(this.host.requiresMediaPipelineResetAfterAds())return this.debug&&console.log("[StormcloudVideoPlayer] Live break end — hard-reloading stream to reacquire decoder (single-decoder platform)"),this.host.reloadLiveStream(),void this.monitorLiveResumeStall(this.host.video.currentTime);var r=this.host.getLiveSyncPosition();return null!=r&&r>this.host.video.currentTime&&(this.debug&&console.log("[StormcloudVideoPlayer] Live break end — snapping to live edge: ".concat(this.host.video.currentTime.toFixed(2),"s → ").concat(r.toFixed(2),"s")),this.host.video.currentTime=r,this.host.restartHlsLoad(r)),this.resumeContentPlayback(),void this.monitorLiveResumeStall(this.host.video.currentTime)}this.resumeContentPlayback()},e.prototype.getBufferedAhead=function(){for(var e=this.host.video,t=e.currentTime,r=e.buffered,i=0;i<r.length;i++)if(t>=r.start(i)-.5&&t<=r.end(i))return r.end(i)-t;return 0},e.prototype.describeVideoState=function(){for(var e,t,r=this.host.video,i=null!==(e=["EMPTY","IDLE","LOADING","NO_SOURCE"][r.networkState])&&void 0!==e?e:String(r.networkState),n=null!==(t=["HAVE_NOTHING","HAVE_METADATA","HAVE_CURRENT_DATA","HAVE_FUTURE_DATA","HAVE_ENOUGH_DATA"][r.readyState])&&void 0!==t?t:String(r.readyState),a=r.error?"code=".concat(r.error.code).concat(r.error.message?" (".concat(r.error.message,")"):""):"none",s=[],o=0;o<r.buffered.length;o++)s.push("[".concat(r.buffered.start(o).toFixed(2),"–").concat(r.buffered.end(o).toFixed(2),"]"));return"t=".concat(r.currentTime.toFixed(2),"s paused=").concat(r.paused," ended=").concat(r.ended," seeking=").concat(r.seeking," ")+"readyState=".concat(n," networkState=").concat(i," error=").concat(a," ")+"buffered=".concat(s.length?s.join(","):"none")},e.prototype.monitorLiveResumeStall=function(e){var t,r,i,n=this,a=this.host.requiresMediaPipelineResetAfterAds(),s=a?8e3:5e3,o=a?7e3:5e3,l=Date.now(),u=e,c=0,d=0,h=this.host.video,f=!1,v=["loadstart","loadedmetadata","loadeddata","canplay","canplaythrough","play","playing","pause","waiting","stalled","suspend","seeking","seeked","emptied","error","ended"];if(this.debug){i=function(e){var t=((Date.now()-l)/1e3).toFixed(1);console.log("[ResumeDiag] +".concat(t,"s event=").concat(e.type," — ").concat(n.describeVideoState()))};try{for(var g=F(v),p=g.next();!p.done;p=g.next()){var m=p.value;h.addEventListener(m,i)}}catch(e){t={error:e}}finally{try{p&&!p.done&&(r=g.return)&&r.call(g)}finally{if(t)throw t.error}}f=!0,console.log("[ResumeDiag] +0.0s monitor start — ".concat(this.describeVideoState()))}var y=function(){var e,t;if(f&&i){try{for(var r=F(v),n=r.next();!n.done;n=r.next()){var a=n.value;h.removeEventListener(a,i)}}catch(t){e={error:t}}finally{try{n&&!n.done&&(t=r.return)&&t.call(r)}finally{if(e)throw e.error}}f=!1}},k=function(){var e,t;if(n.inAdBreak)y();else{var r=h.currentTime,i=r>u+.5,f=!h.paused&&h.readyState>=3;if(i&&f)return n.debug&&console.log("[StormcloudVideoPlayer] Live stream resumed successfully after ad break — ".concat(n.describeVideoState())),void y();h.paused&&(null===(e=h.play())||void 0===e||e.catch(function(){}));var v=Date.now()-l,g=n.getBufferedAhead()<.5&&!i;if(v>=45e3)return n.debug&&!i&&console.warn("[StormcloudVideoPlayer] Live stream failed to resume after ".concat(45..toFixed(0),"s — ").concat(n.describeVideoState())),void y();if(g&&v>=s&&Date.now()-d>=o&&c<3){if(c++,d=Date.now(),a)n.debug&&console.warn("[StormcloudVideoPlayer] Content still wedged after ad break — hard-reloading live stream (recovery ".concat(c,"/").concat(3,") — ").concat(n.describeVideoState())),n.host.reloadLiveStream();else if(1===c)n.debug&&console.warn("[StormcloudVideoPlayer] Content wedged after ad break — calling recoverMediaError() (recovery ".concat(c,"/").concat(3,") — ").concat(n.describeVideoState())),n.host.recoverMediaError();else if(2===c){var p=n.host.getLiveSyncPosition(),m=null!=p&&p>r?p:r;n.debug&&console.warn("[StormcloudVideoPlayer] Content wedged after ad break — restarting HLS load at ".concat(m.toFixed(2),"s (recovery ").concat(c,"/").concat(3,") — ").concat(n.describeVideoState())),null!=p&&p>r&&(h.currentTime=p),n.host.restartHlsLoad(m)}else n.debug&&console.warn("[StormcloudVideoPlayer] Content still wedged after ad break — hard-reloading live stream (recovery ".concat(c,"/").concat(3,") — ").concat(n.describeVideoState())),n.host.reloadLiveStream();u=h.currentTime,h.paused&&(null===(t=h.play())||void 0===t||t.catch(function(){}))}window.setTimeout(k,1e3)}};window.setTimeout(k,1e3)},e.prototype.resumeContentPlayback=function(e){var t,r=this;void 0===e&&(e=0);var i=this.host.video;if(i.paused)if(this.debug&&console.log("[StormcloudVideoPlayer] Resuming content playback after ads (attempt ".concat(e+1,"/").concat(5,", readyState=").concat(i.readyState,")")),i.readyState<3){if(e+1>=5)return this.debug&&console.warn("[StormcloudVideoPlayer] readyState never reached HAVE_FUTURE_DATA, forcing play()"),void(null===(t=i.play())||void 0===t||t.catch(function(){}));var n=function(){i.removeEventListener("canplay",n),r.resumeContentPlayback(e+1)};i.addEventListener("canplay",n);var a=500*(e+1);window.setTimeout(function(){i.removeEventListener("canplay",n),i.paused&&r.resumeContentPlayback(e+1)},a)}else{var s=i.play();s&&"function"==typeof s.catch&&s.catch(function(t){if(e+1>=5)r.debug&&console.warn("[StormcloudVideoPlayer] Failed to resume content playback after ads:",t);else{var i=250*(e+1);window.setTimeout(function(){r.resumeContentPlayback(e+1)},i)}})}else this.debug&&0===e&&console.log("[StormcloudVideoPlayer] Content video already playing after ads")},e.prototype.handleAdFailure=function(){this.timing.consecutiveFailures++,this.timing.recordGamNoFill();var e=this.timing.getRemainingAdMs();if(this.debug&&console.log("[CONTINUOUS-FETCH] Ad failure: remaining=".concat(e,"ms, queued ads=").concat(this.adRequestQueue.length,", consecutiveFailures=").concat(this.timing.consecutiveFailures),this.adRequestQueue.length>0?{queuedUrls:B([],N(this.adRequestQueue),!1)}:{}),this.timing.consecutiveFailures>=this.timing.maxConsecutiveFailures)return this.debug&&console.log("[CONTINUOUS-FETCH] Max consecutive failures reached (".concat(this.timing.consecutiveFailures,"), ending ad break gracefully")),void this.handleAdPodComplete();this.timing.hasTimeToStartAnotherAd()?this.tryNextAvailableAdWithRateLimit():(this.debug&&console.log("[AD-ERROR] Ad failed and not enough time remaining for another ad. Failed URLs:",this.timing.failedVastUrls.size),this.handleAdPodComplete())},e}(),If=function(){function e(e){var t=this;this.attached=!1,this.palPlaybackStarted=!1,Vh();var r=Ed();this.config=_(_({},r),e),this.video=e.videoElement,Sd(e.debugAdTiming),this.adPlayer=this.createAdPlayer(!1),this.palNonce=Vd(),this.cueManager=new yf(!!this.config.debugAdTiming,{onEarlyStartCue:function(e,r,i){t.startAdPrefetch(e,r,i)},onPlaybackCue:function(e,r){t.onScte35Marker(e,r)},isInAdBreak:function(){return t.adBreak.inAdBreak}}),this.adConfig=new kf(this.config,this.video),this.timing=new Ef(this.config,this.video,{onAdStopTimerFired:function(){return t.onAdStopTimerFired()},onAdStartTimerFired:function(e,r){t.startScte35AdBreak(e,r,null!=e.durationSeconds?1e3*e.durationSeconds:t.timing.expectedAdBreakDurationMs)},onWatchdogTimeout:function(){return t.adBreak.handleAdFailure()},onFailsafeTimeout:function(){return t.adBreak.handleAdFailure()},getAdState:function(){return{inAdBreak:t.adBreak.inAdBreak,showAds:t.adBreak.showAds,adPlaying:t.adPlayer.isAdPlaying()}}}),this.placeholder=new Sf(this.video,!!this.config.debugAdTiming),this.hlsEngine=new Tf(this.config,this.video,this.cueManager,this.timing,{onManifestParsed:function(e){return x(t,void 0,void 0,function(){return O(this,function(t){return[2,this.onManifestParsed(e)]})})},onScte35Cue:function(e,r){return t.cueManager.onScte35Cue(e,r)},activatePendingCuesForFragment:function(e){return t.cueManager.activatePendingScte35CuesForFragment(e)},onFatalDestroy:function(){return t.destroy()},isInAdBreak:function(){return t.adBreak.inAdBreak},hasPendingAdBreak:function(){return null!==t.adBreak.pendingAdBreak}}),this.adBreak=new bf({config:this.config,video:this.video,getAdPlayer:function(){return t.adPlayer},setAdPlayer:function(e){t.adPlayer=e},createAdPlayer:function(e){return t.createAdPlayer(e)},shouldContinueLiveStreamDuringAds:function(){return t.shouldContinueLiveStreamDuringAds()},isLiveStream:function(){return t.hlsEngine.isLiveStream},getLiveSyncPosition:function(){return t.hlsEngine.getLiveSyncPosition()},restartHlsLoad:function(e){return t.hlsEngine.restartLoadAt(e)},reloadLiveStream:function(){return t.hlsEngine.reloadLiveStream()},recoverMediaError:function(){return t.hlsEngine.recoverMediaError()},requiresMediaPipelineResetAfterAds:function(){return kd()},generatePodVastUrl:function(e,r){return t.generatePodVastUrl(e,r)},onAdClick:function(){return t.palNonce.sendAdClick()},onAdInteraction:function(e){return t.palNonce.sendAdTouch(e)}},this.timing,this.adConfig,this.cueManager,this.placeholder)}return Object.defineProperty(e.prototype,"debug",{get:function(){return!!this.config.debugAdTiming},enumerable:!1,configurable:!0}),e.prototype.createAdPlayer=function(e){var t;return this.debug&&console.log("[StormcloudVideoPlayer] Creating HLS ad player"),Md(this.video,_(_({continueLiveStreamDuringAds:e},this.config.licenseKey?{licenseKey:this.config.licenseKey}:{}),(null===(t=this.hlsEngine)||void 0===t?void 0:t.hls)?{mainHlsInstance:this.hlsEngine.hls}:{}))},e.prototype.generatePodVastUrl=function(e,t){var r=this.adConfig.resolvePodParams(t);return this.adConfig.generatePodVastUrl(e,r,this.adPlayer,this.palNonce,this.adBreak.inAdBreak)},e.prototype.load=function(){return x(this,void 0,void 0,function(){var e,t,r,i=this;return O(this,function(n){switch(n.label){case 0:this.attached||this.attach(),n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this.adConfig.fetchAdConfiguration()];case 2:return n.sent(),[3,4];case 3:return e=n.sent(),this.debug&&console.warn("[StormcloudVideoPlayer] Failed to fetch ad configuration:",e),[3,4];case 4:return t=this.config.ctvAdRequest?this.adConfig.getPalDescriptionUrl():void 0,function(e){void 0===e&&(e=1500);var t={};if("undefined"==typeof window)return Promise.resolve(t);var r=[],i=window.__tcfapi;"function"==typeof i&&r.push(new Promise(function(r){var n=!1;try{i("addEventListener",2,function(e,a){var s,o;if(!n&&a&&e&&("tcloaded"===e.eventStatus||"useractioncomplete"===e.eventStatus)){n=!0,t.gdpr=e.gdprApplies?"1":"0",t.storageAllowed=!e.gdprApplies||!0===(null===(o=null===(s=e.purpose)||void 0===s?void 0:s.consents)||void 0===o?void 0:o[1]),"string"==typeof e.tcString&&e.tcString&&(t.gdprConsent=e.tcString);try{i("removeEventListener",2,function(){},e.listenerId)}catch(e){}r()}})}catch(e){r()}setTimeout(function(){n||(n=!0,r())},e)}));var n=window.__uspapi;return"function"==typeof n&&r.push(new Promise(function(r){try{n("getUSPData",1,function(e,i){i&&"string"==typeof(null==e?void 0:e.uspString)&&e.uspString&&(t.usPrivacy=e.uspString),r()})}catch(e){r()}setTimeout(r,e)})),0===r.length?Promise.resolve(t):Promise.all(r).then(function(){return t})}().catch(function(){return{}}).then(function(e){var r;i.adConfig.consentSignals=e;var n=i.video.muted;return i.palNonce.generateNonce(_(_({videoWidth:i.video.offsetWidth||i.video.clientWidth||640,videoHeight:i.video.offsetHeight||i.video.clientHeight||480,adWillAutoPlay:!!i.config.autoplay,adWillPlayMuted:n,playerVolume:n?0:i.video.volume,continuousPlayback:null!==(r=i.config.lowLatencyMode)&&void 0!==r&&r},t?{descriptionUrl:t}:{}),null!=e.storageAllowed?{allowStorage:e.storageAllowed}:{}))}).catch(function(){}),this.adConfig.initializeTracking(),this.hlsEngine.shouldUseNativeHls(function(){return i.getStreamType()})?[4,this.hlsEngine.setupNativeHls()]:[3,6];case 5:return n.sent(),r=this.shouldContinueLiveStreamDuringAds(),this.debug&&console.log("[StormcloudVideoPlayer] Native HLS ad behavior:",{isLive:this.hlsEngine.isLiveStream,continueLiveStreamDuringAds:r}),this.adPlayer.destroy(),this.adPlayer=this.createAdPlayer(r),this.adPlayer.initialize(),[2];case 6:return this.hlsEngine.setupHls(),[2]}})})},e.prototype.onManifestParsed=function(e){return x(this,void 0,void 0,function(){var t,r;return O(this,function(i){return this.hlsEngine.reloadingLiveStream?(this.debug&&console.log("[StormcloudVideoPlayer] Manifest re-parsed after hard reload — skipping ad-player setup"),[2]):(this.adConfig.isVmapEnabled()||e||0!==this.adConfig.vmapBreaks.length||!this.adConfig.apiVastTagUrl||(t="synthetic-vod-preroll",this.adConfig.consumedVmapBreakIds.has(t)||(this.adConfig.vmapBreaks=[{id:t,startTimeMs:0,vastTagUrl:this.adConfig.apiVastTagUrl}],this.debug&&console.log("[StormcloudVideoPlayer] Injected synthetic VOD preroll from apiVastTagUrl"))),this.debug&&(r=this.shouldContinueLiveStreamDuringAds()?"live (main video continues muted during ads)":"vod (main video pauses during ads)",console.log("[StormcloudVideoPlayer] Stream type detected:",{isLive:e,allowNativeHls:this.config.allowNativeHls,adBehavior:r})),this.adPlayer.destroy(),this.adPlayer=this.createAdPlayer(this.shouldContinueLiveStreamDuringAds()),this.adPlayer.initialize(),[2])})})},e.prototype.attach=function(){var e=this;this.attached||(this.attached=!0,this.video.autoplay=!!this.config.autoplay,this.video.muted=!!this.config.muted,this.adPlayer.initialize(),this.adPlayer.updateOriginalMutedState(this.video.muted,this.video.volume),this.adBreak.attachImaEventListeners(),this.video.addEventListener("play",function(){e.palPlaybackStarted||e.adPlayer.isAdPlaying()||(e.palPlaybackStarted=!0,e.palNonce.sendPlaybackStart())}),this.endedHandler=function(){e.palPlaybackStarted&&(e.palPlaybackStarted=!1,e.palNonce.sendPlaybackEnd()),e.onVideoEnded()},this.video.addEventListener("ended",this.endedHandler),this.video.addEventListener("mousedown",function(t){e.palNonce.sendAdTouch(t)}),this.video.addEventListener("touchstart",function(t){e.palNonce.sendAdTouch(t)}),this.timeUpdateHandler=function(){e.onTimeUpdate(e.video.currentTime)},this.video.addEventListener("timeupdate",this.timeUpdateHandler),this.emptiedHandler=function(){if(e.hlsEngine.nativeHlsMode&&e.hlsEngine.videoSrcProtection&&!e.adPlayer.isAdPlaying()){e.debug&&console.log("[StormcloudVideoPlayer] Video src was cleared, restoring:",e.hlsEngine.videoSrcProtection);var t=e.video.currentTime,r=e.video.paused;e.video.src=e.hlsEngine.videoSrcProtection,e.video.currentTime=t,r||e.video.play().catch(function(){})}},this.video.addEventListener("emptied",this.emptiedHandler))},e.prototype.shouldContinueLiveStreamDuringAds=function(){if(this.config.pauseContentDuringAds)return!1;if(this.hlsEngine.isLiveStream)return!0;var e=this.video.duration;return!Number.isFinite(e)||e===1/0},e.prototype.onScte35Marker=function(e,t){var r,i,n;if(this.debug&&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.adBreak.pendingAdBreak}),"start"!==e.type){if("progress"===e.type&&this.adBreak.inAdBreak)return null!=e.durationSeconds&&this.timing.setAdBreakDurationBoundary(1e3*e.durationSeconds),this.timing.scheduleAdStopAtBreakBoundary(),void(!this.adPlayer.isAdPlaying()&&null===this.timing.activeAdRequestToken&&this.adBreak.adRequestQueue.length>0&&this.timing.hasTimeToStartAnotherAd()&&this.adBreak.tryNextAvailableAdWithRateLimit());if("end"===e.type){this.video.muted||(this.video.muted=!0,this.debug&&console.log("[StormcloudVideoPlayer] Muted video on SCTE end marker"));var a=this.timing.getRemainingAdMs(),s=this.adPlayer.isAdPlaying(),o=this.adBreak.adRequestQueue.length>0;return this.debug&&console.log("[StormcloudVideoPlayer] SCTE-35 end marker received:",{remaining:a,adPlaying:s,hasQueuedAds:o,activeAdRequest:null!==this.timing.activeAdRequestToken}),this.timing.scteAdBreakEndWallClockMs=Date.now(),this.timing.clearAdStartTimer(),this.timing.clearAdStopTimer(),s&&this.adPlayer.stop().catch(function(){}),void this.adBreak.handleAdPodComplete()}}else{if(this.adBreak.inAdBreak){if(null!=e.durationSeconds){var l=1e3*e.durationSeconds;(null==this.timing.expectedAdBreakDurationMs||l>this.timing.expectedAdBreakDurationMs)&&(this.timing.setAdBreakDurationBoundary(l),this.timing.scheduleAdStopAtBreakBoundary(),this.debug&&console.log("[StormcloudVideoPlayer] Updated ad break duration from subsequent marker: ".concat(l,"ms, remaining: ").concat(this.timing.getWallClockRemainingAdMs(),"ms")))}return}if(!this.adBreak.adDetectSentForCurrentBreak){this.adBreak.adDetectSentForCurrentBreak=!0;var u={};null!=e.durationSeconds&&(u.durationSeconds=e.durationSeconds),null!=e.ptsSeconds&&(u.ptsSeconds=e.ptsSeconds),Fh(this.config.licenseKey,_({source:"scte35",timestamp:(new Date).toISOString()},u),Ph(this.config)).catch(function(){})}var c=this.adBreak.pendingAdBreak&&this.adBreak.pendingAdBreak.vastUrls.length>0,d=null!=e.durationSeconds?1e3*e.durationSeconds:null!=(null===(r=this.adBreak.pendingAdBreak)||void 0===r?void 0:r.marker.durationSeconds)?1e3*this.adBreak.pendingAdBreak.marker.durationSeconds:void 0,h=function(e){var t=e.raw;if(!t)return!1;if(t.tag){var r=String(t.tag);return r.includes("EXT-X-CUE-OUT")||r.includes("EXT-X-CUE-IN")||r.includes("EXT-X-DATERANGE")}return t.id3||t.splice_command_type,!1}(e),f=null===(i=this.config.immediateManifestAds)||void 0===i||i;if(this.debug&&console.log("[StormcloudVideoPlayer] Ad start decision:",{isManifestMarker:h,forceImmediate:f,hasPts:"number"==typeof e.ptsSeconds,hasPrefetchedAds:c}),h&&f)this.debug&&console.log("[StormcloudVideoPlayer] Starting ad immediately (manifest-based)".concat(c?" with prefetched ads":"")),this.timing.clearAdStartTimer(),this.startScte35AdBreak(e,t,d);else if("number"==typeof e.ptsSeconds){var v=null!==(n=this.config.driftToleranceMs)&&void 0!==n?n:1e3,g=1e3*this.video.currentTime,p=g-this.timing.ptsDriftEmaMs,m=Math.floor(1e3*e.ptsSeconds-p);this.debug&&console.log("[StormcloudVideoPlayer] PTS-based timing calculation:",{nowMs:g,estCurrentPtsMs:p,markerPtsMs:1e3*e.ptsSeconds,deltaMs:m,tolerance:v}),m>v?(this.debug&&console.log("[StormcloudVideoPlayer] Scheduling ad start in ".concat(m,"ms")),this.timing.expectedAdBreakDurationMs=d,this.cueManager.scheduledScte35BreakKey=t,this.timing.scheduleAdStartIn(m,e,t)):(this.debug&&console.log("[StormcloudVideoPlayer] Starting ad immediately (within tolerance)"),this.timing.clearAdStartTimer(),this.startScte35AdBreak(e,t,d))}else this.debug&&console.log("[StormcloudVideoPlayer] Starting ad immediately (fallback)"),this.timing.clearAdStartTimer(),this.startScte35AdBreak(e,t,d)}},e.prototype.startScte35AdBreak=function(e,t,r){this.adBreak.inAdBreak=!0,this.cueManager.activeScte35BreakKey=null!=t?t:this.cueManager.pendingScte35CueKey,this.cueManager.scheduledScte35BreakKey=void 0,this.timing.currentAdBreakStartWallClockMs=this.timing.resolveScteBreakStartWallClockMs(e),this.timing.setAdBreakDurationBoundary(r),this.adBreak.handleAdStart(e),this.timing.scheduleAdStopAtBreakBoundary()},e.prototype.onAdStopTimerFired=function(){var e,t;if(this.adBreak.inAdBreak){var r=this.adPlayer.isAdPlaying(),i=Math.max(250,Math.floor(null!==(e=this.config.adBreakCheckIntervalMs)&&void 0!==e?e:1e3)),n=this.config.maxAdBreakExtensionMs,a="number"==typeof n&&n>0?n:0,s=null!==(t=this.timing.getAdBreakEndWallClockMs())&&void 0!==t?t:Date.now(),o=Math.max(0,Date.now()-s);r&&o<a?this.timing.scheduleAdStopCountdown(i):(this.debug&&console.log("[StormcloudVideoPlayer] Ad break boundary reached (overrun=".concat(o,"ms) - hard-stopping ads and resuming stream")),r&&this.adPlayer.stop().catch(function(){}),this.adBreak.handleAdPodComplete())}},e.prototype.startAdPrefetch=function(e,t,r){if(!this.adBreak.pendingAdBreak&&!this.adBreak.inAdBreak){var i,n=this.adConfig.findCurrentOrNextBreak(1e3*this.video.currentTime),a=this.adConfig.selectVastTagsForBreak(n);if(a&&a.length>0&&a[0])i=a[0];else{if(!this.adConfig.apiVastTagUrl)return void(this.debug&&console.warn("[StormcloudVideoPlayer] No VAST URL available for prefetch"));i=this.adConfig.apiVastTagUrl}this.adConfig.beginNewAdPod(),this.adConfig.podAssignedByPrefetch=!0;var s=null!=e.durationSeconds?1e3*e.durationSeconds:void 0,o=[this.generatePodVastUrl(i,s)];this.adBreak.pendingAdBreak=_(_({marker:e},void 0!==t?{detectedAtFragmentSn:t}:{}),{vastUrls:o,isFetching:!1,fetchStartTime:Date.now()}),this.cueManager.pendingScte35CueKey=r,this.adBreak.adDetectSentForCurrentBreak=!0;var l={};null!=e.durationSeconds&&(l.durationSeconds=e.durationSeconds),null!=e.ptsSeconds&&(l.ptsSeconds=e.ptsSeconds),void 0!==t&&(l.detectedAtFragmentSn=t),Fh(this.config.licenseKey,_({source:"scte35",timestamp:(new Date).toISOString()},l),Ph(this.config)).catch(function(){}),this.debug&&(console.log("[PREFETCH] Starting ad prefetch for upcoming ad break"),console.log("[PREFETCH] Pre-generated pod request URL"))}},e.prototype.onTimeUpdate=function(e){var t=this;if(this.adConfig.isVmapEnabled()&&0!==this.adConfig.vmapBreaks.length&&!this.adPlayer.isAdPlaying()&&!this.adBreak.inAdBreak){var r=1e3*e,i=this.adConfig.findBreakForTime(r);i&&this.handleVmapAdBreak(i,r).catch(function(e){t.debug&&console.warn("[StormcloudVideoPlayer] VMAP ad break failed gracefully:",e)})}},e.prototype.onVideoEnded=function(){var e=this;if(this.adConfig.isVmapEnabled()&&0!==this.adConfig.vmapBreaks.length&&!this.adPlayer.isAdPlaying()&&!this.adBreak.inAdBreak){var t=Number.isFinite(this.video.duration)?Math.floor(1e3*this.video.duration):0,r=this.adConfig.vmapBreaks.find(function(t){return-1===t.startTimeMs&&!e.adConfig.consumedVmapBreakIds.has(e.adConfig.getAdBreakKey(t))});r&&this.handleVmapAdBreak(r,t).catch(function(t){e.debug&&console.warn("[StormcloudVideoPlayer] VMAP post-roll failed gracefully:",t)})}},e.prototype.handleVmapAdBreak=function(e,t){return x(this,void 0,void 0,function(){var r,i,n,a,s,o,l,u,c;return O(this,function(d){switch(d.label){case 0:if(r=this.adConfig.getAdBreakKey(e),this.adConfig.consumedVmapBreakIds.has(r))return[2];if(null==(i=this.adConfig.resolveBreakStartMs(e)))return[2];if(n=null!==(c=e.durationMs)&&void 0!==c?c:0,a=i+n,!(n>0?t>=i&&t<a:t>=i))return[3,4];if(this.adConfig.consumedVmapBreakIds.add(r),!(s=this.adConfig.selectVastTagsForBreak(e))||0===s.length)return[2];o=s[0],l=s.slice(1),this.adBreak.adPodQueue=l,this.adPlayer.updateOriginalMutedState(this.video.muted,this.video.volume),this.adBreak.showAds=!0,this.adBreak.inAdBreak=!0,this.timing.currentAdBreakStartWallClockMs=Date.now(),d.label=1;case 1:return d.trys.push([1,3,,4]),[4,this.adBreak.playSingleAd(o)];case 2:return d.sent(),[3,4];case 3:return u=d.sent(),this.debug&&console.warn("[StormcloudVideoPlayer] VMAP ad request failed:",u),this.adBreak.handleAdPodComplete(),[3,4];case 4:return[2]}})})},e.prototype.getCurrentAdIndex=function(){return this.timing.currentAdIndex},e.prototype.getTotalAdsInBreak=function(){return this.timing.totalAdsInBreak},e.prototype.getAdRemainingMs=function(){return this.timing.getRemainingAdMs()},e.prototype.isAdPlaying=function(){return this.adBreak.inAdBreak&&this.adPlayer.isAdPlaying()},e.prototype.isShowingAds=function(){return this.adBreak.showAds},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.isLive=function(){return this.hlsEngine.isLiveStream},e.prototype.isLowLatencyStream=function(){return this.hlsEngine.isLowLatencyStream()},Object.defineProperty(e.prototype,"videoElement",{get:function(){return this.video},enumerable:!1,configurable:!0}),e.prototype.toggleMute=function(){!function(e,t,r){if(t.isAdPlaying()){var i=!t.getOriginalMutedState(),n=t.getOriginalVolume()||1;t.updateOriginalMutedState(i,e.volume),t.setAdVolume(i?0:n),r&&console.log("[StormcloudVideoPlayer] Mute toggle during ad - immediately applied:",i)}else e.muted=!e.muted,t.updateOriginalMutedState(e.muted,e.volume),r&&console.log("[StormcloudVideoPlayer] Muted:",e.muted)}(this.video,this.adPlayer,this.debug)},e.prototype.toggleFullscreen=function(){return e=this.video,t=this.debug,new Promise(function(r,i){if(document.fullscreenElement)document.exitFullscreen().then(function(){t&&console.log("[StormcloudVideoPlayer] Exited fullscreen"),r()}).catch(function(e){t&&console.error("[StormcloudVideoPlayer] Exit fullscreen error:",e),i(e)});else{var n=e.parentElement;if(!n)return void i(new Error("No parent container found for fullscreen"));n.requestFullscreen().then(function(){t&&console.log("[StormcloudVideoPlayer] Entered fullscreen"),r()}).catch(function(e){t&&console.error("[StormcloudVideoPlayer] Fullscreen error:",e),i(e)})}});var e,t},e.prototype.isMuted=function(){return e=this.video,(t=this.adPlayer).isAdPlaying()?t.getOriginalMutedState():e.muted;var e,t},e.prototype.setMuted=function(e){!function(e,t,r,i){var n=t.isAdPlaying();if(n&&r===e.muted)i&&console.log("[StormcloudVideoPlayer] setMuted reflective update during ad ignored",{muted:r});else{if(e.muted=r,n)return t.updateOriginalMutedState(r,e.volume),t.setAdVolume(r?0:1),void(i&&console.log("[StormcloudVideoPlayer] setMuted applied during ad",{muted:r}));t.updateOriginalMutedState(r,e.volume),i&&console.log("[StormcloudVideoPlayer] setMuted called:",r)}}(this.video,this.adPlayer,e,this.debug)},e.prototype.setVolume=function(e){!function(e,t,r,i){var n=Math.max(0,Math.min(1,r));t.isAdPlaying()?(t.setAdVolume(n),t.updateOriginalMutedState(0===n,n),i&&console.log("[StormcloudVideoPlayer] setVolume applied during ad",{volume:n})):(e.volume=n,e.muted=0===n,t.updateOriginalMutedState(0===n,n),i&&console.log("[StormcloudVideoPlayer] setVolume called:",n))}(this.video,this.adPlayer,e,this.debug)},e.prototype.getVolume=function(){return e=this.video,(t=this.adPlayer).isAdPlaying()?t.getAdVolume():e.volume;var e,t},e.prototype.isFullscreen=function(){return!!document.fullscreenElement},e.prototype.resize=function(){!function(e,t,r){if(r&&console.log("[StormcloudVideoPlayer] Resizing player"),t&&t.isAdPlaying()){var i=e.clientWidth||640,n=e.clientHeight||480;r&&console.log("[StormcloudVideoPlayer] Resizing ads manager to ".concat(i,"x").concat(n)),t.resize(i,n)}}(this.video,this.adPlayer,this.debug)},e.prototype.destroy=function(){var e;this.adBreak.stopContinuousFetching(),this.timing.destroy(),this.adBreak.clearPendingAdBreak(),this.placeholder.destroy(),this.timeUpdateHandler&&(this.video.removeEventListener("timeupdate",this.timeUpdateHandler),delete this.timeUpdateHandler),this.endedHandler&&(this.video.removeEventListener("ended",this.endedHandler),delete this.endedHandler),this.emptiedHandler&&(this.video.removeEventListener("emptied",this.emptiedHandler),delete this.emptiedHandler),this.adConfig.destroyTracking(),this.hlsEngine.destroy(),null===(e=this.adPlayer)||void 0===e||e.destroy(),this.palPlaybackStarted&&(this.palPlaybackStarted=!1,this.palNonce.sendPlaybackEnd()),this.palNonce.reset(),this.adBreak.adRequestQueue=[],this.timing.consecutiveFailures=0},e}(),Rf={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},Lf=J.createContext&&J.createContext(Rf),Pf=["attr","size","title"];function wf(){return wf=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var i in r)({}).hasOwnProperty.call(r,i)&&(e[i]=r[i])}return e},wf.apply(null,arguments)}function Cf(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,i)}return r}function Df(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Cf(Object(r),!0).forEach(function(t){_f(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Cf(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function _f(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=R(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var i=r.call(e,t||"default");if("object"!=R(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==R(t)?t:t+""}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Mf(e){return e&&e.map(function(e,t){return J.createElement(e.tag,Df({key:t},e.attr),Mf(e.child))})}function xf(e){return function(t){return J.createElement(Of,wf({attr:Df({},e.attr)},t),Mf(e.child))}}function Of(e){var t=function(t){var r,i=e.attr,n=e.size,a=e.title,s=function(e,t){if(null==e)return{};var r,i,n=function(e,t){if(null==e)return{};var r={};for(var i in e)if({}.hasOwnProperty.call(e,i)){if(-1!==t.indexOf(i))continue;r[i]=e[i]}return r}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)r=a[i],-1===t.indexOf(r)&&{}.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}(e,Pf),o=n||t.size||"1em";return t.className&&(r=t.className),e.className&&(r=(r?r+" ":"")+e.className),J.createElement("svg",wf({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},t.attr,i,s,{className:r,style:Df(Df({color:e.color||t.color},t.style),e.style),height:o,width:o,xmlns:"http://www.w3.org/2000/svg"}),a&&J.createElement("title",null,a),e.children)};return void 0!==Lf?J.createElement(Lf.Consumer,null,function(e){return t(e)}):t(Rf)}function Ff(e){return xf({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)}function Nf(e){return xf({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 Bf(e){return xf({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 Uf(e){return xf({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 Vf(e){return xf({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)}var Gf=function(e){var t=e.size,r=void 0===t?18:t;return Q.jsxs("svg",{width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",children:[Q.jsx("path",{d:"M9 4H4v5"}),Q.jsx("path",{d:"M20 9V4h-5"}),Q.jsx("path",{d:"M15 20h5v-5"}),Q.jsx("path",{d:"M4 15v5h5"})]})},Hf=function(e){var t=e.size,r=void 0===t?18:t;return Q.jsxs("svg",{width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",children:[Q.jsx("path",{d:"M4 9h5V4"}),Q.jsx("path",{d:"M15 4v5h5"}),Q.jsx("path",{d:"M20 15h-5v5"}),Q.jsx("path",{d:"M9 20v-5H4"})]})},Kf=["src","allowNativeHls","isLiveStream","licenseKey","isVmap","vmapUrl","lowLatencyMode","driftToleranceMs","vastMode","ctvAdRequest"],jf=16/9,qf=J.memo(function(e){var t=e.src,r=e.autoplay,i=e.muted,n=e.lowLatencyMode,a=e.allowNativeHls,s=e.isLiveStream,o=e.driftToleranceMs,l=e.immediateManifestAds,u=e.debugAdTiming,c=e.showCustomControls,d=e.hideLoadingIndicator,h=e.onVolumeToggle,f=e.onFullscreenToggle,v=e.onControlClick,g=e.onReady,p=e.wrapperClassName,m=e.wrapperStyle,y=e.className,k=e.style,E=e.controls,S=e.playsInline,T=e.preload,A=e.poster,b=e.children,I=e.licenseKey,R=e.vastMode,L=e.vastTagUrl,P=e.isVmap,w=e.vmapUrl,C=e.minSegmentsBeforePlay,D=e.ctvAdRequest,x=e.programTitle,O=e.channelName,F=M(e,["src","autoplay","muted","lowLatencyMode","allowNativeHls","isLiveStream","driftToleranceMs","immediateManifestAds","debugAdTiming","showCustomControls","hideLoadingIndicator","onVolumeToggle","onFullscreenToggle","onControlClick","onReady","wrapperClassName","wrapperStyle","className","style","controls","playsInline","preload","poster","children","licenseKey","vastMode","vastTagUrl","isVmap","vmapUrl","minSegmentsBeforePlay","ctvAdRequest","programTitle","channelName"]),B=$.useRef(null),U=$.useRef(null),V=$.useRef(null),G=$.useRef(null),H=$.useRef(null),K=N(J.useState({showAds:!1,currentIndex:0,totalAds:0,remainingSeconds:0}),2),j=K[0],q=K[1],W=N(J.useState(!0),2),Y=W[0],z=W[1],X=N(J.useState(!1),2),Z=X[0],ee=X[1],te=N(J.useState(!1),2),re=te[0],ie=te[1],ne=N(J.useState(!1),2),ae=ne[0],se=ne[1],oe=N(J.useState(0),2),le=oe[0],ue=oe[1],ce=N(J.useState(0),2),de=ce[0],he=ce[1],fe=N(J.useState(1),2),ve=fe[0],ge=fe[1],pe=N(J.useState(1),2),me=pe[0],ye=pe[1],ke=N(J.useState(!1),2),Ee=ke[0],Se=ke[1],Te=N(J.useState(!1),2),Ae=Te[0],be=Te[1],Ie=N(J.useState(!0),2),Re=Ie[0],Le=Ie[1],Pe=N(J.useState(!1),2),we=Pe[0],Ce=Pe[1],De=N(J.useState(!1),2),_e=De[0],Me=De[1],xe=N(J.useState(!1),2),Oe=xe[0],Fe=xe[1],Ne=N(J.useState(!0),2),Be=Ne[0],Ue=Ne[1],Ve=N(J.useState("undefined"!=typeof window?window.innerWidth:1920),2),Ge=Ve[0],He=Ve[1],Ke=N(J.useState("undefined"!=typeof window&&window.innerHeight>window.innerWidth),2),je=Ke[0],qe=Ke[1],We=N(J.useState(jf),2),Ye=We[0],ze=We[1],Xe=Ge<480?.7:Ge<768?.8:Ge<1024?.9:1,Qe=$.useCallback(function(){G.current&&clearTimeout(G.current),Ue(!0),G.current=window.setTimeout(function(){Ee||Ae||Ue(!1)},3e3)},[Ee,Ae]),$e=$.useCallback(function(){Qe()},[Qe]),Je=$.useCallback(function(){Ee||Ae||Ue(!1)},[Ee,Ae]),Ze=function(e){if(!isFinite(e))return"0:00:00";var t=Math.floor(e/3600),r=Math.floor(e%3600/60),i=Math.floor(e%60);return"".concat(t,":").concat(r.toString().padStart(2,"0"),":").concat(i.toString().padStart(2,"0"))},et=function(e){if(U.current&&isFinite(e)){var t=Math.max(0,Math.min(1,e));U.current.setVolume(t)}},tt=(null==t?void 0:t.toLowerCase().includes(".m3u8"))||(null==t?void 0:t.toLowerCase().includes("/hls/")),rt=c&&(!tt||!(!0===s)),it=$.useMemo(function(){return Kf.map(function(t){return"".concat(t,":").concat(e[t])}).join("|")},[t,a,s,I,P,w,n,o,R]);$.useEffect(function(){if("undefined"!=typeof window){var e=B.current;if(e&&t){if(!I)return Fe(!0),Le(!1),void console.warn("StormcloudVideoPlayer: License key is required but not provided. Please set the licenseKey prop to use the player.");if(Fe(!1),u&&console.log("[StormcloudUI] Initializing player, isLoading=true"),U.current){try{U.current.destroy()}catch(e){}U.current=null}var d={src:t,videoElement:e};void 0!==r&&(d.autoplay=r),void 0!==i&&(d.muted=i),void 0!==n&&(d.lowLatencyMode=n),void 0!==a&&(d.allowNativeHls=a),void 0!==s&&(d.isLiveStream=s),void 0!==o&&(d.driftToleranceMs=o),void 0!==l&&(d.immediateManifestAds=l),void 0!==u&&(d.debugAdTiming=u),void 0!==c&&(d.showCustomControls=c),void 0!==h&&(d.onVolumeToggle=h),void 0!==f&&(d.onFullscreenToggle=f),void 0!==v&&(d.onControlClick=v),void 0!==I&&(d.licenseKey=I),void 0!==R&&(d.vastMode=R),void 0!==L&&(d.vastTagUrl=L),void 0!==P&&(d.isVmap=P),void 0!==w&&(d.vmapUrl=w),void 0!==C&&(d.minSegmentsBeforePlay=C),void 0!==D&&(d.ctvAdRequest=D),void 0!==x&&(d.programTitle=x),void 0!==O&&(d.channelName=O);var p=new If(d);return U.current=p,p.load().then(function(){var e=p.shouldShowNativeControls();z(e),u&&console.log("[StormcloudUI] Player loaded successfully, waiting for video ready"),null==g||g(p)}).catch(function(e){console.error("StormcloudVideoPlayer: Failed to load player:",e),Le(!1),null==g||g(p)}),function(){try{p.destroy()}catch(e){}U.current=null}}}},[it]),$.useEffect(function(){if(U.current)try{void 0!==r&&U.current.videoElement&&(U.current.videoElement.autoplay=r),void 0===i||U.current.isShowingAds()||U.current.setMuted(i)}catch(e){console.warn("Failed to update player properties:",e)}},[r,i]),$.useEffect(function(){if(U.current){var e=setInterval(function(){var e,t;if(U.current){var r=U.current.isShowingAds(),i="true"===(null===(t=null===(e=B.current)||void 0===e?void 0:e.dataset)||void 0===t?void 0:t.stormcloudAdPlaying),n=r||i,a=U.current.getCurrentAdIndex(),s=U.current.getTotalAdsInBreak(),o=U.current.getAdRemainingMs(),l=n?Math.max(0,Math.ceil(o/1e3)):0;q(function(e){return e.showAds!==n||e.currentIndex!==a||e.totalAds!==s||e.remainingSeconds!==l?(n&&!e.showAds&&Me(!1),{showAds:n,currentIndex:a,totalAds:s,remainingSeconds:l}):e})}},50);return function(){return clearInterval(e)}}},[]),$.useEffect(function(){if("undefined"!=typeof window&&U.current){var e=function(){U.current&&B.current&&"function"==typeof U.current.resize&&U.current.resize(),He(window.innerWidth),qe(window.innerHeight>window.innerWidth)};return window.addEventListener("resize",e),function(){return window.removeEventListener("resize",e)}}},[]),$.useEffect(function(){if(U.current&&B.current){var e=setInterval(function(){if(U.current&&B.current){ee(U.current.isMuted()),se(!B.current.paused);var e=B.current.currentTime;ue(isFinite(e)?e:0);var t=B.current.duration;he(isFinite(t)?t:0);var r=U.current.getVolume();ge(isFinite(r)?Math.max(0,Math.min(1,r)):1);var i=B.current.playbackRate;ye(isFinite(i)&&i>0?i:1)}ie(document.fullscreenElement===H.current)},200),t=function(){ie(document.fullscreenElement===H.current)};return document.addEventListener("fullscreenchange",t),function(){clearInterval(e),document.removeEventListener("fullscreenchange",t)}}},[]),$.useEffect(function(){if(B.current){var e=function(){var e,t=B.current;t&&(t.videoWidth>0&&t.videoHeight>0&&ze(t.videoWidth/t.videoHeight),t.offsetHeight),u&&console.log("[StormcloudUI] Video event: loadedmetadata, readyState:",null===(e=B.current)||void 0===e?void 0:e.readyState)},t=function(){var e;u&&console.log("[StormcloudUI] Video event: loadeddata, readyState:",null===(e=B.current)||void 0===e?void 0:e.readyState)},r=function(){var e;u&&console.log("[StormcloudUI] Video event: loadstart, readyState:",null===(e=B.current)||void 0===e?void 0:e.readyState)},i=function(){var e;Le(!1),V.current&&(clearTimeout(V.current),V.current=null),Ce(!1),u&&console.log("[StormcloudUI] Video event: canplay, readyState:",null===(e=B.current)||void 0===e?void 0:e.readyState,"- clearing loading state, isLoading=false")},n=function(){var e;Le(!1),V.current&&(clearTimeout(V.current),V.current=null),Ce(!1),u&&console.log("[StormcloudUI] Video event: canplaythrough, readyState:",null===(e=B.current)||void 0===e?void 0:e.readyState,"- clearing loading state, isLoading=false")},a=function(){var e;V.current&&clearTimeout(V.current),V.current=window.setTimeout(function(){var e;Ce(!0),u&&console.log("[StormcloudUI] Video buffering detected (after 300ms delay), readyState:",null===(e=B.current)||void 0===e?void 0:e.readyState,"- showing spinner, isBuffering=true")},300),u&&console.log("[StormcloudUI] Video event: waiting, readyState:",null===(e=B.current)||void 0===e?void 0:e.readyState,"- buffering delay started (300ms)")},s=function(){var e;Le(!1),V.current&&(clearTimeout(V.current),V.current=null),Ce(!1),Me(!1),u&&console.log("[StormcloudUI] Video event: playing, readyState:",null===(e=B.current)||void 0===e?void 0:e.readyState,"- playback started, isLoading=false, isBuffering=false")},o=function(){var e,t,r,i=(null===(e=U.current)||void 0===e?void 0:e.isShowingAds())||"true"===(null===(r=null===(t=B.current)||void 0===t?void 0:t.dataset)||void 0===r?void 0:r.stormcloudAdPlaying);U.current&&!i?Me(!0):Me(!1)},l=function(){Me(!0)},c=B.current;return c.addEventListener("loadstart",r),c.addEventListener("loadedmetadata",e),c.addEventListener("loadeddata",t),c.addEventListener("canplay",i),c.addEventListener("canplaythrough",n),c.addEventListener("waiting",a),c.addEventListener("playing",s),c.addEventListener("pause",o),c.addEventListener("ended",l),c.paused&&Me(!0),function(){V.current&&(clearTimeout(V.current),V.current=null),c.removeEventListener("loadstart",r),c.removeEventListener("loadedmetadata",e),c.removeEventListener("loadeddata",t),c.removeEventListener("canplay",i),c.removeEventListener("canplaythrough",n),c.removeEventListener("waiting",a),c.removeEventListener("playing",s),c.removeEventListener("pause",o),c.removeEventListener("ended",l)}}},[u]),$.useEffect(function(){ze(jf)},[t]),$.useEffect(function(){return function(){G.current&&clearTimeout(G.current)}},[]);var nt=de>0?le/de*100:0,at=Z||0===ve?Nf:ve<.5?Bf:Ff;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-loading-glow {\n 0%, 100% { opacity: 0.85; transform: scale(1); }\n 50% { opacity: 1; transform: scale(1.05); }\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:H,className:"sc-wrapper ".concat(p||""),onMouseMove:$e,onMouseLeave:Je,style:_({display:"flex",alignItems:"center",justifyContent:"center",position:re?"fixed":"relative",top:re?0:void 0,left:re?0:void 0,overflow:"hidden",width:re?"100vw":"100%",height:re?"100vh":"auto",minHeight:re?"100vh":"auto",aspectRatio:re?void 0:Ye,maxWidth:re?"100vw":"100%",maxHeight:re?"100vh":"none",zIndex:re?999999:void 0,backgroundColor:"#000",borderRadius:re?0:void 0,boxShadow:re?"none":void 0},m),children:[Q.jsx("video",_({ref:B,className:y,style:_({display:"block",width:"100%",height:"100%",maxWidth:"100%",maxHeight:re?"100%":"none",objectFit:re?"cover":"contain",backgroundColor:"#000",aspectRatio:re?"unset":void 0},k),controls:Y&&E&&!c,playsInline:S,preload:T,poster:A},F,{children:b})),(Re||we)&&!d&&Q.jsxs("div",{className:"sc-loading-indicator",style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",zIndex:20,width:"".concat(Math.max(34,38*Xe),"px"),height:"".concat(Math.max(34,38*Xe),"px"),display:"flex",alignItems:"center",justifyContent:"center",animation:"sc-loading-glow 1.4s ease-in-out infinite",filter:"drop-shadow(0 6px 14px rgba(0, 0, 0, 0.55))"},children:[Q.jsx("div",{style:{position:"absolute",inset:0,borderRadius:"50%",border:"3px solid rgba(255, 255, 255, 0.25)",borderTopColor:"#ff0000",borderRightColor:"rgba(255, 255, 255, 0.85)",animation:"sc-spin 0.8s linear infinite"}}),Q.jsx("div",{style:{width:"7px",height:"7px",borderRadius:"50%",background:"#ff0000",boxShadow:"0 0 10px rgba(255, 0, 0, 0.65)"}})]}),Oe&&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."]})]}),j.showAds&&Q.jsx("div",{style:{position:"absolute",top:"".concat(12*Xe,"px"),left:"".concat(12*Xe,"px"),zIndex:50,display:"flex",alignItems:"center",gap:"8px",pointerEvents:"none",animation:"sc-fade-in 0.3s ease"},children:Q.jsx("div",{style:{background:"rgba(234, 179, 8, 0.95)",color:"#111",padding:"".concat(4*Xe,"px ").concat(12*Xe,"px"),borderRadius:"6px",fontSize:"".concat(11*Xe,"px"),fontWeight:700,letterSpacing:"0.08em",textTransform:"uppercase",boxShadow:"0 2px 12px rgba(234, 179, 8, 0.35)"},children:"Ad ".concat(Math.max(1,j.currentIndex))})}),_e&&!Re&&!we&&!Oe&&!j.showAds&&Q.jsx("div",{onClick:function(){var e;B.current&&B.current.paused&&(B.current.src||B.current.currentSrc&&""!==B.current.currentSrc||B.current.readyState>=1?(null===(e=B.current.play())||void 0===e||e.catch(function(e){console.error("[StormcloudVideoPlayer] Failed to play:",e)}),Me(!1)):console.warn("[StormcloudVideoPlayer] Cannot play: video has no valid source"))},style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",zIndex:15,cursor:"pointer",background:"rgba(0, 0, 0, 0.55)",backdropFilter:"blur(8px)",borderRadius:"50%",width:"".concat(92*Xe,"px"),height:"".concat(92*Xe,"px"),display:"flex",alignItems:"center",justifyContent:"center",transition:"background 0.2s ease, transform 0.2s ease",animation:"sc-fade-in 0.2s ease"},onMouseEnter:function(e){e.currentTarget.style.background="rgba(0, 0, 0, 0.72)",e.currentTarget.style.transform="translate(-50%, -50%) scale(1.06)"},onMouseLeave:function(e){e.currentTarget.style.background="rgba(0, 0, 0, 0.55)",e.currentTarget.style.transform="translate(-50%, -50%) scale(1)"},title:"Play",children:Q.jsx(Uf,{size:Math.max(24,32*Xe),color:"white",style:{marginLeft:"4px"}})}),rt&&!Oe?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*Xe,"px ").concat(12*Xe,"px ").concat(8*Xe,"px"),zIndex:10,opacity:Be||j.showAds?1:0,transform:Be||j.showAds?"translateY(0)":"translateY(6px)",pointerEvents:Be||j.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*Xe,"px"),cursor:"pointer",position:"relative",transition:"height 0.1s ease"},onClick:function(e){if(B.current&&de>0&&isFinite(de)){var t=e.currentTarget.getBoundingClientRect(),r=e.clientX-t.left,i=Math.max(0,Math.min(1,r/t.width))*de;isFinite(i)&&i>=0&&i<=de&&(B.current.currentTime=i)}Qe()},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:j.showAds?"#f5c518":"#ff0000",borderRadius:"1.5px",width:"".concat(nt,"%"),transition:"width 0.15s linear"}}),Q.jsx("div",{className:"sc-progress-thumb",style:{position:"absolute",top:"50%",left:"".concat(nt,"%"),transform:"translate(-50%, -50%) scale(0)",width:"13px",height:"13px",background:j.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*Xe,"px")},children:[Q.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"".concat(8*Xe,"px")},children:[Q.jsx("button",{className:"sc-ctrl-btn",onClick:function(){var e;B.current&&(B.current.paused?B.current.src||B.current.currentSrc&&""!==B.current.currentSrc||B.current.readyState>=1?(null===(e=B.current.play())||void 0===e||e.catch(function(e){console.error("[StormcloudVideoPlayer] Failed to play:",e)}),Me(!1)):console.warn("[StormcloudVideoPlayer] Cannot play: video has no valid source"):(B.current.pause(),Me(!0)));Qe()},style:{padding:"".concat(8*Xe,"px"),borderRadius:"50%",minWidth:"".concat(36*Xe,"px"),minHeight:"".concat(36*Xe,"px")},title:ae?"Pause":"Play",children:ae?Q.jsx(Vf,{size:Math.max(14,18*Xe)}):Q.jsx(Uf,{size:Math.max(14,18*Xe),style:{marginLeft:"2px"}})}),Q.jsxs("div",{style:{display:"flex",alignItems:"center",paddingRight:"".concat(6*Xe,"px")},onMouseEnter:function(){return Se(!0)},onMouseLeave:function(){return Se(!1)},children:[Q.jsx("button",{className:"sc-ctrl-btn",onClick:function(){U.current&&U.current.toggleMute(),null==h||h(),Qe()},style:{padding:"".concat(8*Xe,"px"),borderRadius:"50%",minWidth:"".concat(36*Xe,"px"),minHeight:"".concat(36*Xe,"px")},title:Z?"Unmute":"Mute",children:Q.jsx(at,{size:Math.max(14,18*Xe)})}),Q.jsx("div",{style:{width:Ee?"".concat(68*Xe,"px"):"0px",overflow:"hidden",transition:"width 0.2s cubic-bezier(0.4, 0, 0.2, 1)",display:"flex",alignItems:"center",paddingLeft:Ee?"".concat(3*Xe,"px"):"0",paddingRight:Ee?"".concat(8*Xe,"px"):"0"},children:Q.jsxs("div",{style:{position:"relative",width:"".concat(56*Xe,"px"),height:"3px",cursor:"pointer",borderRadius:"1.5px"},onMouseDown:function(e){e.preventDefault();var t=e.currentTarget,r=function(e){var r=t.getBoundingClientRect();et(Math.max(0,Math.min(1,(e.clientX-r.left)/r.width)))},i=function(){document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",i)};document.addEventListener("mousemove",r),document.addEventListener("mouseup",i);var n=t.getBoundingClientRect();et(Math.max(0,Math.min(1,(e.clientX-n.left)/n.width)))},onClick:function(e){e.stopPropagation();var t=e.currentTarget.getBoundingClientRect();et(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*(Z?0:ve),"%"),background:"#fff",borderRadius:"1.5px",transition:"width 0.1s ease-out"}}),Q.jsx("div",{style:{position:"absolute",top:"50%",left:"".concat(100*(Z?0:ve),"%"),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*Xe,"px"),fontFamily:"Roboto, 'Segoe UI', Arial, sans-serif",color:"rgba(255, 255, 255, 0.9)",display:Ge<480?"none":"block",fontVariantNumeric:"tabular-nums",userSelect:"none",marginLeft:"".concat(4*Xe,"px")},children:[Ze(le)," ",Q.jsx("span",{style:{color:"rgba(255,255,255,0.5)"},children:"/"})," ",Ze(de)]})]}),Q.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"".concat(8*Xe,"px")},children:[Q.jsxs("div",{style:{position:"relative",display:Ge<600?"none":"block"},children:[Q.jsxs("button",{className:"sc-ctrl-btn",onClick:function(){be(!Ae),Qe()},style:{padding:"".concat(6*Xe,"px ").concat(10*Xe,"px"),borderRadius:"".concat(6*Xe,"px"),fontSize:"".concat(13*Xe,"px"),fontFamily:"'SF Mono', 'Cascadia Code', monospace",fontWeight:"600",minHeight:"".concat(32*Xe,"px")},title:"Playback Speed",children:[me,"x"]}),Ae&&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,B.current&&isFinite(t)&&t>0&&(B.current.playbackRate=t),void be(!1);var t},style:{display:"block",width:"100%",padding:"".concat(8*Xe,"px ").concat(14*Xe,"px"),background:me===e?"rgba(255, 255, 255, 0.12)":"transparent",border:"none",color:me===e?"#fff":"rgba(255, 255, 255, 0.7)",cursor:"pointer",fontSize:"".concat(12*Xe,"px"),fontFamily:"'SF Mono', monospace",fontWeight:me===e?"700":"500",textAlign:"center",transition:"background 0.15s ease, color 0.15s ease"},onMouseEnter:function(t){me!==e&&(t.target.style.background="rgba(255, 255, 255, 0.08)",t.target.style.color="#fff")},onMouseLeave:function(t){me!==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(){f?f():H.current&&(document.fullscreenElement?document.exitFullscreen().catch(function(){}):H.current.requestFullscreen().catch(function(){})),Qe()},style:{padding:"".concat(8*Xe,"px"),borderRadius:"50%",minWidth:"".concat(36*Xe,"px"),minHeight:"".concat(36*Xe,"px")},title:re?"Exit Fullscreen":"Enter Fullscreen",children:re?Q.jsx(Hf,{size:Math.max(14,18*Xe)}):Q.jsx(Gf,{size:Math.max(14,18*Xe)})})]})]})]}):c&&!Oe&&Q.jsxs(Q.Fragment,{children:[Q.jsxs("div",{style:{position:"absolute",top:"".concat(10*Xe,"px"),left:"".concat(10*Xe,"px"),display:"flex",alignItems:"center",gap:"6px",zIndex:10,opacity:Be?1:0,transition:"opacity 0.35s ease"},children:[Q.jsx("div",{style:{width:"8px",height:"8px",borderRadius:"50%",background:"#ff3b30",animation:"sc-pulse 1.5s ease-in-out infinite",flexShrink:0}}),Q.jsx("span",{style:{fontSize:"".concat(12*Xe,"px"),fontFamily:"'SF Pro Display', 'Segoe UI', Arial, sans-serif",fontWeight:700,letterSpacing:"0.08em",color:"#fff",textShadow:"0 1px 3px rgba(0,0,0,0.6)",userSelect:"none"},children:"LIVE"})]}),Q.jsxs("div",{className:"sc-controls-bar",style:{position:"absolute",bottom:"".concat(10*Xe,"px"),right:"".concat(10*Xe,"px"),display:"flex",flexDirection:je?"column":"row",alignItems:je?"flex-end":"center",gap:"".concat(8*Xe,"px"),zIndex:10,opacity:Be?1:0,transform:Be?"translateY(0)":"translateY(4px)",pointerEvents:Be?"auto":"none"},children:[Q.jsxs("div",{style:{display:"flex",alignItems:"center",background:"rgba(0, 0, 0, 0.6)",borderRadius:"".concat(18*Xe,"px"),padding:"2px",paddingRight:"".concat(8*Xe,"px")},onMouseEnter:function(){return Se(!0)},onMouseLeave:function(){return Se(!1)},children:[Q.jsx("button",{className:"sc-ctrl-btn",onClick:function(){U.current&&U.current.toggleMute(),null==h||h(),Qe()},style:{padding:"".concat(8*Xe,"px"),borderRadius:"50%",minWidth:"".concat(36*Xe,"px"),minHeight:"".concat(36*Xe,"px")},title:Z?"Unmute":"Mute",children:Q.jsx(at,{size:Math.max(14,18*Xe)})}),Q.jsx("div",{style:{width:Ee?"".concat(68*Xe,"px"):"0px",overflow:"hidden",transition:"width 0.2s cubic-bezier(0.4, 0, 0.2, 1)",display:"flex",alignItems:"center",paddingLeft:Ee?"".concat(3*Xe,"px"):"0",paddingRight:Ee?"".concat(10*Xe,"px"):"0"},children:Q.jsxs("div",{style:{position:"relative",width:"".concat(56*Xe,"px"),height:"3px",cursor:"pointer",borderRadius:"1.5px"},onMouseDown:function(e){e.preventDefault();var t=e.currentTarget,r=function(e){var r=t.getBoundingClientRect();et(Math.max(0,Math.min(1,(e.clientX-r.left)/r.width)))},i=function(){document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",i)};document.addEventListener("mousemove",r),document.addEventListener("mouseup",i);var n=t.getBoundingClientRect();et(Math.max(0,Math.min(1,(e.clientX-n.left)/n.width)))},onClick:function(e){e.stopPropagation();var t=e.currentTarget.getBoundingClientRect();et(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*(Z?0:ve),"%"),background:"#fff",borderRadius:"1.5px",transition:"width 0.1s ease-out"}}),Q.jsx("div",{style:{position:"absolute",top:"50%",left:"".concat(100*(Z?0:ve),"%"),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(){f?f():H.current&&(document.fullscreenElement?document.exitFullscreen().catch(function(){}):H.current.requestFullscreen().catch(function(){})),Qe()},style:{padding:"".concat(8*Xe,"px"),borderRadius:"50%",minWidth:"".concat(36*Xe,"px"),minHeight:"".concat(36*Xe,"px"),background:"rgba(0, 0, 0, 0.6)"},title:re?"Exit Fullscreen":"Enter Fullscreen",children:re?Q.jsx(Hf,{size:Math.max(14,18*Xe)}):Q.jsx(Gf,{size:Math.max(14,18*Xe)})})]})]}),v&&Q.jsx("div",{onClick:v,style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:1,cursor:"pointer"}})]})]})},function(e,t){var r,i,n,a,s,o;try{for(var l=F(Kf),u=l.next();!u.done;u=l.next()){if(e[v=u.value]!==t[v])return!1}}catch(e){r={error:e}}finally{try{u&&!u.done&&(i=l.return)&&i.call(l)}finally{if(r)throw r.error}}try{for(var c=F(["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=F(["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}),Wf=function(){},Yf={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:"",isVmap:!1,vmapUrl:"",adFailsafeTimeoutMs:1e4,minSegmentsBeforePlay:2,onStart:Wf,onPlay:Wf,onPause:Wf,onBuffer:Wf,onBufferEnd:Wf,onEnded:Wf,onError:Wf,onDuration:Wf,onSeek:Wf,onProgress:Wf,onVolumeToggle:Wf,onFullscreenToggle:Wf,onControlClick:Wf},zf=$.lazy,Xf=function(e,t){var r=_({},e);return t.forEach(function(e){delete r[e]}),r},Qf=function(e){return"undefined"!=typeof window&&window.MediaStream&&e instanceof window.MediaStream},$f=function(e){for(var t,r,i=[],n=1;n<arguments.length;n++)i[n-1]=arguments[n];if(!i.length)return e;var a=i.shift();if(Jf(e)&&Jf(a))for(var s in a)Jf(a[s])?(e[s]||Object.assign(e,((t={})[s]={},t)),$f(e[s],a[s])):Object.assign(e,((r={})[s]=a[s],r));return $f.apply(void 0,B([e],N(i),!1))},Jf=function(e){return e&&"object"===R(e)&&!Array.isArray(e)},Zf="undefined"!=typeof window&&window.document,ev="undefined"!=typeof self&&self.window&&self.window.document,tv=Zf&&/iPad|iPhone|iPod/.test(navigator.userAgent),rv=Zf&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent),iv=/\.(m3u8)($|\?)/i,nv=/\/hls\//i,av=/\.(mpd)($|\?)/i,sv=/\.(mp4|webm|ogg|avi|mov|wmv|flv|mkv)($|\?)/i,ov=/\.(mp3|wav|ogg|aac|wma|flac|m4a)($|\?)/i,lv={hls:function(e){return!(!e||"string"!=typeof e)&&(iv.test(e)||nv.test(e))},dash:function(e){return!(!e||"string"!=typeof e)&&av.test(e)},video:function(e){return!(!e||"string"!=typeof e)&&sv.test(e)},audio:function(e){return!(!e||"string"!=typeof e)&&ov.test(e)},file:function(e){return!(!e||"string"!=typeof e)&&(sv.test(e)||ov.test(e))}},uv=function(e){function t(){var t=e.apply(this,B([],N(arguments),!1))||this;return t.player=null,t.mounted=!1,t.load=function(){return x(t,void 0,void 0,function(){var e,t,r,i,n,a,s,o;return O(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.isLiveStream&&(e.isLiveStream=this.props.isLiveStream),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),void 0!==this.props.ctvAdRequest&&(e.ctvAdRequest=this.props.ctvAdRequest),this.player=new If(e),null===(i=(r=this.props).onMount)||void 0===i||i.call(r,this),[4,this.player.load()];case 2:return l.sent(),this.mounted&&(null===(a=(n=this.props).onReady)||void 0===a||a.call(n)),[3,4];case 3:return t=l.sent(),this.mounted&&(null===(o=(s=this.props).onError)||void 0===o||o.call(s,t)),[3,4];case 4:return[2]}})})},t.play=function(){var e,r,i;if(t.props.videoElement){var n=t.props.videoElement;n.src||n.currentSrc&&""!==n.currentSrc||n.readyState>=1?(null===(e=n.play())||void 0===e||e.catch(function(e){var r,i;console.error("[HlsPlayer] Failed to play:",e),null===(i=(r=t.props).onError)||void 0===i||i.call(r,e)}),null===(i=(r=t.props).onPlay)||void 0===i||i.call(r)):console.warn("[HlsPlayer] Cannot play: video has no valid source")}},t.pause=function(){var e,r;t.props.videoElement&&(t.props.videoElement.pause(),null===(r=(e=t.props).onPause)||void 0===r||r.call(e))},t.stop=function(){t.pause(),t.props.videoElement&&(t.props.videoElement.currentTime=0)},t.seekTo=function(e,r){t.props.videoElement&&(t.props.videoElement.currentTime=e,r||t.pause())},t.setVolume=function(e){t.props.videoElement&&(t.props.videoElement.volume=Math.max(0,Math.min(1,e)))},t.mute=function(){t.props.videoElement&&(t.props.videoElement.muted=!0)},t.unmute=function(){t.props.videoElement&&(t.props.videoElement.muted=!1)},t.setPlaybackRate=function(e){t.props.videoElement&&e>0&&(t.props.videoElement.playbackRate=e)},t.getDuration=function(){return t.props.videoElement&&isFinite(t.props.videoElement.duration)?t.props.videoElement.duration:null},t.getCurrentTime=function(){return t.props.videoElement&&isFinite(t.props.videoElement.currentTime)?t.props.videoElement.currentTime:null},t.getSecondsLoaded=function(){return t.props.videoElement&&t.props.videoElement.buffered.length>0?t.props.videoElement.buffered.end(t.props.videoElement.buffered.length-1):null},t.getInternalPlayer=function(e){return void 0===e&&(e="player"),"player"===e?t.player:"video"===e?t.props.videoElement:"hls"===e&&t.player?t.player.hls:null},t}return D(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=lv.hls,t}($.Component),cv=function(e){function t(){var t=e.apply(this,B([],N(arguments),!1))||this;return t.mounted=!1,t.ready=!1,t.load=function(){var e,r;if(t.props.videoElement&&t.props.src){var i=t.props.videoElement,n=function(){var e,r;t.mounted&&!t.ready&&(t.ready=!0,null===(r=(e=t.props).onReady)||void 0===r||r.call(e))},a=function(){var e,r;t.mounted&&(null===(r=(e=t.props).onPlay)||void 0===r||r.call(e))},s=function(){var e,r;t.mounted&&(null===(r=(e=t.props).onPause)||void 0===r||r.call(e))},o=function(){var e,r;t.mounted&&(null===(r=(e=t.props).onEnded)||void 0===r||r.call(e))},l=function(e){var r,i;t.mounted&&(null===(i=(r=t.props).onError)||void 0===i||i.call(r,e))},u=function(){var e,r;t.mounted&&(null===(r=(e=t.props).onLoaded)||void 0===r||r.call(e))};return i.addEventListener("loadedmetadata",n),i.addEventListener("play",a),i.addEventListener("pause",s),i.addEventListener("ended",o),i.addEventListener("error",l),i.addEventListener("loadeddata",u),i.src=t.props.src,void 0!==t.props.autoplay&&(i.autoplay=t.props.autoplay),void 0!==t.props.muted&&(i.muted=t.props.muted),void 0!==t.props.loop&&(i.loop=t.props.loop),void 0!==t.props.controls&&(i.controls=t.props.controls),void 0!==t.props.playsInline&&(i.playsInline=t.props.playsInline),void 0!==t.props.preload&&(i.preload=t.props.preload),void 0!==t.props.poster&&(i.poster=t.props.poster),null===(r=(e=t.props).onMount)||void 0===r||r.call(e,t),function(){i.removeEventListener("loadedmetadata",n),i.removeEventListener("play",a),i.removeEventListener("pause",s),i.removeEventListener("ended",o),i.removeEventListener("error",l),i.removeEventListener("loadeddata",u)}}},t.play=function(){var e;if(t.props.videoElement){var r=t.props.videoElement;r.src||r.currentSrc&&""!==r.currentSrc||r.readyState>=1?null===(e=r.play())||void 0===e||e.catch(function(e){var r,i;console.error("[FilePlayer] Failed to play:",e),null===(i=(r=t.props).onError)||void 0===i||i.call(r,e)}):console.warn("[FilePlayer] Cannot play: video has no valid source")}},t.pause=function(){t.props.videoElement&&t.props.videoElement.pause()},t.stop=function(){t.pause(),t.props.videoElement&&(t.props.videoElement.currentTime=0)},t.seekTo=function(e,r){t.props.videoElement&&(t.props.videoElement.currentTime=e,r||t.pause())},t.setVolume=function(e){t.props.videoElement&&(t.props.videoElement.volume=Math.max(0,Math.min(1,e)))},t.mute=function(){t.props.videoElement&&(t.props.videoElement.muted=!0)},t.unmute=function(){t.props.videoElement&&(t.props.videoElement.muted=!1)},t.setPlaybackRate=function(e){t.props.videoElement&&e>0&&(t.props.videoElement.playbackRate=e)},t.setLoop=function(e){t.props.videoElement&&(t.props.videoElement.loop=e)},t.getDuration=function(){return t.props.videoElement&&isFinite(t.props.videoElement.duration)?t.props.videoElement.duration:null},t.getCurrentTime=function(){return t.props.videoElement&&isFinite(t.props.videoElement.currentTime)?t.props.videoElement.currentTime:null},t.getSecondsLoaded=function(){return t.props.videoElement&&t.props.videoElement.buffered.length>0?t.props.videoElement.buffered.end(t.props.videoElement.buffered.length-1):null},t.getInternalPlayer=function(e){return void 0===e&&(e="player"),"video"===e?t.props.videoElement:null},t.enablePIP=function(){return x(t,void 0,void 0,function(){var e;return O(this,function(t){switch(t.label){case 0:if(!this.props.videoElement||!("requestPictureInPicture"in this.props.videoElement))return[3,4];t.label=1;case 1:return t.trys.push([1,3,,4]),[4,this.props.videoElement.requestPictureInPicture()];case 2:return t.sent(),[3,4];case 3:return e=t.sent(),console.warn("Picture-in-Picture failed:",e),[3,4];case 4:return[2]}})})},t.disablePIP=function(){return x(t,void 0,void 0,function(){var e;return O(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 D(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=lv.file,t}($.Component),dv=[{key:"hls",name:"HLS Player",canPlay:lv.hls,lazyPlayer:zf(function(){return Promise.resolve({default:uv})})},{key:"file",name:"File Player",canPlay:lv.file,canEnablePIP:function(e){return lv.file(e)&&(document.pictureInPictureEnabled||"function"==typeof document.webkitSupportsPresentationMode)},lazyPlayer:zf(function(){return Promise.resolve({default:cv})})}],hv=function(e){function t(){var t=e.apply(this,B([],N(arguments),!1))||this;return t.mounted=!1,t.isReady=!1,t.isPlaying=!1,t.isLoading=!0,t.loadOnReady=null,t.startOnPlay=!0,t.seekOnPlay=null,t.onDurationCalled=!1,t.handlePlayerMount=function(e){t.player||(t.player=e,t.player.load(t.props.src)),t.progress()},t.getInternalPlayer=function(e){return t.player?t.player.getInternalPlayer(e):null},t.progress=function(){var e,r;if(t.props.src&&t.player&&t.isReady){var i=t.getCurrentTime()||0,n=t.getSecondsLoaded(),a=t.getDuration();if(a){var s={playedSeconds:i,played:i/a,loaded:0,loadedSeconds:0};null!==n&&(s.loadedSeconds=n,s.loaded=n/a),s.playedSeconds===t.prevPlayed&&s.loadedSeconds===t.prevLoaded||null===(r=(e=t.props).onProgress)||void 0===r||r.call(e,s),t.prevPlayed=s.playedSeconds,t.prevLoaded=s.loadedSeconds}}t.progressTimeout=window.setTimeout(t.progress,t.props.progressInterval||1e3)},t.handleReady=function(){if(t.mounted){t.isReady=!0,t.isLoading=!1;var e=t.props,r=e.onReady,i=e.playing,n=e.volume,a=e.muted;r(),a||null===n||t.player.setVolume(n),t.loadOnReady?(t.player.load(t.loadOnReady,!0),t.loadOnReady=null):i&&t.player.play(),t.handleDurationCheck()}},t.handlePlay=function(){t.isPlaying=!0,t.isLoading=!1;var e=t.props,r=e.onStart,i=e.onPlay,n=e.playbackRate;t.startOnPlay&&(t.player.setPlaybackRate&&1!==n&&t.player.setPlaybackRate(n),null==r||r(),t.startOnPlay=!1),null==i||i(),t.seekOnPlay&&(t.seekTo(t.seekOnPlay),t.seekOnPlay=null),t.handleDurationCheck()},t.handlePause=function(e){var r,i;t.isPlaying=!1,t.isLoading||null===(i=(r=t.props).onPause)||void 0===i||i.call(r,e)},t.handleEnded=function(){var e=t.props,r=e.activePlayer,i=e.loop,n=e.onEnded;r.loopOnEnded&&i&&t.seekTo(0),i||(t.isPlaying=!1,null==n||n())},t.handleError=function(){for(var e,r,i=[],n=0;n<arguments.length;n++)i[n]=arguments[n];t.isLoading=!1,null===(r=(e=t.props).onError)||void 0===r||r.call(e,i[0],i[1],i[2],i[3])},t.handleDurationCheck=function(){var e,r;clearTimeout(t.durationCheckTimeout);var i=t.getDuration();i?t.onDurationCalled||(null===(r=(e=t.props).onDuration)||void 0===r||r.call(e,i),t.onDurationCalled=!0):t.durationCheckTimeout=window.setTimeout(t.handleDurationCheck,100)},t.handleLoaded=function(){t.isLoading=!1},t}return D(t,e),t.prototype.componentDidMount=function(){this.mounted=!0},t.prototype.componentWillUnmount=function(){clearTimeout(this.progressTimeout),clearTimeout(this.durationCheckTimeout),this.mounted=!1},t.prototype.componentDidUpdate=function(e){var t=this;if(this.player){var r=this.props,i=r.src,n=r.playing,a=r.volume,s=r.muted,o=r.playbackRate,l=r.loop,u=r.activePlayer;if(e.src!==i){if(this.isLoading&&!u.forceLoad&&!Qf(i))return console.warn("StormcloudPlayer: the attempt to load ".concat(i," is being deferred until the player has loaded")),void(this.loadOnReady=i||null);this.isLoading=!0,this.startOnPlay=!0,this.onDurationCalled=!1,this.player.load(i,this.isReady)}e.playing||!n||this.isPlaying||this.player.play(),e.playing&&!n&&this.isPlaying&&this.player.pause(),e.volume!==a&&null!==a&&this.player.setVolume(a),e.muted!==s&&(s?this.player.mute():(this.player.unmute(),null!==a&&setTimeout(function(){return t.player.setVolume(a)}))),e.playbackRate!==o&&this.player.setPlaybackRate&&this.player.setPlaybackRate(o),e.loop!==l&&this.player.setLoop&&this.player.setLoop(l)}},t.prototype.getDuration=function(){return this.isReady?this.player.getDuration():null},t.prototype.getCurrentTime=function(){return this.isReady?this.player.getCurrentTime():null},t.prototype.getSecondsLoaded=function(){return this.isReady?this.player.getSecondsLoaded():null},t.prototype.seekTo=function(e,t,r){var i=this;if(this.isReady){if(t?"fraction"===t:e>0&&e<1){var n=this.player.getDuration();return n?void this.player.seekTo(n*e,r):void console.warn("StormcloudPlayer: could not seek using fraction – duration not yet available")}this.player.seekTo(e,r)}else 0!==e&&(this.seekOnPlay=e,setTimeout(function(){i.seekOnPlay=null},5e3))},t.prototype.render=function(){var e=this.props.activePlayer;return e?J.createElement(e,_(_({},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=Yf,t}($.Component),fv="undefined"!=typeof window&&window.document,vv="undefined"!=typeof self&&self.window&&self.window.document,gv=fv||vv?$.Suspense:function(){return null},pv=["src","playing","loop","controls","volume","muted","playbackRate","width","height","style","progressInterval","playsInline","autoplay","preload","poster","className","wrapperClassName","wrapperStyle","allowNativeHls","lowLatencyMode","isLiveStream","driftToleranceMs","immediateManifestAds","debugAdTiming","showCustomControls","licenseKey","isVmap","vmapUrl","adFailsafeTimeoutMs","minSegmentsBeforePlay","ctvAdRequest","onReady","onStart","onPlay","onPause","onBuffer","onBufferEnd","onEnded","onError","onDuration","onSeek","onProgress","onVolumeToggle","onFullscreenToggle","onControlClick"],mv=[],yv=function(e,t){var r;return r=function(r){function i(){var i=r.apply(this,B([],N(arguments),!1))||this;return i.state={showPreview:!1},i.references={wrapper:function(e){i.wrapper=e},player:function(e){i.player=e}},i.getActivePlayer=function(r){var i,n;if(!r)return null;try{for(var a=F(B(B([],N(mv),!1),N(e),!1)),s=a.next();!s.done;s=a.next()){var o=s.value;if(o.canPlay(r))return o}}catch(e){i={error:e}}finally{try{s&&!s.done&&(n=a.return)&&n.call(a)}finally{if(i)throw i.error}}return t||null},i.getAttributes=function(e){return Xf(i.props,pv)},i.handleReady=function(){var e,t;null===(t=(e=i.props).onReady)||void 0===t||t.call(e,i)},i.seekTo=function(e,t,r){if(!i.player)return null;i.player.seekTo(e,t,r)},i.getCurrentTime=function(){return i.player?i.player.getCurrentTime():null},i.getSecondsLoaded=function(){return i.player?i.player.getSecondsLoaded():null},i.getDuration=function(){return i.player?i.player.getDuration():null},i.getInternalPlayer=function(e){return void 0===e&&(e="player"),i.player?i.player.getInternalPlayer(e):null},i.renderActivePlayer=function(e){if(!e)return null;var t=i.getActivePlayer(e);return t?J.createElement(hv,_(_({},i.props),{key:t.key,ref:i.references.player,activePlayer:t.lazyPlayer||t,onReady:i.handleReady})):null},i}return D(i,r),i.prototype.render=function(){var e=this.props,t=e.src,r=e.style,i=e.width,n=e.height,a=e.fallback,s=e.wrapper,o=this.getAttributes(t),l="string"==typeof s?this.references.wrapper:void 0;return J.createElement(s,_({ref:l,style:_(_({},r),{width:i,height:n})},o),J.createElement(gv,{fallback:a},this.renderActivePlayer(t)))},i}($.Component),r.displayName="StormcloudPlayer",r.defaultProps=_(_({},Yf),{fallback:null,wrapper:"div"}),r.addCustomPlayer=function(e){mv.push(e)},r.removeCustomPlayers=function(){mv.length=0},r.canPlay=function(t){var r,i;try{for(var n=F(B(B([],N(mv),!1),N(e),!1)),a=n.next();!a.done;a=n.next()){if(a.value.canPlay(t))return!0}}catch(e){r={error:e}}finally{try{a&&!a.done&&(i=n.return)&&i.call(n)}finally{if(r)throw r.error}}return!1},r.canEnablePIP=function(t){var r,i;try{for(var n=F(B(B([],N(mv),!1),N(e),!1)),a=n.next();!a.done;a=n.next()){var s=a.value;if(s.canEnablePIP&&s.canEnablePIP(t))return!0}}catch(e){r={error:e}}finally{try{a&&!a.done&&(i=n.return)&&i.call(n)}finally{if(r)throw r.error}}return!1},r},kv=yv(dv,dv[dv.length-1]);e.DEFAULT_TRACKING_INGEST_CONFIG=Gd,e.IS_BROWSER=Zf,e.IS_GLOBAL=ev,e.IS_IOS=tv,e.IS_SAFARI=rv,e.SUPPORTS_DASH=function(){if(!Zf)return!1;var e=document.createElement("video");return Boolean(e.canPlayType("application/dash+xml"))},e.SUPPORTS_HLS=function(){if(!Zf)return!1;var e=document.createElement("video");return Boolean(e.canPlayType("application/vnd.apple.mpegurl"))},e.StormcloudPlayer=kv,e.StormcloudVideoPlayer=If,e.StormcloudVideoPlayerComponent=qf,e.applyTrackingIngestConfig=Kd,e.buildAnalyticsContext=Ph,e.canPlay=lv,e.configureTrackingIngest=function(e){Kd(e)},e.createHlsAdPlayer=Md,e.createPalNonceManager=Vd,e.createStormcloudPlayer=yv,e.default=qf,e.detectBrowser=yd,e.getBrowserConfigOverrides=Ed,e.getBrowserID=_h,e.getClientInfo=wh,e.ingestPlayerTracking=Wd,e.initializePolyfills=Vh,e.isMediaStream=Qf,e.isTrackingIngestEnabled=jd,e.lazy=zf,e.logBrowserInfo=Sd,e.merge=$f,e.omit=Xf,e.parseQuery=function(e){var t={},r=e.split("?")[1]||"";if(!r)return t;var i=function(e){e.split("&").forEach(function(e){var r=N(e.split("="),2),i=r[0],n=r[1];if(i)try{t[decodeURIComponent(i)]=n?decodeURIComponent(n.replace(/\+/g," ")):""}catch(e){t[i]=n||""}})};if("undefined"!=typeof URLSearchParams)try{return new URLSearchParams(r).forEach(function(e,r){t[r]=e}),t}catch(e){i(r)}else i(r);return t},e.players=dv,e.randomString=function(){return Math.random().toString(36).substr(2,9)},e.requiresMediaPipelineResetAfterAds=kd,e.sendAdDetectTracking=Fh,e.sendAdImpressionTracking=Bh,e.sendAdLoadedTracking=Nh,e.sendHeartbeat=Uh,e.sendInitialTracking=Oh,e.supportsFeature=function(e){switch(e){case"urlsearchparams":return"undefined"!=typeof URLSearchParams;case"textencoder":return"undefined"!=typeof TextEncoder;case"promises":return"undefined"!=typeof Promise;case"fetch":return"undefined"!=typeof fetch;case"crypto":return"undefined"!=typeof crypto&&void 0!==crypto.subtle;default:return!1}},e.supportsModernJS=function(){try{return"undefined"!=typeof Promise&&"undefined"!=typeof Map&&"undefined"!=typeof Set&&void 0!==Array.from&&void 0!==Object.assign&&void 0!==Array.prototype.forEach&&void 0!==String.prototype.includes}catch(e){return!1}},e.supportsWebKitPresentationMode=function(){return"undefined"!=typeof window&&"webkitSupportsPresentationMode"in document.createElement("video")},e.trackingIngestConfig=Hd,Object.defineProperty(e,"__esModule",{value:!0})});
|
|
3
|
+
var e,t,r="function"==typeof Symbol?Symbol:{},i=r.iterator||"@@iterator",n=r.toStringTag||"@@toStringTag";function a(r,i,n,a){var l=i&&i.prototype instanceof o?i:o,u=Object.create(l.prototype);return k(u,"_invoke",function(r,i,n){var a,o,l,u=0,c=n||[],d=!1,h={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,r){return a=t,o=0,l=e,h.n=r,s}};function f(r,i){for(o=r,l=i,t=0;!d&&u&&!n&&t<c.length;t++){var n,a=c[t],f=h.p,v=a[2];r>3?(n=v===i)&&(l=a[(o=a[4])?5:(o=3,3)],a[4]=a[5]=e):a[0]<=f&&((n=r<2&&f<a[1])?(o=0,h.v=i,h.n=a[1]):f<v&&(n=r<3||a[0]>i||i>v)&&(a[4]=r,a[5]=i,h.n=v,o=0))}if(n||r>1)return s;throw d=!0,i}return function(n,c,v){if(u>1)throw TypeError("Generator is already running");for(d&&1===c&&f(c,v),o=c,l=v;(t=o<2?e:l)||!d;){a||(o?o<3?(o>1&&(h.n=-1),f(o,l)):h.n=l:h.v=l);try{if(u=2,a){if(o||(n="next"),t=a[n]){if(!(t=t.call(a,l)))throw TypeError("iterator result is not an object");if(!t.done)return t;l=t.value,o<2&&(o=0)}else 1===o&&(t=a.return)&&t.call(a),o<2&&(l=TypeError("The iterator does not provide a '"+n+"' method"),o=1);a=e}else if((t=(d=h.n<0)?l:r.call(i,h))!==s)break}catch(t){a=e,o=1,l=t}finally{u=1}}return{value:t,done:d}}}(r,n,a),!0),u}var s={};function o(){}function l(){}function u(){}t=Object.getPrototypeOf;var c=[][i]?t(t([][i]())):(k(t={},i,function(){return this}),t),d=u.prototype=o.prototype=Object.create(c);function h(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,k(e,n,"GeneratorFunction")),e.prototype=Object.create(d),e}return l.prototype=u,k(d,"constructor",u),k(u,"constructor",l),l.displayName="GeneratorFunction",k(u,n,"GeneratorFunction"),k(d),k(d,n,"Generator"),k(d,i,function(){return this}),k(d,"toString",function(){return"[object Generator]"}),(y=function(){return{w:a,m:h}})()}function k(e,t,r,i){var n=Object.defineProperty;try{n({},"",{})}catch(e){n=0}k=function(e,t,r,i){function a(t,r){k(e,t,function(e){return this._invoke(t,r,e)})}t?n?n(e,t,{value:r,enumerable:!i,configurable:!i,writable:!i}):e[t]=r:(a("next",0),a("throw",1),a("return",2))},k(e,t,r,i)}function E(e,t){return E=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},E(e,t)}function S(e,t){return i(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var i,n,a,s,o=[],l=!0,u=!1;try{if(a=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;l=!1}else for(;!(l=(i=a.call(r)).done)&&(o.push(i.value),o.length!==t);l=!0);}catch(e){u=!0,n=e}finally{try{if(!l&&null!=r.return&&(s=r.return(),Object(s)!==s))return}finally{if(u)throw n}}return o}}(e,t)||L(e,t)||p()}function T(e,t){for(;!{}.hasOwnProperty.call(e,t)&&null!==(e=h(e)););return e}function A(e,t,r,i){var n=d(h(1&i?e.prototype:e),t,r);return 2&i&&"function"==typeof n?function(e){return n.apply(r,e)}:n}function b(e){return function(e){if(Array.isArray(e))return r(e)}(e)||g(e)||L(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 I(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var i=r.call(e,t||"default");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}function R(e){return R="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},R(e)}function L(e,t){if(e){if("string"==typeof e)return r(e,t);var i={}.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?r(e,t):void 0}}function P(e){var r,i;function n(r,i){try{var s=e[r](i),o=s.value,l=o instanceof t;Promise.resolve(l?o.v:o).then(function(t){if(l){var i="return"===r&&o.k?r:"next";if(!o.k||t.done)return n(i,t);t=e[i](t).value}a(!!s.done,t)},function(e){n("throw",e)})}catch(e){a(2,e)}}function a(e,t){2===e?r.reject(t):r.resolve({value:t,done:e}),(r=r.next)?n(r.key,r.arg):i=null}this._invoke=function(e,t){return new Promise(function(a,s){var o={key:e,arg:t,resolve:a,reject:s,next:null};i?i=i.next=o:(r=i=o,n(e,t))})},"function"!=typeof e.return&&(this.return=void 0)}function w(e){var t="function"==typeof Map?new Map:void 0;return w=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return function(e,t,r){if(v())return Reflect.construct.apply(null,arguments);var i=[null];i.push.apply(i,t);var n=new(e.bind.apply(e,i));return r&&E(n,r.prototype),n}(e,arguments,h(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),E(r,e)},w(e)}P.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},P.prototype.next=function(e){return this._invoke("next",e)},P.prototype.throw=function(e){return this._invoke("throw",e)},P.prototype.return=function(e){return this._invoke("return",e)};var C=function(e,t){return C=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},C(e,t)};function D(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}C(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var _=function(){return _=Object.assign||function(e){for(var t,r=1,i=arguments.length;r<i;r++)for(var n in t=arguments[r])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e},_.apply(this,arguments)};function M(e,t){var r={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(r[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(e);n<i.length;n++)t.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(e,i[n])&&(r[i[n]]=e[i[n]])}return r}function x(e,t,r,i){return new(r||(r=Promise))(function(n,a){function s(e){try{l(i.next(e))}catch(e){a(e)}}function o(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,o)}l((i=i.apply(e,t||[])).next())})}function O(e,t){var r,i,n,a={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]},s=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return s.next=o(0),s.throw=o(1),s.return=o(2),"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(o){return function(l){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,o[0]&&(a=0)),a;)try{if(r=1,i&&(n=2&o[0]?i.return:o[0]?i.throw||((n=i.return)&&n.call(i),0):i.next)&&!(n=n.call(i,o[1])).done)return n;switch(i=0,n&&(o=[2&o[0],n.value]),o[0]){case 0:case 1:n=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,i=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!(n=a.trys,(n=n.length>0&&n[n.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!n||o[1]>n[0]&&o[1]<n[3])){a.label=o[1];break}if(6===o[0]&&a.label<n[1]){a.label=n[1],n=o;break}if(n&&a.label<n[2]){a.label=n[2],a.ops.push(o);break}n[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],i=0}finally{r=n=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}}Object.create;function F(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],i=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function N(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var i,n,a=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(i=a.next()).done;)s.push(i.value)}catch(e){n={error:e}}finally{try{i&&!i.done&&(r=a.return)&&r.call(a)}finally{if(n)throw n.error}}return s}function B(e,t,r){if(r||2===arguments.length)for(var i,n=0,a=t.length;n<a;n++)!i&&n in t||(i||(i=Array.prototype.slice.call(t,0,n)),i[n]=t[n]);return e.concat(i||Array.prototype.slice.call(t))}Object.create;"function"==typeof SuppressedError&&SuppressedError;"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function U(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var V,G={exports:{}},H={};var K,j={exports:{}},q={};function W(){if(K)return q;K=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),n=Symbol.for("react.profiler"),a=Symbol.for("react.consumer"),s=Symbol.for("react.context"),o=Symbol.for("react.forward_ref"),l=Symbol.for("react.suspense"),u=Symbol.for("react.memo"),c=Symbol.for("react.lazy"),d=Symbol.for("react.activity"),h=Symbol.for("react.view_transition"),f=Symbol.iterator;var v={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},g=Object.assign,p={};function m(e,t,r){this.props=e,this.context=t,this.refs=p,this.updater=r||v}function y(){}function k(e,t,r){this.props=e,this.context=t,this.refs=p,this.updater=r||v}m.prototype.isReactComponent={},m.prototype.setState=function(e,t){if("object"!==R(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")},y.prototype=m.prototype;var E=k.prototype=new y;E.constructor=k,g(E,m.prototype),E.isPureReactComponent=!0;var S=Array.isArray;function T(){}var A={H:null,A:null,T:null,S:null},b=Object.prototype.hasOwnProperty;function I(t,r,i){var n=i.ref;return{$$typeof:e,type:t,key:r,ref:void 0!==n?n:null,props:i}}function L(t){return"object"===R(t)&&null!==t&&t.$$typeof===e}var P=/\/+/g;function w(e,t){return"object"===R(e)&&null!==e&&null!=e.key?(r=""+e.key,i={"=":"=0",":":"=2"},"$"+r.replace(/[=:]/g,function(e){return i[e]})):t.toString(36);var r,i}function C(r,i,n,a,s){var o=R(r);"undefined"!==o&&"boolean"!==o||(r=null);var l,u,d=!1;if(null===r)d=!0;else switch(o){case"bigint":case"string":case"number":d=!0;break;case"object":switch(r.$$typeof){case e:case t:d=!0;break;case c:return C((d=r._init)(r._payload),i,n,a,s)}}if(d)return s=s(r),d=""===a?"."+w(r,0):a,S(s)?(n="",null!=d&&(n=d.replace(P,"$&/")+"/"),C(s,i,n,"",function(e){return e})):null!=s&&(L(s)&&(l=s,u=n+(null==s.key||r&&r.key===s.key?"":(""+s.key).replace(P,"$&/")+"/")+d,s=I(l.type,u,l.props)),i.push(s)),1;d=0;var h,v=""===a?".":a+":";if(S(r))for(var g=0;g<r.length;g++)d+=C(a=r[g],i,n,o=v+w(a,g),s);else if("function"==typeof(g=null===(h=r)||"object"!==R(h)?null:"function"==typeof(h=f&&h[f]||h["@@iterator"])?h:null))for(r=g.call(r),g=0;!(a=r.next()).done;)d+=C(a=a.value,i,n,o=v+w(a,g++),s);else if("object"===o){if("function"==typeof r.then)return C(function(e){switch(e.status){case"fulfilled":return e.value;case"rejected":throw e.reason;default:switch("string"==typeof e.status?e.then(T,T):(e.status="pending",e.then(function(t){"pending"===e.status&&(e.status="fulfilled",e.value=t)},function(t){"pending"===e.status&&(e.status="rejected",e.reason=t)})),e.status){case"fulfilled":return e.value;case"rejected":throw e.reason}}throw e}(r),i,n,a,s);throw i=String(r),Error("Objects are not valid as a React child (found: "+("[object Object]"===i?"object with keys {"+Object.keys(r).join(", ")+"}":i)+"). If you meant to render a collection of children, use an array instead.")}return d}function D(e,t,r){if(null==e)return e;var i=[],n=0;return C(e,i,"","",function(e){return t.call(r,e,n++)}),i}function _(e){if(-1===e._status){var t=(0,e._result)();t.then(function(r){0!==e._status&&-1!==e._status||(e._status=1,e._result=r,void 0===t.status&&(t.status="fulfilled",t.value=r))},function(r){0!==e._status&&-1!==e._status||(e._status=2,e._result=r,void 0===t.status&&(t.status="rejected",t.reason=r))}),-1===e._status&&(e._status=0,e._result=t)}if(1===e._status)return e._result.default;throw e._result}var M="function"==typeof reportError?reportError:function(e){if("object"===("undefined"==typeof window?"undefined":R(window))&&"function"==typeof window.ErrorEvent){var t=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:"object"===R(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":R(process))&&"function"==typeof process.emit)return void process.emit("uncaughtException",e);console.error(e)};function x(e){var t=A.T,r={};r.types=null!==t?t.types:null,A.T=r;try{var i=e(),n=A.S;null!==n&&n(r,i),"object"===R(i)&&null!==i&&"function"==typeof i.then&&i.then(T,M)}catch(e){M(e)}finally{null!==t&&null!==r.types&&(t.types=r.types),A.T=t}}var O={map:D,forEach:function(e,t,r){D(e,function(){t.apply(this,arguments)},r)},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(!L(e))throw Error("React.Children.only expected to receive a single React element child.");return e}};return q.Activity=d,q.Children=O,q.Component=m,q.Fragment=r,q.Profiler=n,q.PureComponent=k,q.StrictMode=i,q.Suspense=l,q.ViewTransition=h,q.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=A,q.__COMPILER_RUNTIME={__proto__:null,c:function(e){return A.H.useMemoCache(e)}},q.addTransitionType=function e(t){var r=A.T;if(null!==r){var i=r.types;null===i?r.types=[t]:-1===i.indexOf(t)&&i.push(t)}else x(e.bind(null,t))},q.cache=function(e){return function(){return e.apply(null,arguments)}},q.cacheSignal=function(){return null},q.cloneElement=function(e,t,r){if(null==e)throw Error("The argument must be a React element, but you passed "+e+".");var i=g({},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||(i[a]=t[a]);var a=arguments.length-2;if(1===a)i.children=r;else if(1<a){for(var s=Array(a),o=0;o<a;o++)s[o]=arguments[o+2];i.children=s}return I(e.type,n,i)},q.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},q.createElement=function(e,t,r){var i,n={},a=null;if(null!=t)for(i in void 0!==t.key&&(a=""+t.key),t)b.call(t,i)&&"key"!==i&&"__self"!==i&&"__source"!==i&&(n[i]=t[i]);var s=arguments.length-2;if(1===s)n.children=r;else if(1<s){for(var o=Array(s),l=0;l<s;l++)o[l]=arguments[l+2];n.children=o}if(e&&e.defaultProps)for(i in s=e.defaultProps)void 0===n[i]&&(n[i]=s[i]);return I(e,a,n)},q.createRef=function(){return{current:null}},q.forwardRef=function(e){return{$$typeof:o,render:e}},q.isValidElement=L,q.lazy=function(e){return{$$typeof:c,_payload:{_status:-1,_result:e},_init:_}},q.memo=function(e,t){return{$$typeof:u,type:e,compare:void 0===t?null:t}},q.startTransition=x,q.unstable_useCacheRefresh=function(){return A.H.useCacheRefresh()},q.use=function(e){return A.H.use(e)},q.useActionState=function(e,t,r){return A.H.useActionState(e,t,r)},q.useCallback=function(e,t){return A.H.useCallback(e,t)},q.useContext=function(e){return A.H.useContext(e)},q.useDebugValue=function(){},q.useDeferredValue=function(e,t){return A.H.useDeferredValue(e,t)},q.useEffect=function(e,t){return A.H.useEffect(e,t)},q.useEffectEvent=function(e){return A.H.useEffectEvent(e)},q.useId=function(){return A.H.useId()},q.useImperativeHandle=function(e,t,r){return A.H.useImperativeHandle(e,t,r)},q.useInsertionEffect=function(e,t){return A.H.useInsertionEffect(e,t)},q.useLayoutEffect=function(e,t){return A.H.useLayoutEffect(e,t)},q.useMemo=function(e,t){return A.H.useMemo(e,t)},q.useOptimistic=function(e,t){return A.H.useOptimistic(e,t)},q.useReducer=function(e,t,r){return A.H.useReducer(e,t,r)},q.useRef=function(e){return A.H.useRef(e)},q.useState=function(e){return A.H.useState(e)},q.useSyncExternalStore=function(e,t,r){return A.H.useSyncExternalStore(e,t,r)},q.useTransition=function(){return A.H.useTransition()},q.version="19.3.0",q}var Y;j.exports;function z(){return Y||(Y=1,j.exports=W()),j.exports}var X;G.exports;var Q=(X||(X=1,G.exports=function(){if(V)return H;V=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function r(t,r,i){var n=null;if(void 0!==i&&(n=""+i),void 0!==r.key&&(n=""+r.key),"key"in r)for(var a in i={},r)"key"!==a&&(i[a]=r[a]);else i=r;return r=i.ref,{$$typeof:e,type:t,key:n,ref:void 0!==r?r:null,props:i}}return H.Fragment=t,H.jsx=r,H.jsxs=r,H}()),G.exports),$=z(),J=U($),Z=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},ee=Number.isSafeInteger||function(e){return"number"==typeof e&&Math.abs(e)<=te},te=Number.MAX_SAFE_INTEGER||9007199254740991,re=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}({}),ie=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.PLAYLIST_UNCHANGED_ERROR="playlistUnchangedError",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_APPEND_NO_PROGRESS="bufferAppendNoProgress",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.MEDIA_SOURCE_REQUIRES_RESET="mediaSourceRequiresReset",e.UNKNOWN="unknown",e}({}),ne=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}({});function ae(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var se,oe={exports:{}};var le=(se||(se=1,function(e){var t,r,i,n,a;t=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,i=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(e,t,i){if(i=i||{},e=e.trim(),!(t=t.trim())){if(!i.alwaysNormalize)return e;var n=a.parseURL(e);if(!n)throw new Error("Error trying to parse base URL.");return n.path=a.normalizePath(n.path),a.buildURLFromParts(n)}var s=a.parseURL(t);if(!s)throw new Error("Error trying to parse relative URL.");if(s.scheme)return i.alwaysNormalize?(s.path=a.normalizePath(s.path),a.buildURLFromParts(s)):t;var o=a.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=r.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var u={scheme:o.scheme,netLoc:s.netLoc,path:null,params:s.params,query:s.query,fragment:s.fragment};if(!s.netLoc&&(u.netLoc=o.netLoc,"/"!==s.path[0]))if(s.path){var c=o.path,d=c.substring(0,c.lastIndexOf("/")+1)+s.path;u.path=a.normalizePath(d)}else u.path=o.path,s.params||(u.params=o.params,s.query||(u.query=o.query));return null===u.path&&(u.path=i.alwaysNormalize?a.normalizePath(s.path):s.path),a.buildURLFromParts(u)},parseURL:function(e){var r=t.exec(e);return r?{scheme:r[1]||"",netLoc:r[2]||"",path:r[3]||"",params:r[4]||"",query:r[5]||"",fragment:r[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(i,"");e.length!==(e=e.replace(n,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}},e.exports=a}(oe)),oe.exports),ue=l(function e(){s(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=function(e){return e.MANIFEST="manifest",e.LEVEL="level",e.AUDIO_TRACK="audioTrack",e.SUBTITLE_TRACK="subtitleTrack",e.MEDIA_FRAGMENT="media-fragment",e.KEY="key",e.STEERING_MANIFEST="steering-manifest",e.SERVER_CERTIFICATE="server-certificate",e.INTERSTITIAL_ASSET_LIST="interstitial-asset-list",e}({}),de=function(e){return e.MAIN="main",e.AUDIO="audio",e.SUBTITLE="subtitle",e}({}),he="audio",fe="video",ve="audiovideo",ge=function(){return l(function e(t){var r,i,n;s(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=Se(r=this,i="stats"))&&(n.enumerable=!0,Object.defineProperty(r,i,n))},[{key:"setByteRange",value:function(e,t){var r,i=e.split("@",2);r=1===i.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(i[1]),this._byteRange=[r,parseInt(i[0])+r]}},{key:"baseurl",get:function(){return this.base.url}},{key:"byteRange",get:function(){return null===this._byteRange?[]:this._byteRange}},{key:"byteRangeStartOffset",get:function(){return this.byteRange[0]}},{key:"byteRangeEndOffset",get:function(){return this.byteRange[1]}},{key:"elementaryStreams",get:function(){return null===this._streams&&(this._streams=c(c(c({},he,null),fe,null),ve,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 ue),this._stats},set:function(e){this._stats=e}},{key:"url",get:function(){return!this._url&&this.relurl&&(this._url=le.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""},set:function(e){this._url=e}},{key:"clearElementaryStreamInfo",value:function(){var e=this.elementaryStreams;e[he]=null,e[fe]=null,e[ve]=null,this.url=null}}])}();function pe(e){return"initSegment"!==e.sn}function me(e,t){return e.sn===(null==t?void 0:t.sn)&&e.level===t.level}function ye(e,t){return e.sn===(null==t?void 0:t.sn)&&e.level===t.level&&e.cc===t.cc}var ke=function(e){function t(e,r){var i;return s(this,t),(i=a(this,t,[r]))._decryptdata=null,i._programDateTime=null,i._ref=null,i._bitrate=void 0,i.rawProgramDateTime=null,i.tagList=[],i.duration=0,i.sn=0,i.levelkeys=void 0,i.type=void 0,i.loader=null,i.keyLoader=null,i.level=-1,i.cc=0,i.startPTS=void 0,i.endPTS=void 0,i.startDTS=void 0,i.endDTS=void 0,i.start=0,i.playlistOffset=0,i.deltaPTS=void 0,i.maxStartPTS=void 0,i.minEndPTS=void 0,i.data=void 0,i.bitrateTest=!1,i.title=null,i.initSegment=null,i.endList=void 0,i.gap=void 0,i.urlId=0,i.type=e,i}return f(t,e),l(t,[{key:"byteLength",get:function(){if(this.hasStats){var e=this.stats.total;if(e)return e}if(this.byteRange.length){var t=this.byteRange[0],r=this.byteRange[1];if(Z(t)&&Z(r))return r-t}return null}},{key:"bitrate",get:function(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null},set:function(e){this._bitrate=e}},{key:"decryptdata",get:function(){var e,t=this.levelkeys;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(null==(e=this._decryptdata)||!e.keyId){var r=Object.keys(t);if(1===r.length){var i=this._decryptdata=t[r[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,t))}}return this._decryptdata}},{key:"end",get:function(){return this.start+this.duration}},{key:"endProgramDateTime",get:function(){if(null===this.programDateTime)return null;var e=Z(this.duration)?this.duration:0;return this.programDateTime+1e3*e}},{key:"encrypted",get:function(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){var t,r=Object.keys(this.levelkeys),i=r.length;if(i>1||1===i&&null!=(t=this.levelkeys[r[0]])&&t.encrypted)return!0}return!1}},{key:"programDateTime",get:function(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime},set:function(e){Z(e)?this._programDateTime=e:this._programDateTime=this.rawProgramDateTime=null}},{key:"ref",get:function(){return pe(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}},{key:"addStart",value:function(e){this.setStart(this.start+e)}},{key:"setStart",value:function(e){this.start=e,this._ref&&(this._ref.start=e)}},{key:"setDuration",value:function(e){this.duration=e,this._ref&&(this._ref.duration=e)}},{key:"setKeyFormat",value:function(e){var t=this.levelkeys;if(t){var r,i=t[e];!i||null!=(r=this._decryptdata)&&r.keyId||(this._decryptdata=i.getDecryptData(this.sn,t))}}},{key:"abortRequests",value:function(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()}},{key:"setElementaryStreamInfo",value:function(e,t,r,i,n){var a=arguments.length>5&&void 0!==arguments[5]&&arguments[5],s=this.elementaryStreams,o=s[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,r),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,n)):s[e]={startPTS:t,endPTS:r,startDTS:i,endDTS:n,partial:a}}}])}(ge),Ee=function(e){function t(e,r,i,n,o){var l;s(this,t),(l=a(this,t,[i])).fragOffset=0,l.duration=0,l.independent=!1,l.relurl=void 0,l.fragment=void 0,l.index=void 0,l.gap=!1,l.duration=e.decimalFloatingPoint("DURATION"),l.gap=e.bool("GAP"),l.independent=e.bool("INDEPENDENT"),l.relurl=e.enumeratedString("URI"),l.fragment=r,l.index=n;var u=e.enumeratedString("BYTERANGE");return u&&l.setByteRange(u,o),o&&(l.fragOffset=o.fragOffset+o.duration),l}return f(t,e),l(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||this.fragment.type===de.SUBTITLE&&this.stats.loading.end>0)}}])}(ge);function Se(e,t){var r=Object.getPrototypeOf(e);if(r){var i=Object.getOwnPropertyDescriptor(r,t);return i||Se(r,t)}}function Te(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=R(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var i=r.call(e,t);if("object"!=R(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==R(t)?t:t+""}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Ae(){return Ae=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var i in r)({}).hasOwnProperty.call(r,i)&&(e[i]=r[i])}return e},Ae.apply(null,arguments)}function be(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,i)}return r}function Ie(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?be(Object(r),!0).forEach(function(t){Te(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):be(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function Re(e,t){if(null==e)return{};var r,i,n=function(e,t){if(null==e)return{};var r={};for(var i in e)if({}.hasOwnProperty.call(e,i)){if(-1!==t.indexOf(i))continue;r[i]=e[i]}return r}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)r=a[i],-1===t.indexOf(r)&&{}.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function Le(e){switch(e.details){case ie.FRAG_LOAD_TIMEOUT:case ie.KEY_LOAD_TIMEOUT:case ie.LEVEL_LOAD_TIMEOUT:case ie.MANIFEST_LOAD_TIMEOUT:case ie.AUDIO_TRACK_LOAD_TIMEOUT:case ie.SUBTITLE_TRACK_LOAD_TIMEOUT:case ie.ASSET_LIST_LOAD_TIMEOUT:return!0}return!1}function Pe(e){return e.details.startsWith("key")}function we(e){return Pe(e)&&!!e.frag&&!e.frag.decryptdata}function Ce(e,t){var r=Le(t);return e.default["".concat(r?"timeout":"error","Retry")]}function De(e,t){var r="linear"===e.backoff?1:Math.pow(2,t);return Math.min(r*e.retryDelayMs,e.maxRetryDelayMs)}function _e(e){return Ie(Ie({},e),{errorRetry:null,timeoutRetry:null})}function Me(e,t,r,i){if(!e)return!1;var n=null==i?void 0:i.code,a=t<e.maxNumRetry&&(function(e){return xe(e)||!!e&&(e<400||e>499)}(n)||!!r);return e.shouldRetry?e.shouldRetry(e,t,r,i,a):a}function xe(e){return 0===e&&!1===navigator.onLine}function Oe(e,t){return t>0&&e.loadError>0&&0!==e.loadErrorTime&&self.performance.now()-e.loadErrorTime>t}var Fe=function(){return l(function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;s(this,e),this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=r,this.totalWeight_=i},[{key:"sample",value:function(e,t){var r=Math.pow(this.alpha_,e);this.estimate_=t*(1-r)+r*this.estimate_,this.totalWeight_+=e}},{key:"getTotalWeight",value:function(){return this.totalWeight_}},{key:"getEstimate",value:function(){if(this.alpha_){var e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}])}(),Ne=function(){return l(function e(t,r,i){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:100;s(this,e),this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new Fe(t),this.fast_=new Fe(r),this.defaultTTFB_=n,this.ttfb_=new Fe(t)},[{key:"update",value:function(e,t){var r=this.slow_,i=this.fast_,n=this.ttfb_;r.halfLife!==e&&(this.slow_=new Fe(e,r.getEstimate(),r.getTotalWeight())),i.halfLife!==t&&(this.fast_=new Fe(t,i.getEstimate(),i.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new Fe(e,n.getEstimate(),n.getTotalWeight()))}},{key:"sample",value:function(e,t){if(!(t<=0)){var r=Math.min(this.minDelayMs_,t/1e5),i=8*t,n=Math.max(e,r)/1e3,a=i/n;this.fast_.sample(n,a),this.slow_.sample(n,a)}}},{key:"sampleTTFB",value:function(e){var t=e/1e3,r=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(r,Math.max(e,5))}},{key:"canEstimate",value:function(){return this.fast_.getTotalWeight()>=this.minWeight_}},{key:"getEstimate",value:function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}},{key:"getEstimateTTFB",value:function(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}},{key:"defaultEstimate",get:function(){return this.defaultEstimate_}},{key:"destroy",value:function(){}}])}(),Be=l(function e(t,r){s(this,e),this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;var i="[".concat(t,"]:");this.trace=Ue,this.debug=r.debug.bind(null,i),this.log=r.log.bind(null,i),this.warn=r.warn.bind(null,i),this.info=r.info.bind(null,i),this.error=r.error.bind(null,i)}),Ue=function(){},Ve={trace:Ue,debug:Ue,log:Ue,warn:Ue,info:Ue,error:Ue};function Ge(){return Ae({},Ve)}function He(e,t,r){return t[e]?t[e].bind(t):function(e,t){var r=self.console[e];return r?r.bind(self.console,"".concat(t?"["+t+"] ":"","[").concat(e,"] >")):Ue}(e,r)}var Ke=Ge();var je=Ke;function qe(){if("undefined"!=typeof self)return(!(arguments.length>0&&void 0!==arguments[0])||arguments[0]||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function We(e,t){var r=Object.keys(e),i=Object.keys(t),n=r.length,a=i.length;return!n||!a||n===a&&!r.some(function(e){return-1===i.indexOf(e)})}function Ye(e){return e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer}var ze="utf-16be",Xe="utf-16le",Qe="utf-8";function $e(e,t){if(e<0)return-$e(-e,t);var r=Math.pow(10,t);if(Math.abs(e*r%1-.5)<Number.EPSILON){var i=Math.floor(e*r);return(i%2==0?i:i+1)/r}return Math.round(e*r)/r}function Je(){try{return crypto.randomUUID()}catch(i){try{var e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(e){var r=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=(r+16*Math.random())%16|0;return r=Math.floor(r/16),("x"==e?t:3&t|8).toString(16)})}}}function Ze(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 et(e,t){var r=0;return r=(127&e[t])<<21,r|=(127&e[t+1])<<14,r|=(127&e[t+2])<<7,r|=127&e[t+3]}function tt(e,t){return Ze(e,t)&&et(e,t+6)+10<=e.length-t}function rt(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 it(e,t){for(var r=t,i=0;Ze(e,t);){i+=10,i+=et(e,t+6),rt(e,t+10)&&(i+=10),t+=i}if(i>0)return e.subarray(r,r+i)}function nt(e){return function(e,t,r,i){var n=(s=e,Ye(s)?s:s.buffer),a=1;var s;"BYTES_PER_ELEMENT"in i&&(a=i.BYTES_PER_ELEMENT);var o=(d=e,d&&Ye(d.buffer)&&void 0!==d.byteLength&&void 0!==d.byteOffset?e.byteOffset:0),l=(o+e.byteLength)/a,u=(o+t)/a,c=Math.floor(Math.max(0,Math.min(u,l)));var d;return new i(n,c,Math.floor(Math.min(c+Math.max(r,0),l))-c)}(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,arguments.length>2&&void 0!==arguments[2]?arguments[2]:1/0,Uint8Array)}function at(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=t?e.indexOf(0):e.length,i=function(e){var t,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};t=Ye(e)?new DataView(e):new DataView(e.buffer,e.byteOffset,e.byteLength);var i=0,n=r.encoding;if(!n){var a=t.getUint8(0),s=t.getUint8(1);239==a&&187==s&&191==t.getUint8(2)?(n=Qe,i=3):254==a&&255==s?(n=ze,i=2):255==a&&254==s?(n=Xe,i=2):n=Qe}if("undefined"!=typeof TextDecoder)return new TextDecoder(n).decode(t);for(var o,l=t.byteLength,u=n!==ze,c="";i<l;){switch(n){case Qe:if((o=t.getUint8(i))<128)i++;else if(o>=194&&o<=223)if(i+1<l){var d=t.getUint8(i+1);d>=128&&d<=191?(o=(31&o)<<6|63&d,i+=2):i++}else i++;else if(o>=224&&o<=239)if(i+2<=l-1){var h=t.getUint8(i+1),f=t.getUint8(i+2);h>=128&&h<=191&&f>=128&&f<=191?(o=(15&o)<<12|(63&h)<<6|63&f,i+=3):i++}else i++;else if(o>=240&&o<=244)if(i+3<=l-1){var v=t.getUint8(i+1),g=t.getUint8(i+2),p=t.getUint8(i+3);v>=128&&v<=191&&g>=128&&g<=191&&p>=128&&p<=191?(o=(7&o)<<18|(63&v)<<12|(63&g)<<6|63&p,i+=4):i++}else i++;else i++;break;case ze:case"utf-16":case Xe:o=t.getUint16(i,u),i+=2}c+=String.fromCodePoint(o)}return c}(new DataView(e.buffer,e.byteOffset,r),{encoding:Qe});return t?i:i.replace(/\0/g,"")}function st(e){var t={key:e.type,description:"",data:"",mimeType:null,pictureType:null};if(!(e.size<2))if(3===e.data[0]){var r=e.data.subarray(1).indexOf(0);if(-1!==r){var i=at(nt(e.data,1,r)),n=e.data[2+r],a=e.data.subarray(3+r).indexOf(0);if(-1!==a){var s,o,l=at(nt(e.data,3+r,a));return"--\x3e"===i?s=at(nt(e.data,4+r+a)):s=Ye(o=e.data.subarray(4+r+a))?o:0==o.byteOffset&&o.byteLength==o.buffer.byteLength?o.buffer:new Uint8Array(o).buffer,t.mimeType=i,t.pictureType=n,t.description=l,t.data=s,t}}}else console.log("Ignore frame with unrecognized character encoding")}function ot(e){return"PRIV"===e.type?function(e){if(!(e.size<2)){var t=at(e.data,!0),r=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:r.buffer}}}(e):"W"===e.type[0]?function(e){if("WXXX"===e.type){if(e.size<2)return;var t=1,r=at(e.data.subarray(t),!0);t+=r.length+1;var i=at(e.data.subarray(t));return{key:e.type,info:r,data:i}}var n=at(e.data);return{key:e.type,info:"",data:n}}(e):"APIC"===e.type?st(e):function(e){if(!(e.size<2)){if("TXXX"===e.type){var t=1,r=e.data,i=at(r.subarray(t),!0);t+=i.length+1;var n=at(r.subarray(t));return{key:e.type,info:i,data:n}}var a=at(e.data.subarray(1));return{key:e.type,info:"",data:a}}}(e)}function lt(e){var t=String.fromCharCode(e[0],e[1],e[2],e[3]),r=et(e,4);return{type:t,size:r,data:e.subarray(10,10+r)}}function ut(e){for(var t=0,r=[];Ze(e,t);){var i=et(e,t+6);e[t+5]>>6&1&&(t+=10);for(var n=(t+=10)+i;t+10<n;){var a=lt(e.subarray(t)),s=ot(a);s&&r.push(s),t+=a.size+10}rt(e,t)&&(t+=10)}return r}function ct(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info}function dt(e){if(8===e.data.byteLength){var t=new Uint8Array(e.data),r=1&t[3],i=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return i/=45,r&&(i+=47721858.84),Math.round(i)}}function ht(e){var t,r=u(ut(e));try{for(r.s();!(t=r.n()).done;){var i=t.value;if(ct(i))return dt(i)}}catch(e){r.e(e)}finally{r.f()}}function ft(e){for(var t="",r=0;r<e.length;r++){var i=e[r].toString(16);i.length<2&&(i="0"+i),t+=i}return t}function vt(e){return Uint8Array.from(e.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function gt(e){return Uint8Array.from(atob(e),function(e){return e.charCodeAt(0)})}function pt(e){return String.fromCharCode.apply(null,e)}var mt,yt=Math.pow(2,32)-1,kt={avc1:1635148593,avcC:1635148611,hvc1:1752589105,hvcC:1752589123,btrt:1651798644,dinf:1684631142,dref:1685218662,esds:1702061171,free:1718773093,ftyp:1718909296,hdlr:1751411826,mdat:1835295092,mdhd:1835296868,mdia:1835297121,mfhd:1835427940,minf:1835626086,moof:1836019558,moov:1836019574,mp4a:1836069985,".mp3":778924083,dac3:1684103987,"ac-3":1633889587,mvex:1836475768,mvhd:1836476516,pasp:1885434736,sdtp:1935963248,stbl:1937007212,stco:1937007471,stsc:1937011555,stsd:1937011556,stsz:1937011578,stts:1937011827,tfdt:1952867444,tfhd:1952868452,traf:1953653094,trak:1953653099,trun:1953658222,trex:1953654136,tkhd:1953196132,vmhd:1986881636,smhd:1936549988},Et={video:1,audio:2,id3:3,text:4};function St(e,t){var r=e[t]<<8|e[t+1];return r<0?65536+r:r}function Tt(e,t){var r=e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3];return r<0?4294967296+r:r}function At(e,t){var r=Tt(e,t);return r*=Math.pow(2,32),r+=Tt(e,t+4)}function bt(e,t){for(var r="",i=t;i<e.length;i++)if(r+=String.fromCharCode(e[i]),0===e[i])return r;return null}function It(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function Rt(e,t,r){e[t]=r>>24,e[t+1]=r>>16&255,e[t+2]=r>>8&255,e[t+3]=255&r}function Lt(e,t,r){var i=t.byteOffset-e.byteOffset-8,n=8+r,a=t.byteLength+8-n;a<8||(Rt(e,i,n),Rt(e,i+n,a),Rt(e,i+n+4,kt.free))}function Pt(e,t){return[e.byteOffset-t-8,e.byteOffset-t+e.byteLength]}function wt(e,t){t.sort(function(e,t){return e[0]-t[0]});for(var r=t.reduce(function(e,t){var r=S(t,2),i=r[0];return e+r[1]-i},0),i=new Uint8Array(e.byteLength-r),n=0,a=0,s=0;s<t.length;s++){var o=S(t[s],2),l=o[0],u=o[1];i.set(e.subarray(n,l),a),a+=l-n,n=u}i.set(e.subarray(n),a);return{result:i,dropped:r,droppedBefore:function(e){return t.reduce(function(t,r){var i=S(r,2),n=i[0],a=i[1];return a<=e?t+a-n:t},0)}}}function Ct(e,t){var r=[];return t.length?(Dt(e,t,0,0,e.byteLength,r),r):r}function Dt(e,t,r,i,n,a){var s=t[r];if(4===(null==s?void 0:s.length))for(var o=s.charCodeAt(0),l=s.charCodeAt(1),u=s.charCodeAt(2),c=s.charCodeAt(3),d=t.length-1,h=i;h<n;){var f=h+8<=n,v=h+4<=n?16777216*e[h]+(e[h+1]<<16|e[h+2]<<8|e[h+3]):Tt(e,h),g=v>1?h+v:n;if(f&&e[h+4]===o&&e[h+5]===l&&e[h+6]===u&&e[h+7]===c){var p=Math.min(g,n);r===d?a.push(e.subarray(h+8,p)):Dt(e,t,r+1,h+8,p,a)}h=g}}function _t(e){var t=[],r=e[0],i=8,n=Tt(e,i);i+=4;var a=0,s=0;0===r?(a=Tt(e,i),s=Tt(e,i+4),i+=8):(a=At(e,i),s=At(e,i+8),i+=16),i+=2;var o=e.length+s,l=St(e,i);i+=2;for(var u=0;u<l;u++){var c=i,d=Tt(e,c);c+=4;var h=2147483647&d;if(1===(2147483648&d)>>>31)return je.warn("SIDX has hierarchical references (not supported)"),null;var f=Tt(e,c);c+=4,t.push({referenceSize:h,subsegmentDuration:f,info:{duration:f/n,start:o,end:o+h-1}}),o+=h,i=c+=4}return{earliestPresentationTime:a,timescale:n,version:r,referencesCount:l,references:t}}function Mt(e){for(var t=[],r=Ct(e,["moov","trak"]),i=0;i<r.length;i++){var n=r[i],a=Ct(n,["tkhd"])[0];if(a){var s=a[0],o=Tt(a,0===s?12:20),l=Ct(n,["mdia","mdhd"])[0];if(l){var u=Tt(l,0===(s=l[0])?12:20),c=Ct(n,["mdia","hdlr"])[0];if(c){var d=pt(c.subarray(8,12)),h={soun:he,vide:fe}[d],f=xt(Ct(n,["mdia","minf","stbl","stsd"])[0]);h?(t[o]={timescale:u,type:h,stsd:f},t[h]=Ie({timescale:u,id:o},f)):t[o]={timescale:u,type:d,stsd:f}}}}}return Ct(e,["moov","mvex","trex"]).forEach(function(e){var r=Tt(e,4),i=t[r];i&&(i.default={duration:Tt(e,12),sampleSize:Tt(e,16),flags:Tt(e,20)})}),t}function xt(e){var t,r=e.subarray(8),i=r.subarray(86),n=pt(r.subarray(4,8)),a=n,s="enca"===n||"encv"===n;if(s){var o=Ct(r,[n])[0];Ct(o.subarray("enca"===n?28:78),["sinf"]).forEach(function(e){var t=Ct(e,["schm"])[0];if(t){var r=pt(t.subarray(4,8));if("cbcs"===r||"cenc"===r){var i=Ct(e,["frma"])[0];i&&(a=pt(i))}}})}var l=a;switch(a){case"avc1":case"avc2":case"avc3":case"avc4":var u=Ct(i,["avcC"])[0];u&&u.length>3&&(a+="."+Nt(u[1])+Nt(u[2])+Nt(u[3]),t=Ot("avc1"===l?"dva1":"dvav",i));break;case"mp4a":var c=Ct(r,[n])[0],d=Ct(c.subarray(28),["esds"])[0];if(d&&d.length>7){var h=4;if(3!==d[h++])break;h=Ft(d,h),h+=2;var f=d[h++];if(128&f&&(h+=2),64&f&&(h+=d[h++]),4!==d[h++])break;h=Ft(d,h);var v=d[h++];if(64!==v)break;if(a+="."+Nt(v),h+=12,5!==d[h++])break;h=Ft(d,h);var g=d[h++],p=(248&g)>>3;31===p&&(p+=1+((7&g)<<3)+((224&d[h])>>5)),a+="."+p}break;case"hvc1":case"hev1":var m=Ct(i,["hvcC"])[0];if(m&&m.length>12){var y=m[1],k=["","A","B","C"][y>>6],E=31&y,S=Tt(m,2),T=(32&y)>>5?"H":"L",A=m[12],b=m.subarray(6,12);a+="."+k+E,a+="."+function(e){for(var t=0,r=0;r<32;r++)t|=(e>>r&1)<<31-r;return t>>>0}(S).toString(16).toUpperCase(),a+="."+T+A;for(var I="",R=b.length;R--;){var L=b[R];if(L||I)I="."+L.toString(16).toUpperCase()+I}a+=I}t=Ot("hev1"==l?"dvhe":"dvh1",i);break;case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":a=Ot(a,i)||a;break;case"vp09":var P=Ct(i,["vpcC"])[0];if(P&&P.length>6){var w=P[4],C=P[5],D=P[6]>>4&15;a+="."+Bt(w)+"."+Bt(C)+"."+Bt(D)}break;case"av01":var _=Ct(i,["av1C"])[0];if(_&&_.length>2){var M=_[1]>>>5,x=31&_[1],O=_[2]>>>7?"H":"M",F=(64&_[2])>>6,N=(32&_[2])>>5,B=2===M&&F?N?12:10:F?10:8,U=(16&_[2])>>4,V=(8&_[2])>>3,G=(4&_[2])>>2,H=3&_[2];a+="."+M+"."+Bt(x)+O+"."+Bt(B)+"."+U+"."+V+G+H+"."+Bt(1)+"."+Bt(1)+"."+Bt(1)+".0",t=Ot("dav1",i)}}return{codec:a,encrypted:s,supplemental:t}}function Ot(e,t){var r=Ct(t,["dvvC"]),i=r.length?r[0]:Ct(t,["dvcC"])[0];if(i){var n=i[2]>>1&127,a=i[2]<<5&32|i[3]>>3&31;return e+"."+Bt(n)+"."+Bt(a)}}function Ft(e,t){for(var r=t+5;128&e[t++]&&t<r;);return t}function Nt(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function Bt(e){return(e<10?"0":"")+e}function Ut(e,t){Ct(e,["moov","trak"]).forEach(function(e){var r=Ct(e,["mdia","minf","stbl","stsd"])[0];if(r){var i=r.subarray(8),n=Ct(i,["enca"]),a=n.length>0;a||(n=Ct(i,["encv"])),n.forEach(function(e){Ct(a?e.subarray(28):e.subarray(78),["sinf"]).forEach(function(e){var r=Vt(e);r&&t(r,a)})})}})}function Vt(e){var t=Ct(e,["schm"])[0];if(t){var r=pt(t.subarray(4,8));if("cbcs"===r||"cenc"===r){var i=Ct(e,["schi","tenc"])[0];if(i)return i}}}function Gt(e){return"undefined"==typeof TextDecoder?at(e):(mt||(mt=new TextDecoder("utf-8"))).decode(e).replace(/\0/g,"")}function Ht(e,t,r,i,n){for(var a={},s=!1,o=function(e){for(var t=e.byteLength,r=[],i=0;i<t;){var n=i+8<=t,a=i+4<=t?16777216*e[i]+(e[i+1]<<16|e[i+2]<<8|e[i+3]):Tt(e,i),s=a>1?i+a:t;if(n&&109===e[i+4]&&111===e[i+5]&&111===e[i+6]&&102===e[i+7])for(var o=Math.min(s,t),l=i+8;l<o;){var u=l+8<=o,c=l+4<=o?16777216*e[l]+(e[l+1]<<16|e[l+2]<<8|e[l+3]):Tt(e,l),d=c>1?l+c:o;if(u&&116===e[l+4]&&114===e[l+5]&&97===e[l+6]&&102===e[l+7]){for(var h=Math.min(d,o),f=void 0,v=void 0,g=[],p=l+8;p<h;){var m=p+8<=h,y=p+4<=h?16777216*e[p]+(e[p+1]<<16|e[p+2]<<8|e[p+3]):Tt(e,p),k=y>1?p+y:h;if(m&&116===e[p+4]){var E=Math.min(k,h);102===e[p+5]&&104===e[p+6]&&100===e[p+7]?v||(v=e.subarray(p+8,E)):102===e[p+5]&&100===e[p+6]&&116===e[p+7]?f||(f=e.subarray(p+8,E)):114===e[p+5]&&117===e[p+6]&&110===e[p+7]&&g.push(e.subarray(p+8,E))}p=k}r.push({moofOffset:e.byteOffset+i,tfdt:f,tfhd:v,truns:g})}l=d}i=s}return r}(e),l=e.byteLength,u=0;u<o.length;u++){var c=o[u],d=c.moofOffset,h=c.tfdt,f=c.tfhd,v=c.truns,g=Tt(f,4),p=t[g];if(p){var m=a[g]||(a[g]={start:NaN,duration:0,sampleCount:0,trun:[],timescale:p.timescale,type:p.type}),y=void 0;if(h){var k=h[0];y=Tt(h,4),1===k&&(y===yt?r.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(y*=yt+1,y+=Tt(h,8))),Z(y)&&(!Z(m.start)||y<m.start)&&(m.start=y),n&&Z(y)&&(n.timeOffset=y/n.timescale)}var E=(null==n?void 0:n.trackId)===g&&p.type===fe,S=p.default,T=16777215&Tt(f,0),A=(null==S?void 0:S.duration)||0,b=void 0,I=(null==S?void 0:S.sampleSize)||0,R=8;1&T&&(R+=8),2&T&&(R+=4),8&T&&(A=Tt(f,R),b=f.byteOffset-e.byteOffset+R,R+=4),16&T&&(I=Tt(f,R));var L=0,P=!!(1&T),w=!P&&!!(131072&T);P?(L=Tt(f,8),L*=Math.pow(2,32),L+=Tt(f,12)):w&&(L=d);for(var C=y||0,D=0,_=A,M=0;M<v.length;M++){var x=v[M],O=Tt(x,4),F=m.sampleCount;m.sampleCount+=O;var N=1&x[3],B=0,U=4&x[3],V=1&x[2],G=2&x[2],H=4&x[2],K=8&x[2],j=8;if(N&&(B=It(x,j),j+=4),U)1&x[j+1]||void 0!==m.keyFrameIndex||(m.keyFrameIndex=F),j+=4;var q=L+B;if(i||0!==x[1]||6!==x[2]||1!==x[3]){var W=void 0,Y=void 0;i&&(Y={sampleOffset:q,samples:W=[],defaultSampleDurationOffset:b},q<=l&&m.trun.push(Y));for(var z=void 0,X=0;X<O;X++){var Q=void 0;V?(i&&(Q=x.byteOffset-e.byteOffset+j),_=Tt(x,j),j+=4):_=A,G?(z=Tt(x,j),j+=4):z=I;var $=void 0,J=void 0;H&&(J=1&x[j+1]?1:0,i&&($={isNonSync:J,dependsOn:1==(3&x[j])?1:2}),j+=4);var ee=0;if(K)ee=0===x[0]?Tt(x,j):It(x,j),j+=4;if(E){for(var te=q,re=0;re<z;){var ie=Tt(e,te);te+=4,qt(n.isHEVCFlavor,e[te])&&Wt(e.subarray(te,te+ie),n.isHEVCFlavor?2:1,n.timeOffset+ee/n.timescale,n.samples),te+=ie,re+=ie+4}n.timeOffset+=_/n.timescale}if((q+=z)<=l){Y&&void 0!==Q&&(Y.lastSampleDurationOffset=Q),0===J&&void 0===m.keyFrameIndex&&(m.keyFrameIndex=X,m.keyFrameStart=C);var ne=C+ee;(!Z(m.ptsMin)||ne<m.ptsMin)&&(m.ptsMin=ne),(!Z(m.ptsMax)||ne+_>m.ptsMax)&&(m.ptsMax=ne+_),W&&(W[X]={cts:ee,duration:_,flags:$,size:z})}C+=_,D+=_}!D&&A&&(D+=A*O)}else{for(var ae,se,oe=C,le=q,ue=j,ce=-1,de=0,he=0,ve=null!=(ae=null==n?void 0:n.timeOffset)?ae:0,ge=A/(null!=(se=null==n?void 0:n.timescale)?se:1),pe=!0===(null==n?void 0:n.isHEVCFlavor),me=pe?2:1,ye=0;ye<O;ye++){var ke=0===x[j]?x[j+1]<<16|x[j+2]<<8|x[j+3]:Tt(x,j),Ee=-1===ce&&void 0===m.keyFrameIndex&&!(1&x[j+5]);j+=8;var Se=q+ke;if(E){if(ke>0){var Te=q;do{var Ae=0===e[Te]?e[Te+1]<<16|e[Te+2]<<8|e[Te+3]:Tt(e,Te),be=e[Te+=4],Ie=pe?be>>1&63:31&be;(pe?39===Ie||40===Ie:6===Ie)&&Wt(e.subarray(Te,Te+Ae),me,ve,n.samples),Te+=Ae}while(Te<Se)}ve+=ge}q=Se,Ee&&(ce=ye,de=q)}if(q<=l)he=O;else for(var Re=le,Le=ue,Pe=0;Pe<O;Pe++){if((Re+=0===x[Le]?x[Le+1]<<16|x[Le+2]<<8|x[Le+3]:Tt(x,Le))>l)break;he=Pe+1,Le+=8}if(E&&(n.timeOffset=ve),-1!==ce&&de<=l&&void 0===m.keyFrameIndex&&(m.keyFrameIndex=ce,m.keyFrameStart=oe+ce*A),he){(!Z(m.ptsMin)||oe<m.ptsMin)&&(m.ptsMin=oe);var we=oe+he*A;(!Z(m.ptsMax)||we>m.ptsMax)&&(m.ptsMax=we)}var Ce=A*O;C=oe+Ce,D+=Ce}}m.duration+=D,m.duration&&(s=!0)}}if(!s){for(var De=1/0,_e=0,Me=Ct(e,["sidx"]),xe=0;xe<Me.length;xe++){var Oe=_t(Me[xe]);if(null!=Oe&&Oe.references){De=Math.min(De,Oe.earliestPresentationTime/Oe.timescale);var Fe=Oe.references.reduce(function(e,t){return e+t.info.duration||0},0);_e=Math.max(_e,Fe+Oe.earliestPresentationTime/Oe.timescale)}}_e&&Z(_e)&&Object.keys(a).forEach(function(e){a[e].duration||(a[e].duration=_e*a[e].timescale-a[e].start)})}return a}function Kt(e,t){var r=new Uint8Array(e.length+t.length);return r.set(e),r.set(t,e.length),r}function jt(e){if(!e)return!1;var t=e.substring(0,4);return"hvc1"===t||"hev1"===t||"dvh1"===t||"dvhe"===t}function qt(e,t){if(e){var r=t>>1&63;return 39===r||40===r}return 6===(31&t)}function Wt(e,t,r,i){var n=Yt(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){je.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=St(n,c);if(c+=2,49===d){var h=Tt(n,c);if(c+=4,1195456820===h){var f=n[c++];if(3===f){var v=n[c++],g=64&v,p=g?2+3*(31&v):0,m=new Uint8Array(p);if(g){m[0]=v;for(var y=1;y<p;y++)m[y]=n[c++]}i.push({type:f,payloadType:s,pts:r,bytes:m})}}}}}else if(5===s&&o>16){for(var k=[],E=0;E<16;E++){var S=n[c++].toString(16);k.push(1==S.length?"0"+S:S),3!==E&&5!==E&&7!==E&&9!==E||k.push("-")}for(var T=o-16,A=new Uint8Array(T),b=0;b<T;b++)A[b]=n[c++];i.push({payloadType:s,pts:r,uuid:k.join(""),userData:Gt(A),userDataBytes:A})}}}function Yt(e){for(var t,r=e.byteLength,i=e.indexOf(3,3);-1!==i;)0===e[i-1]&&0===e[i-2]&&(t||(t=[])).push(i),i=e.indexOf(3,i+1);if(!t)return e;for(var n=r-t.length,a=new Uint8Array(n),s=0,o=0,l=0;l<n;o++,l++)o===t[s]&&(o++,s++),a[l]=e[o];return a}function zt(e,t,r){if(16!==e.byteLength)throw new RangeError("Invalid system id");var i,n;i=new Uint8Array,n=new Uint8Array;var a=new Uint8Array(4);return r.byteLength>0&&new DataView(a.buffer).setUint32(0,r.byteLength,!1),function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];for(var n=r.length,a=8,s=n;s--;)a+=r[s].byteLength;var o=new Uint8Array(a);for(o[0]=a>>24&255,o[1]=a>>16&255,o[2]=a>>8&255,o[3]=255&a,o.set(e,4),s=0,a=8;s<n;s++)o.set(r[s],a),a+=r[s].byteLength;return o}([112,115,115,104],new Uint8Array([0,0,0,0]),e,n,i,a,r)}function Xt(e){var t=[];if(e instanceof ArrayBuffer)for(var r=e.byteLength,i=0;i+32<r;){var n=Qt(new DataView(e,i));t.push(n),i+=n.size}return t}function Qt(e){var t=e.getUint32(0),r=e.byteOffset,i=e.byteLength;if(i<t)return{offset:r,size:i};if(1886614376!==e.getUint32(4))return{offset:r,size:t};var n=e.getUint32(8)>>>24;if(0!==n&&1!==n)return{offset:r,size:t};var a,s=e.buffer,o=ft(new Uint8Array(s,r+12,16)),l=null,u=0;if(0===n)u=28;else{var c=e.getUint32(28);if(!c||i<32+16*c)return{offset:r,size:t};l=[];for(var d=0;d<c;d++)l.push(new Uint8Array(s,r+32+16*d,16));u=32+16*c}if(!u)return{offset:r,size:t};var h=e.getUint32(u);return t-32<h?{offset:r,size:t}:(a=new Uint8Array(s,r+u+4,h),0===n&&(l=function(e){for(var t=[],r=0;r<e.length;){var i=e[r++],n=7&i;if(0!==n)if(2===n){for(var a=0,s=0,o=128;128&o;s+=7)a|=(127&(o=e[r++]))<<s;if(i>>3==2)if(32===a){for(var l=new Uint8Array(16),u=0;u<16;u++)l[u]=parseInt(String.fromCharCode(e[r+2*u],e[r+2*u+1]),16);t.push(l)}else 16===a&&t.push(e.subarray(r,r+16));r+=a}else r+=1===n?8:4;else for(;128&e[r++];);}return t}(a)),{version:n,systemId:o,kids:l,data:a,offset:r,size:t})}var $t,Jt,Zt,er=rr("userAgent"),tr=rr("vendor");function rr(e){try{return navigator[e]||""}catch(e){}return""}function ir(){if(void 0===$t){var e=er.match(/Chrome\/(\d+)/i);$t=e?parseInt(e[1]):0}return $t}function nr(){return/\(Windows.+Firefox\//i.test(er)}var ar={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},image:{mjpg:1}};function sr(e,t){var r=ar[t];return!!r&&!!r[e.slice(0,4)]}function or(e,t){var r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return!e.split(",").some(function(e){return!lr(e,t,r)})}function lr(e,t){var r,i=qe(!(arguments.length>2&&void 0!==arguments[2])||arguments[2]);return null!=(r=null==i?void 0:i.isTypeSupported(ur(e,t)))&&r}function ur(e,t){return"".concat(t,"/mp4;codecs=").concat(e)}function cr(e){if(e){var t=e.substring(0,4);return ar.video[t]}return 2}function dr(e){var t=nr();return e.split(",").reduce(function(e,r){var i=t&&jt(r)?9:ar.video[r];return i?(2*i+e)/(e?3:2):(ar.audio[r]+e)/(e?2:1)},0)}var hr={};var fr=/flac|opus|mp4a\.40\.34/i;function vr(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return e.replace(fr,function(e){return function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(hr[e])return hr[e];for(var r={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e],i=0;i<r.length;i++){var n;if(lr(r[i],"audio",t))return hr[e]=r[i],r[i];if("mp3"===r[i]&&null!=(n=qe(t))&&n.isTypeSupported("audio/mpeg"))return""}return e}(e.toLowerCase(),t)})}function gr(e,t){if(e&&(e.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e))&&(pr(e,"audio")||pr(e,"video")))return e;if(t){var r=t.split(",");if(r.length>1){if(e)for(var i=r.length;i--;)if(r[i].substring(0,4)===e.substring(0,4))return r[i];return r[0]}}return t||e}function pr(e,t){return sr(e,t)&&lr(e,t)}function mr(e){if(e.startsWith("av01.")){for(var t=e.split("."),r=["0","111","01","01","01","0"],i=t.length;i>4&&i<10;i++)t[i]=r[i-4];return t.join(".")}return e}function yr(e){var t=qe(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 kr(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}var Er={supported:!1,smooth:!1,powerEfficient:!1},Sr={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function Tr(e,t){return{supported:!1,configurations:t,decodingInfoResults:[Er],error:e}}function Ar(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},n=e.videoCodec;if(!n&&!e.audioCodec||!r)return Promise.resolve(Sr);for(var a=[],s=function(e){var t,r=null==(t=e.videoCodec)?void 0:t.split(","),i=Ir(e),n=e.width||640,a=e.height||480,s=e.frameRate||30,o=e.videoRange.toLowerCase();return r?r.map(function(e){var t={contentType:ur(mr(e),"video"),width:n,height:a,bitrate:i,framerate:s};return"sdr"!==o&&(t.transferFunction=o),t}):[]}(e),o=s.length,l=function(e,t,r){var i,n=null==(i=e.audioCodec)?void 0:i.split(","),a=Ir(e);if(n&&e.audioGroups)return e.audioGroups.reduce(function(e,i){var s,o=i?null==(s=t.groups[i])?void 0:s.tracks:null;return o?o.reduce(function(e,t){if(t.groupId===i){var s=parseFloat(t.channels||"");n.forEach(function(t){var i={contentType:ur(t,"audio"),bitrate:r?br(t,a):a};s&&(i.channels=""+s),e.push(i)})}return e},e):e},[]);return[]}(e,t,o>0),u=l.length,c=o||1*u||1;c--;){var d={type:"media-source"};if(o&&(d.video=s[c%o]),u){d.audio=l[c%u];var h=d.audio.bitrate;d.video&&h&&(d.video.bitrate-=h)}a.push(d)}if(n){var f=navigator.userAgent;if(n.split(",").some(function(e){return jt(e)})&&nr())return Promise.resolve(Tr(new Error("Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (".concat(f,")")),a))}return Promise.all(a.map(function(e){var t=function(e){var t="",r=e.audio,i=e.video;if(i){var n=kr(i.contentType);t+="".concat(n,"_r").concat(i.height,"x").concat(i.width,"f").concat(Math.ceil(i.framerate)).concat(i.transferFunction||"sd","_").concat(Math.ceil(i.bitrate/1e5))}if(r){var a=kr(r.contentType);t+="".concat(i?"_":"").concat(a,"_c").concat(r.channels)}return t}(e);return i[t]||(i[t]=r.decodingInfo(e))})).then(function(e){return{supported:!e.some(function(e){return!e.supported}),configurations:a,decodingInfoResults:e}}).catch(function(e){return{supported:!1,configurations:a,decodingInfoResults:[],error:e}})}function br(e,t){if(t<=1)return 1;var r=128e3;return"ec-3"===e?r=768e3:"ac-3"===e&&(r=64e4),Math.min(t/2,r)}function Ir(e){return 1e3*Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)/1e3)||1}function Rr(e,t,r){var i=encodeURIComponent(t),n="".concat(i,"=").concat(encodeURIComponent(r)),a=!1,s=[];e.search.substring(1).split("&").forEach(function(e){e===i||e.startsWith(i+"=")?a||(s.push(n),a=!0):e&&s.push(e)}),a||s.push(n),e.search=s.join("&")}var Lr=["NONE","TYPE-0","TYPE-1",null];var Pr=["SDR","PQ","HLG"];var wr="",Cr="YES",Dr="v2";function _r(e){var t=e.canSkipUntil,r=e.canSkipDateRanges,i=e.age;return t&&i<t/2?r?Dr:Cr:wr}var Mr=function(){return l(function e(t,r,i){s(this,e),this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=r,this.skip=i},[{key:"addDirectives",value:function(e){var t=new self.URL(e);return void 0!==this.msn&&Rr(t,"_HLS_msn",this.msn.toString()),void 0!==this.part&&Rr(t,"_HLS_part",this.part.toString()),this.skip&&Rr(t,"_HLS_skip",this.skip),t.href}}])}(),xr=function(){return l(function e(t){if(s(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.imageCodec=void 0,this.iframes=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loadErrorTime=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,"imageCodec"in t&&(this.imageCodec=t.imageCodec),this.codecSet=[t.videoCodec,t.audioCodec].filter(function(e){return!!e}).map(function(e){return e.substring(0,4)}).join(","),"supplemental"in t){var r;this.supplemental=t.supplemental;var i=null==(r=t.supplemental)?void 0:r.videoCodec;i&&i!==t.videoCodec&&(this.codecSet+=",".concat(i.substring(0,4)))}"iframes"in t&&t.iframes?this.iframes=!0:(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 Or(this._audioGroups,e)}},{key:"hasSubtitleGroup",value:function(e){return Or(this._subtitleGroups,e)}},{key:"audioGroups",get:function(){return this._audioGroups}},{key:"subtitleGroups",get:function(){return this._subtitleGroups}},{key:"addGroupId",value:function(e,t){if(t)if("audio"===e){var r=this._audioGroups;r||(r=this._audioGroups=[]),-1===r.indexOf(t)&&r.push(t)}else if("text"===e){var i=this._subtitleGroups;i||(i=this._subtitleGroups=[]),-1===i.indexOf(t)&&i.push(t)}}},{key:"urlId",get:function(){return 0},set:function(e){}},{key:"audioGroupIds",get:function(){return this.audioGroups?[this.audioGroupId]:void 0}},{key:"textGroupIds",get:function(){return this.subtitleGroups?[this.textGroupId]:void 0}},{key:"audioGroupId",get:function(){var e;return null==(e=this.audioGroups)?void 0:e[0]}},{key:"textGroupId",get:function(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}},{key:"addFallback",value:function(){}}])}();function Or(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}function Fr(e,t){var r=!1,i=[];if(e&&(r="SDR"!==e,i=[e]),t){var n="SDR"!==(i=t.allowedVideoRanges||Pr.slice(0)).join("")&&!t.videoCodec;(r=void 0!==t.preferHDR?t.preferHDR:n&&function(){if("function"==typeof matchMedia){var e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}())||(i=["SDR"])}return{preferHDR:r,allowedVideoRanges:i}}var Nr=function(e,t){return JSON.stringify(e,function(e){var t=new WeakSet;return function(r,i){if(e&&(i=e(r,i)),"object"===R(i)&&null!==i){if(t.has(i))return;t.add(i)}return i}}(t))};function Br(e,t){je.log('[abr] start candidates with "'.concat(e,'" ignored because ').concat(t))}function Ur(e){return e.reduce(function(e,t){var r=e.groups[t.groupId];r||(r=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),r.tracks.push(t);var i=t.channels||"2";return r.channels[i]=(r.channels[i]||0)+1,r.hasDefault=r.hasDefault||t.default,r.hasAutoSelect=r.hasAutoSelect||t.autoselect,r.hasDefault&&(e.hasDefaultAudio=!0),r.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Vr(e){return e?{lang:e.lang,assocLang:e.assocLang,characteristics:e.characteristics,channels:e.channels,audioCodec:e.audioCodec}:e}function Gr(e,t,r){if("attrs"in e){var i=t.indexOf(e);if(-1!==i)return i}for(var n=0;n<t.length;n++){if(Hr(e,t[n],r))return n}return-1}function Hr(e,t,r){var i=e.groupId,n=e.name,a=e.lang,s=e.assocLang,o=e.default,l=e.forced;return(void 0===i||t.groupId===i)&&(void 0===n||t.name===n)&&(void 0===a||function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"--";if(e.length===t.length)return e===t;return e.startsWith(t)||t.startsWith(e)}(a,t.lang))&&(void 0===s||t.assocLang===s)&&(void 0===o||t.default===o)&&(void 0===l||t.forced===l)&&(!("characteristics"in e)||function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",r=e.split(","),i=t.split(",");return r.length===i.length&&!r.some(function(e){return-1===i.indexOf(e)})}(e.characteristics||"",t.characteristics))&&(void 0===r||r(e,t))}function Kr(e,t){var r=e.audioCodec,i=e.channels;return!(void 0!==r&&(t.audioCodec||"").substring(0,4)!==r.substring(0,4)||void 0!==i&&i!==(t.channels||"2"))}function jr(e,t,r){for(var i=t;i>-1;i--)if(r(e[i]))return i;for(var n=t+1;n<e.length;n++)if(r(e[n]))return n;return-1}function qr(e,t){var r;return!!e&&e!==(null==(r=t.loadLevelObj)?void 0:r.uri)}function Wr(e,t){return!t||-1!==t.indexOf(e)}function Yr(e,t){if(t||e){var r=Ae({},t);return e&&(e.videoCodec&&(r.videoCodec=e.videoCodec),e.videoRange&&(r.allowedVideoRanges=[e.videoRange])),r}}var zr=function(e){function t(e){var r;return s(this,t),(r=a(this,t,["abr",e.logger])).hls=void 0,r.lastLevelLoadSec=0,r.lastLoadedFragLevel=-1,r.firstSelection=-1,r.firstAutoFloor=-1,r._nextAutoLevel=-1,r.nextAutoLevelKey="",r.audioTracksByGroup=null,r.codecTiers=null,r.timer=-1,r.fragCurrent=null,r.partCurrent=null,r.bitrateTestDelay=0,r.rebufferNotice=-1,r.supportedCache={},r.bwEstimator=void 0,r._abandonRulesCheck=function(e){var t,i=r,n=i.fragCurrent,a=i.partCurrent,s=i.hls;if(s){var o=s.autoLevelEnabled,l=s.media;if(n&&l){var u=performance.now(),c=a?a.stats:n.stats,d=a?a.duration:n.duration,h=u-c.loading.start,f=s.minAutoLevel,v=n.level,g=r._nextAutoLevel;if(c.aborted||c.loaded&&c.loaded===c.total||v<=f)return r.clearTimer(),void(r._nextAutoLevel=-1);if(o){var p=g>-1&&g!==v,m=!!e||p;if(m||!l.paused&&l.playbackRate&&l.readyState){var y=s.mainForwardBufferInfo;if(m||null!==y){var k=r.bwEstimator.getEstimateTTFB(),E=Math.abs(l.playbackRate);if(!(h<=Math.max(k,d/(2*E)*1e3))){var S=y?y.len/E:0,T=c.loading.first?c.loading.first-c.loading.start:-1,A=c.loaded&&T>-1,b=r.getBwEstimate(),I=s.levels,R=I[v],L=Math.max(c.loaded,Math.round(d*(n.bitrate||R.averageBitrate)/8)),P=A?h-T:h;P<1&&A&&(P=Math.min(h,8*c.loaded/b));var w=A?1e3*c.loaded/P:0,C=k/1e3,D=w?(L-c.loaded)/w:8*L/b+C;if(!(D<=S)){var _,M=w?8*w:b,x=!0===(null==(t=(null==e?void 0:e.details)||s.latestLevelDetails)?void 0:t.live),O=s.config.abrBandWidthUpFactor,F=Number.POSITIVE_INFINITY;for(_=v-1;_>f;_--){var N=I[_].maxBitrate,B=!I[_].details||x;if((F=r.getTimeToLoadFrag(C,M,d*N,B))<Math.min(S,d+C))break}if(!(F>=D||F>10*d)){A?r.bwEstimator.sample(h-Math.min(k,T),c.loaded):r.bwEstimator.sampleTTFB(h);var U=I[_].maxBitrate;r.getBwEstimate()*O>U&&(r.firstAutoFloor=Math.min(_,s.firstLevel),r.resetEstimator(U));var V=r.findBestLevel(U,f,_,0,S,1,1);V>-1&&(_=V),r.warn("Fragment ".concat(n.sn).concat(a?" part "+a.index:""," of level ").concat(v," is loading too slowly;\n Fragment duration: ").concat(n.duration.toFixed(3),"\n Time to underbuffer: ").concat(S.toFixed(3)," s\n Estimated load time for current fragment: ").concat(D.toFixed(3)," s\n Estimated load time for down switch fragment: ").concat(F.toFixed(3)," s\n TTFB estimate: ").concat(0|T," ms\n Current BW estimate: ").concat(Z(b)?0|b:"Unknown"," bps\n New BW estimate: ").concat(0|r.getBwEstimate()," bps\n Switching to level ").concat(_," @ ").concat(0|U," bps")),s.nextLoadLevel=s.nextAutoLevel=_,r.clearTimer();var G=function(){r.clearTimer();var e=r.hls;if(r.fragCurrent===n&&e.loadLevel===_&&_>0){var t=r.getStarvationDelay();if(r.warn("Aborting inflight request ".concat(_>0?"and switching down":"","\n Fragment duration: ").concat(n.duration.toFixed(3)," s\n Time to underbuffer: ").concat(t.toFixed(3)," s")),n.abortRequests(),r.fragCurrent=r.partCurrent=null,_>f){var i=r.findBestLevel(e.levels[f].bitrate,f,_,0,t,1,1);-1===i&&(i=f),e.nextLoadLevel=e.nextAutoLevel=i,r.firstAutoFloor=Math.min(i,e.firstLevel),r.resetEstimator(e.levels[i].bitrate)}}};p||D>2*F?G():r.timer=self.setInterval(G,1e3*F),s.trigger(ne.FRAG_LOAD_EMERGENCY_ABORTED,{frag:n,part:a,stats:c})}}}}}}}}},r.hls=e,r.bwEstimator=r.initEstimator(),r.registerListeners(),r}return f(t,e),l(t,[{key:"resetEstimator",value:function(e){this.hls&&(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 Ne(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}},{key:"registerListeners",value:function(){var e=this.hls;e.on(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ne.FRAG_LOADING,this.onFragLoading,this),e.on(ne.FRAG_LOADED,this.onFragLoaded,this),e.on(ne.FRAG_BUFFERED,this.onFragBuffered,this),e.on(ne.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(ne.LEVEL_LOADED,this.onLevelLoaded,this),e.on(ne.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(ne.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(ne.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ne.FRAG_LOADING,this.onFragLoading,this),e.off(ne.FRAG_LOADED,this.onFragLoaded,this),e.off(ne.FRAG_BUFFERED,this.onFragBuffered,this),e.off(ne.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(ne.LEVEL_LOADED,this.onLevelLoaded,this),e.off(ne.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(ne.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(ne.ERROR,this.onError,this))}},{key:"destroy",value:function(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.audioTracksByGroup=this.codecTiers=this.fragCurrent=this.partCurrent=null}},{key:"onManifestLoading",value:function(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}},{key:"onLevelsUpdated",value:function(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}},{key:"onMaxAutoLevelUpdated",value:function(){this.firstSelection=-1,this.nextAutoLevelKey=""}},{key:"onFragLoading",value:function(e,t){var r=t.frag;if(!this.ignoreFragment(r)){var i;if(!r.bitrateTest)this.fragCurrent=r,this.partCurrent=null!=(i=t.part)?i:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}},{key:"onLevelSwitching",value:function(e,t){this.clearTimer()}},{key:"onError",value:function(e,t){if(!t.fatal)switch(t.details){case ie.BUFFER_ADD_CODEC_ERROR:case ie.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case ie.FRAG_LOAD_TIMEOUT:var r=t.frag,i=this.fragCurrent,n=this.partCurrent;if(r&&ye(r,i)){var a=performance.now(),s=n?n.stats:r.stats,o=a-s.loading.start,l=s.loading.first?s.loading.first-s.loading.start:-1;if(s.loaded&&l>-1){var u=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(o-Math.min(u,l),s.loaded)}else this.bwEstimator.sampleTTFB(o)}}}},{key:"getTimeToLoadFrag",value:function(e,t,r,i){return e+r/t+(i?e+this.lastLevelLoadSec:0)}},{key:"onLevelLoaded",value:function(e,t){var r=this.hls.config,i=t.stats.loading,n=i.end-i.first;Z(n)&&(this.lastLevelLoadSec=n/1e3),t.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}},{key:"onFragLoaded",value:function(e,t){var r,i=t.frag,n=t.part,a=n?n.stats:i.stats;if(i.type===de.MAIN&&this.bwEstimator.sampleTTFB(a.loading.first-a.loading.start),!this.ignoreFragment(i)){if(this.clearTimer(),i.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,null!=(r=this.hls)&&r.config.abrMaxWithRealBitrate){var s=n?n.duration:i.duration,o=this.hls.levels[i.level],l=(o.loaded?o.loaded.bytes:0)+a.loaded,u=(o.loaded?o.loaded.duration:0)+s;o.loaded={bytes:l,duration:u},o.realBitrate=Math.round(8*l/u)}if(i.bitrateTest){var c={stats:a,frag:i,part:n,id:i.type};this.onFragBuffered(ne.FRAG_BUFFERED,c),i.bitrateTest=!1}else this.lastLoadedFragLevel=i.level}}},{key:"onFragBuffered",value:function(e,t){var r=t.frag,i=t.part,n=null!=i&&i.stats.loaded?i.stats:r.stats;if(!n.aborted&&!this.ignoreFragment(r)){var a=((r.bitrate||0)>=1e5?n.parsing.end:n.loading.end)-n.loading.start-Math.min(n.loading.first-n.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,n.loaded),n.bwEstimate=this.getBwEstimate(),r.bitrateTest?this.bitrateTestDelay=a/1e3:(this.bitrateTestDelay=0,this.firstAutoFloor>-1&&this.bwEstimator.canEstimate()&&(this.firstAutoFloor=-1))}}},{key:"ignoreFragment",value:function(e){return e.type!==de.MAIN||"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;if(!e)return 0;var t=e.maxAutoLevel,r=e.minAutoLevel,i=this.getBwEstimate(),n=this.getStarvationDelay(),a=e.config.maxStarvationDelay,s=this.findBestLevel(i,r,t,n/2,a,1,1);if(s>-1)return s;var o=e.firstLevel,l=-1===this.firstAutoFloor?1/0:this.firstAutoFloor,u=Math.min(Math.max(o,r),t,l);return this.warn("Could not find best starting auto level. Defaulting to first in playlist ".concat(o," clamped to ").concat(u)),u}},{key:"forcedAutoLevel",get:function(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}},{key:"nextAutoLevel",get:function(){if(!this.hls)return-1;var e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),r=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&r&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;var i=t&&r?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){var n=this.hls.levels;if(n.length>Math.max(e,i)&&n[e].loadError<=n[i].loadError)return e}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i},set:function(e){var t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}},{key:"getAutoLevelKey",value:function(){return"".concat(this.getBwEstimate(),"_").concat(this.getStarvationDelay().toFixed(2))}},{key:"getNextABRAutoLevel",value:function(){var e=this.fragCurrent,t=this.partCurrent,r=this.hls;if(!r)return-1;if(r.levels.length<=1)return r.loadLevel;var i=r.maxAutoLevel,n=r.config,a=r.minAutoLevel,s=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay(),u=n.abrBandWidthFactor,c=n.abrBandWidthUpFactor;if(l){var d=this.findBestLevel(o,a,i,l,0,u,c);if(d>=0)return this.rebufferNotice=-1,d}var h=s?Math.min(s,n.maxStarvationDelay):n.maxStarvationDelay;if(!l){var f=this.bitrateTestDelay;if(f)h=(s?Math.min(s,n.maxLoadingDelay):n.maxLoadingDelay)-f,this.info("bitrate test took ".concat(Math.round(1e3*f),"ms, set first fragment max fetchDuration to ").concat(Math.round(1e3*h)," ms")),u=c=1}var v=this.findBestLevel(o,a,i,l,h,u,c);if(this.rebufferNotice!==v&&(this.rebufferNotice=v,this.info("".concat(l?"rebuffering expected":"buffer is empty",", optimal quality level ").concat(v))),v>-1)return v;var g=r.levels[a],p=r.loadLevelObj;return p&&(null==g?void 0:g.bitrate)<p.bitrate?a:r.loadLevel}},{key:"getStarvationDelay",value:function(){var e=this.hls,t=null==e?void 0:e.media;if(!t)return 1/0;var r=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/r}},{key:"getBwEstimate",value:function(){return this.bwEstimator.getEstimate()}},{key:"findBestLevel",value:function(e,t,r,i,n,a,s){var o=this,l=this.hls,u=this.lastLoadedFragLevel,c=this.fragCurrent,d=this.partCurrent;if(!l)return-1;var h=i+n,f=-1===u?l.firstLevel:u,v=l.levels,g=l.allAudioTracks,p=l.loadLevel,m=l.latestLevelDetails,y=l.config;if(1===v.length)return 0;var k,E=v[f],S=!(null==m||!m.live),T=-1===p||-1===u,A="SDR",b=(null==E?void 0:E.frameRate)||0,I=y.audioPreference,R=y.videoPreference,L=this.audioTracksByGroup||(this.audioTracksByGroup=Ur(g)),P=-1;if(T){if(-1!==this.firstSelection)return this.firstSelection;var w=this.codecTiers||(this.codecTiers=function(e,t,r,i){return e.slice(r,i+1).reduce(function(e,r,i){if(!r.codecSet)return e;var n=r.audioGroups,a=e[r.codecSet];a||(e[r.codecSet]=a={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:i,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!n,fragmentError:0}),a.minBitrate=Math.min(a.minBitrate,r.bitrate);var s=Math.min(r.height,r.width);return a.minHeight=Math.min(a.minHeight,s),a.minFramerate=Math.min(a.minFramerate,r.frameRate),a.minIndex=Math.min(a.minIndex,i),a.maxScore=Math.max(a.maxScore,r.score),a.fragmentError+=r.fragmentError,a.videoRanges[r.videoRange]=(a.videoRanges[r.videoRange]||0)+1,n&&n.forEach(function(e){if(e){var r=t.groups[e];r&&(a.hasDefaultAudio=a.hasDefaultAudio||t.hasDefaultAudio?r.hasDefault:r.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(r.channels).forEach(function(e){a.channels[e]=(a.channels[e]||0)+r.channels[e]}))}}),e},{})}(v,L,t,r)),C=function(e,t,r,i,n){for(var a=Object.keys(e),s=null==i?void 0:i.channels,o=null==i?void 0:i.audioCodec,l=null==n?void 0:n.videoCodec,u=s&&2===parseInt(s),c=!1,d=!1,h=1/0,f=1/0,v=1/0,g=1/0,p=0,m=[],y=Fr(t,n),k=y.preferHDR,E=y.allowedVideoRanges,S=function(){var t=e[a[T]];c||(c=t.channels[2]>0),h=Math.min(h,t.minHeight),f=Math.min(f,t.minFramerate),v=Math.min(v,t.minBitrate),E.filter(function(e){return t.videoRanges[e]>0}).length>0&&(d=!0)},T=a.length;T--;)S();h=Z(h)?h:0,f=Z(f)?f:0;var A=Math.max(1080,h),b=Math.max(30,f);v=Z(v)?v:r,r=Math.max(v,r),d||(t=void 0);var I=a.length>1;return{codecSet:a.reduce(function(t,i){var n=e[i];if(i===t)return t;if(m=d?E.filter(function(e){return n.videoRanges[e]>0}):[],I){if(n.minBitrate>r)return Br(i,"min bitrate of ".concat(n.minBitrate," > current estimate of ").concat(r)),t;if(!n.hasDefaultAudio)return Br(i,"no renditions with default or auto-select sound found"),t;if(o&&i.indexOf(o.substring(0,4))%5!=0)return Br(i,'audio codec preference "'.concat(o,'" not found')),t;if(s&&!u){if(!n.channels[s])return Br(i,"no renditions with ".concat(s," channel sound found (channels options: ").concat(Object.keys(n.channels),")")),t}else if((!o||u)&&c&&0===n.channels[2])return Br(i,"no renditions with stereo sound found"),t;if(n.minHeight>A)return Br(i,"min resolution of ".concat(n.minHeight," > maximum of ").concat(A)),t;if(n.minFramerate>b)return Br(i,"min framerate of ".concat(n.minFramerate," > maximum of ").concat(b)),t;if(!m.some(function(e){return n.videoRanges[e]>0}))return Br(i,"no variants with VIDEO-RANGE of ".concat(Nr(m)," found")),t;if(l&&i.indexOf(l.substring(0,4))%5!=0)return Br(i,'video codec preference "'.concat(l,'" not found')),t;if(n.maxScore<p)return Br(i,"max score of ".concat(n.maxScore," < selected max of ").concat(p)),t}return t&&(dr(i)>=dr(t)||n.fragmentError>e[t].fragmentError)?t:(g=n.minIndex,p=n.maxScore,i)},void 0),videoRanges:m,preferHDR:k,minFramerate:f,minBitrate:v,minIndex:g}}(w,A,e,I,R),D=C.codecSet,_=C.videoRanges,M=C.minFramerate,x=C.minBitrate,O=C.minIndex,F=C.preferHDR;P=O,k=D,A=F?_[_.length-1]:_[0],b=M,e=Math.max(e,x),this.log("picked start tier ".concat(Nr(C)))}else k=null==E?void 0:E.codecSet,A=null==E?void 0:E.videoRange;for(var N,B,U=d?d.duration:c?c.duration:0,V=this.bwEstimator.getEstimateTTFB()/1e3,G=[],H=function(){var t=v[K],l=K>f;if(!t)return 0;if(y.useMediaCapabilities&&!t.supportedResult&&!t.supportedPromise){var c=navigator.mediaCapabilities;"function"==typeof(null==c?void 0:c.decodingInfo)&&function(e,t,r,i,n,a){var s=e.videoCodec,o=e.audioCodec?e.audioGroups:null,l=null==a?void 0:a.audioCodec,u=null==a?void 0:a.channels,c=u?parseInt(u):l?1/0:2,d=null;if(null!=o&&o.length)try{d=1===o.length&&o[0]?t.groups[o[0]].channels:o.reduce(function(e,r){if(r){var i=t.groups[r];if(!i)throw new Error("Audio track group ".concat(r," not found"));Object.keys(i.channels).forEach(function(t){e[t]=(e[t]||0)+i.channels[t]})}return e},{2:0})}catch(e){return!0}return void 0!==s&&(s.split(",").some(function(e){return jt(e)})||e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(i,30)||"SDR"!==e.videoRange&&e.videoRange!==r||e.bitrate>Math.max(n,8e6))||!!d&&Z(c)&&Object.keys(d).some(function(e){return parseInt(e)>c})}(t,L,A,b,e,I)?(t.supportedPromise=Ar(t,L,c,o.supportedCache),t.supportedPromise.then(function(e){if(o.hls){t.supportedResult=e;var r=o.hls.levels,i=r.indexOf(t);e.error?o.warn('MediaCapabilities decodingInfo error: "'.concat(e.error,'" for level ').concat(i," ").concat(Nr(e))):e.supported?e.decodingInfoResults.some(function(e){return!1===e.smooth||!1===e.powerEfficient})&&o.log("MediaCapabilities decodingInfo for level ".concat(i," not smooth or powerEfficient: ").concat(Nr(e))):(o.warn("Unsupported MediaCapabilities decodingInfo result for level ".concat(i," ").concat(Nr(e))),i>-1&&r.length>1&&(o.log("Removing unsupported level ".concat(i)),o.hls.removeLevel(i),-1===o.hls.loadLevel&&(o.hls.nextLoadLevel=0)))}}).catch(function(e){o.warn("Error handling MediaCapabilities decodingInfo: ".concat(e))})):t.supportedResult=Sr}if((k&&t.codecSet!==k||A&&t.videoRange!==A||l&&b>t.frameRate||!l&&b>0&&b<t.frameRate||null!=(N=t.supportedResult)&&null!=(N=N.decodingInfoResults)&&N.some(function(e){return!1===e.smooth}))&&(!T||K!==P))return G.push(K),0;var g,m=t.details,E=(d?null==m?void 0:m.partTarget:null==m?void 0:m.averagetargetduration)||U||1;g=l?s*e:a*e;var R=U&&i>=2*U&&0===n?t.averageBitrate:t.maxBitrate,w=o.getTimeToLoadFrag(V,g,R*E,!m||m.live);if(g>=R&&(K===u||0===t.loadError&&0===t.fragmentError||Oe(t,y.errorPenaltyExpireMs))&&(w<=V||!Z(w)||S&&!o.bitrateTestDelay||w<h)){var C=o.forcedAutoLevel;return K===p||-1!==C&&C===p||(G.length&&o.trace("Skipped level(s) ".concat(G.join(",")," of ").concat(r,' max with CODECS and VIDEO-RANGE:"').concat(v[G[0]].codecs,'" ').concat(v[G[0]].videoRange,'; not compatible with "').concat(k,'" ').concat(A)),o.info("switch candidate:".concat(f,"->").concat(K," adjustedbw(").concat(Math.round(g),")-bitrate=").concat(Math.round(g-R)," ttfb:").concat(V.toFixed(1)," avgDuration:").concat(E.toFixed(1)," maxFetchDuration:").concat(h.toFixed(1)," fetchDuration:").concat(w.toFixed(1)," firstSelection:").concat(T," codecSet:").concat(t.codecSet," videoRange:").concat(t.videoRange," hls.loadLevel:").concat(p))),T&&(o.firstSelection=K),{v:K}}},K=r;K>=t;K--)if(0!==(B=H())&&B)return B.v;return-1}},{key:"deriveNextAutoLevel",value:function(e){if(!this.hls)return-1;var t=this.hls,r=t.maxAutoLevel,i=t.minAutoLevel;return Math.min(Math.max(e,i),r)}}])}(Be),Xr=function(e,t){for(var r=0,i=e.length-1,n=null,a=null;r<=i;){var s=t(a=e[n=(r+i)/2|0]);if(s>0)r=n+1;else{if(!(s<0))return a;i=n-1}}return null};function Qr(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:.005,a=null;if(e){a=t[1+e.sn-t[0].sn]||null;var s=e.endDTS-r;s>0&&s<15e-7&&(r+=15e-7),a&&e.level!==a.level&&a.end<=e.end&&(a=t[2+e.sn-t[0].sn]||null)}else 0===r&&0===t[0].start&&(a=t[0]);if(a&&((!e||e.level===a.level)&&0===$r(r,i,a)||function(e,t,r){if(0===(null==t?void 0:t.start)&&t.level<e.level&&(t.endPTS||0)>0){var i=t.tagList.reduce(function(e,t){return"INF"===t[0]&&(e+=parseFloat(t[1])),e},r);return e.start<=i}return!1}(a,e,Math.min(n,i))))return a;var o=Xr(t,$r.bind(null,r,i));return!o||o===e&&a?a:o}function $r(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2?arguments[2]:void 0;if(r.start<=e&&r.start+r.duration>e)return 0;var i=Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-i<=e?1:r.start-i>e&&r.start?-1:0}function Jr(e,t,r){var i=1e3*Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-i>e}function Zr(e,t,r){if(e&&e.startCC<=t&&e.endCC>=t){var i,n=e.fragments,a=e.fragmentHint;return a&&(n=n.concat(a)),Xr(n,function(e){return e.cc<t?1:e.cc>t?-1:(i=e,e.end<=r?1:e.start>r?-1:0)}),i||null}return null}function ei(e,t){return t===e.endSN&&e.fragmentHint?e.fragmentHint:e.fragments[1+t-e.startSN]||null}var ti=0,ri=2,ii=3,ni=5,ai=0,si=1,oi=2,li=4,ui=8,ci=16,di=function(e){function t(e){var r;return s(this,t),(r=a(this,t,["error-controller",e.logger])).hls=void 0,r.playlistError=0,r.hls=e,r.registerListeners(),r}return f(t,e),l(t,[{key:"registerListeners",value:function(){var e=this.hls;e.on(ne.ERROR,this.onError,this),e.on(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ne.LEVEL_UPDATED,this.onLevelUpdated,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ne.ERROR,this.onError,this),e.off(ne.ERROR,this.onErrorOut,this),e.off(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ne.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)===de.MAIN?e.level:this.getVariantIndex()}},{key:"getVariantIndex",value:function(){var e,t=this.hls,r=t.currentLevel;return null!=(e=t.loadLevelObj)&&e.details||-1===r?t.loadLevel:r}},{key:"variantHasKey",value:function(e,t){if(e){var r;if(null!=(r=e.details)&&r.hasKey(t))return!0;var i=e.audioGroups;if(i)return this.hls.allAudioTracks.filter(function(e){return i.indexOf(e.groupId)>=0}).some(function(e){var r;return null==(r=e.details)?void 0:r.hasKey(t)})}return!1}},{key:"onManifestLoading",value:function(){this.playlistError=0}},{key:"onLevelUpdated",value:function(){this.playlistError=0}},{key:"onError",value:function(e,t){var r;if(!t.fatal){var i=this.hls,n=t.context;switch(t.details){case ie.FRAG_LOAD_ERROR:case ie.FRAG_LOAD_TIMEOUT:case ie.KEY_LOAD_ERROR:case ie.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case ie.FRAG_PARSING_ERROR:if(null!=(r=t.frag)&&r.gap)return void(t.errorAction=vi());case ie.FRAG_GAP:case ie.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=ri);case ie.PLAYLIST_UNCHANGED_ERROR:case ie.LEVEL_EMPTY_ERROR:case ie.LEVEL_PARSING_ERROR:var a,s=t.parent===de.MAIN?t.level:i.loadLevel;return void(t.details===ie.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 ie.LEVEL_LOAD_ERROR:case ie.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==n?void 0:n.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level)));case ie.AUDIO_TRACK_LOAD_ERROR:case ie.AUDIO_TRACK_LOAD_TIMEOUT:case ie.SUBTITLE_LOAD_ERROR:case ie.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){var o=i.loadLevelObj;if(o&&(n.type===ce.AUDIO_TRACK&&o.hasAudioGroup(n.groupId)||n.type===ce.SUBTITLE_TRACK&&o.hasSubtitleGroup(n.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.loadLevel),t.errorAction.action=ri,void(t.errorAction.flags=si)}return;case ie.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(t.errorAction={action:ri,flags:oi});case ie.KEY_SYSTEM_SESSION_UPDATE_FAILED:case ie.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case ie.KEY_SYSTEM_NO_SESSION:return void(t.errorAction={action:ri,flags:li});case ie.BUFFER_ADD_CODEC_ERROR:case ie.REMUX_ALLOC_ERROR:case ie.BUFFER_APPEND_ERROR:return void(t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,t.level)));case ie.MEDIA_SOURCE_REQUIRES_RESET:return t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,t.level)),void(t.errorAction.flags|=ci|ui);case ie.INTERNAL_EXCEPTION:case ie.BUFFER_APPENDING_ERROR:case ie.BUFFER_APPEND_NO_PROGRESS:case ie.BUFFER_FULL_ERROR:case ie.LEVEL_SWITCH_ERROR:case ie.BUFFER_STALLED_ERROR:case ie.BUFFER_SEEK_OVER_HOLE:case ie.BUFFER_NUDGE_ON_STALL:return void(t.errorAction=vi())}t.type===re.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=vi())}}},{key:"getPlaylistRetryOrSwitchAction",value:function(e,t){var r=Ce(this.hls.config.playlistLoadPolicy,e),i=this.playlistError++;if(Me(r,i,Le(e),e.response))return{action:ni,flags:ai,retryConfig:r,retryCount:i};var n=this.getLevelSwitchAction(e,t);return r&&(n.retryConfig=r,n.retryCount=i),n}},{key:"getFragRetryOrSwitchAction",value:function(e){var t=this.hls,r=this.getVariantLevelIndex(e.frag),i=t.levels[r],n=t.config,a=n.fragLoadPolicy,s=n.keyLoadPolicy,o=Ce(Pe(e)?s:a,e),l=t.levels.reduce(function(e,t){return e+t.fragmentError},0);if(i&&(e.details!==ie.FRAG_GAP&&i.fragmentError++,!we(e)&&Me(o,l,Le(e),e.response)))return{action:ni,flags:ai,retryConfig:o,retryCount:l};var u=this.getLevelSwitchAction(e,r);return o&&(u.retryConfig=o,u.retryCount=l),u}},{key:"getLevelSwitchAction",value:function(e,t){var r=this.hls;null==t&&(t=r.loadLevel);var i=this.hls.levels[t];if(i){var n,a,s=e.details;i.loadError++,i.loadErrorTime=self.performance.now(),s===ie.BUFFER_APPEND_ERROR&&i.fragmentError++;var o=-1,l=r.levels,u=r.loadLevel,c=r.minAutoLevel,d=r.maxAutoLevel;r.autoLevelEnabled||r.config.preserveManualLevelOnError||(r.loadLevel=-1);for(var h,f,v,g=null==(n=e.frag)?void 0:n.type,p=(g===de.AUDIO&&s===ie.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&hi(e))&&l.some(function(e){var t=e.audioCodec;return i.audioCodec!==t}),m="video"===e.sourceBufferName&&hi(e)&&l.some(function(e){var t=e.codecSet,r=e.audioCodec;return i.codecSet!==t&&i.audioCodec===r}),y=null!=(a=e.context)?a:{},k=y.type,E=y.groupId,S=function(){var t=(T+u)%l.length;if(t!==u&&t>=c&&t<=d&&(0===l[t].loadError||Oe(l[t],r.config.errorPenaltyExpireMs))){var n=l[t];if(s===ie.FRAG_GAP&&g===de.MAIN&&e.frag){var a=l[t].details;if(a){var v=Qr(e.frag,a.fragments,e.frag.start);if(null!=v&&v.gap)return 0}}else{if(k===ce.AUDIO_TRACK&&n.hasAudioGroup(E)||k===ce.SUBTITLE_TRACK&&n.hasSubtitleGroup(E))return 0;if(g===de.AUDIO&&null!=(h=i.audioGroups)&&h.some(function(e){return n.hasAudioGroup(e)})||g===de.SUBTITLE&&null!=(f=i.subtitleGroups)&&f.some(function(e){return n.hasSubtitleGroup(e)})||p&&i.audioCodec===n.audioCodec||m&&i.codecSet===n.codecSet||!p&&i.audioCodec!==n.audioCodec)return 0}return o=t,1}},T=l.length;T--&&(0===(v=S())||1!==v););if(o>-1&&r.loadLevel!==o)return e.levelRetry=!0,this.playlistError=0,{action:ri,flags:ai,nextAutoLevel:o}}return{action:ri,flags:si}}},{key:"onErrorOut",value:function(e,t){var r,i;switch(null==(r=t.errorAction)?void 0:r.action){case ti:break;case ri:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===ie.FRAG_GAP||t.details===ie.PLAYLIST_UNCHANGED_ERROR||fi(t)||(t.fatal=!0)}((null==(i=t.errorAction)?void 0:i.flags)||0)&ci&&this.hls.recoverMediaError(),t.fatal&&this.hls.stopLoad()}},{key:"sendAlternateToPenaltyBox",value:function(e){var t=this.hls,r=e.errorAction;if(r){var i=r.nextAutoLevel;if(r.flags===ai)this.switchLevel(e,i);else if(r.flags&ui)for(var n=this.hls.levels,a=n.length;a--;)"SDR"!==n[a].videoRange?(n[a].fragmentError++,n[a].loadError++):void 0===i&&(i=a);else if(r.flags&oi){var s=this.getVariantLevelIndex(e.frag),o=t.levels[s],l=null==o?void 0:o.attrs["HDCP-LEVEL"];r.hdcpLevel=l;var u="NONE"===l;l&&!u?(t.maxHdcpLevel=Lr[Lr.indexOf(l)-1],r.resolved=!0,this.warn('Restricting playback to HDCP-LEVEL of "'.concat(t.maxHdcpLevel,'" or lower'))):(u&&this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE"),r.flags|=li)}if(r.flags&li){var c=e.decryptdata;if(c){for(var d=this.hls.levels,h=d.length,f=h;f--;){var v,g;if(this.variantHasKey(d[f],c))this.log("Banned key found in level ".concat(f," (").concat(d[f].bitrate,'bps) or audio group "').concat(null==(v=d[f].audioGroups)?void 0:v.join(","),'" (').concat(null==(g=e.frag)?void 0:g.type," fragment) ").concat(ft(c.keyId||[]))),d[f].fragmentError++,d[f].loadError++,this.log("Removing level ".concat(f," with key error (").concat(e.error,")")),this.hls.removeLevel(f)}var p=e.frag;if(this.hls.levels.length<h)r.resolved=!0;else if(p&&p.type!==de.MAIN){var m=p.decryptdata;m&&!c.matches(m)&&(r.resolved=!0)}}}r.resolved||this.switchLevel(e,i)}}},{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===ie.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&"audiovideo"!==e.sourceBufferName))for(var r=kr(e.mimeType),i=this.hls.levels,n=i.length;n--;)i[n]["".concat(e.sourceBufferName,"Codec")]===r&&(this.log("Removing level ".concat(n," for ").concat(e.details,' ("').concat(r,'" not supported)')),this.hls.removeLevel(n))}}])}(Be);function hi(e){var t=e.details;return t===ie.BUFFER_ADD_CODEC_ERROR||t===ie.MEDIA_SOURCE_REQUIRES_RESET||t===ie.BUFFER_APPEND_ERROR&&!fi(e)}function fi(e){return e.details===ie.BUFFER_APPEND_ERROR&&("QuotaExceededError"===e.error.name||"InvalidStateError"===e.error.name)}function vi(e){var t={action:ti,flags:ai};return e&&(t.resolved=!0),t}var gi="NOT_LOADED",pi="APPENDING",mi="PARTIAL",yi="OK",ki=function(){return l(function e(t){s(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(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ne.BUFFER_APPENDED,this.onBufferAppended,this),e.on(ne.FRAG_BUFFERED,this.onFragBuffered,this),e.on(ne.FRAG_LOADED,this.onFragLoaded,this))}},{key:"_unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ne.BUFFER_APPENDED,this.onBufferAppended,this),e.off(ne.FRAG_BUFFERED,this.onFragBuffered,this),e.off(ne.FRAG_LOADED,this.onFragLoaded,this))}},{key:"destroy",value:function(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}},{key:"getAppendedFrag",value:function(e,t){var r=this.activePartLists[t];if(r)for(var i=r.length;i--;){var n=r[i];if(!n)break;if(n.start<=e&&e<=n.end&&n.loaded)return n}return this.getBufferedFrag(e,t)}},{key:"getBufferedFrag",value:function(e,t){return this.getFragAtPos(e,t,!0)}},{key:"getFragAtPos",value:function(e,t,r){for(var i=this.fragments,n=Object.keys(i),a=n.length;a--;){var s=i[n[a]];if((null==s?void 0:s.body.type)===t&&(!r||s.buffered)){var o=s.body;if(o.start<=e&&e<=o.end)return o}}return null}},{key:"detectEvictedFragments",value:function(e,t,r,i,n,a){var s=this;this.timeRanges&&(this.timeRanges[e]=t);var o=(null==n?void 0:n.fragment.sn)||-1;Object.keys(this.fragments).forEach(function(n){var l=s.fragments[n];if(l&&s.hls){var u=l.body;if(!(o>=u.sn))if(l.buffered||l.loaded&&!a){var c=l.range[e];if(c)if(0!==c.time.length){if(c.time.some(function(e){var r=!s.isTimeBuffered(e.startPTS,e.endPTS,t);return r&&s.removeFragment(u),r}),i&&i!==u&&ir()){var d=i.endPTS,h=u.startPTS;if(d&&h&&l.range.video){var f=h-d;f<0&&f>-.1&&(s.removeFragment(u),s.hls.trigger(ne.BUFFER_FLUSHING,{startOffset:d+.004,endOffset:1/0,type:"video"}))}}}else s.removeFragment(u)}else u.type===r&&s.removeFragment(u)}})}},{key:"detectPartialFragments",value:function(e){var t=this,r=this.timeRanges,i=e.frag,n=e.part,a=e.id;if(r&&pe(i)){var s=Si(i),o=this.fragments[s];if(!(!o||o.buffered&&i.gap)){var l=!i.relurl;Object.keys(r).forEach(function(e){var s=i.elementaryStreams[e];if(s){var u=r[e],c=l||!0===s.partial;o.range[e]=t.getBufferedTimes(i,n,c,u),t.detectEvictedFragments(e,u,a,i,n)}}),o.loaded=null;var u=Object.keys(o.range);if(u.length){if(this.bufferedEnd(o,i),Ei(o)||this.removeParts(i.sn-1,i.type),!n){var c=Math.min(.004,i.duration);u.some(function(e){var r,n=null==(r=o.range[e])?void 0:r.time,a=0===n.length||1===n.length&&n[0].endPTS-n[0].startPTS<c;return a&&t.addAsGap(i),a})}}else this.removeFragment(i)}}}},{key:"addAsGap",value:function(e){e.gap=!0,this.removeFragment(e),this.fragBuffered(e,!0)}},{key:"bufferedEnd",value:function(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&!t.gap&&(this.endListFragments[e.body.type]=e)}},{key:"removeParts",value:function(e,t){var r=this.activePartLists[t];r&&(this.activePartLists[t]=Ti(r,function(t){return t.fragment.sn>=e}))}},{key:"fragBuffered",value:function(e,t){var r=Si(e),i=this.fragments[r];return!i&&t&&(i=this.fragments[r]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,this.bufferedEnd(i,e)),i}},{key:"getBufferedTimes",value:function(e,t,r,i){for(var n={time:[],partial:r},a=e.start,s=e.end,o=e.minEndPTS||s,l=e.maxStartPTS||a,u=0;u<i.length;u++){var c=i.start(u)-this.bufferPadding,d=i.end(u)+this.bufferPadding;if(l>=c&&o<=d){n.time.push({startPTS:Math.max(a,i.start(u)),endPTS:Math.min(s,i.end(u))});break}if(a<d&&s>c){var h=Math.max(a,i.start(u)),f=Math.min(s,i.end(u));f>h&&(n.partial=!0,n.time.push({startPTS:h,endPTS:f}))}else if(s<=c)break}return n}},{key:"getPartialFragment",value:function(e){var t,r,i,n=null,a=0,s=this.bufferPadding,o=this.fragments;return Object.keys(o).forEach(function(l){var u=o[l];u&&Ei(u)&&(r=u.body.start-s,i=u.body.end+s,e>=r&&e<=i&&(t=Math.min(e-r,i-e),a<=t&&(n=u.body,a=t)))}),n}},{key:"isEndListAppended",value:function(e){var t=this.endListFragments[e];return void 0!==t&&(t.buffered||Ei(t))}},{key:"getState",value:function(e){var t=Si(e),r=this.fragments[t];return r?r.buffered?Ei(r)?mi:yi:pi:gi}},{key:"isTimeBuffered",value:function(e,t,r){for(var i,n,a=0;a<r.length;a++){if(i=r.start(a)-this.bufferPadding,n=r.end(a)+this.bufferPadding,e>=i&&t<=n)return!0;if(t<=i)return!1}return!1}},{key:"onManifestLoading",value:function(){this.removeAllFragments()}},{key:"onFragLoaded",value:function(e,t){if(pe(t.frag)&&!t.frag.bitrateTest){var r=t.frag,i=t.part?null:t,n=Si(r);this.fragments[n]={body:r,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}}},{key:"onBufferAppended",value:function(e,t){var r=t.frag,i=t.part,n=t.timeRanges;if(pe(r)){var a=r.type;if(i){var s=this.activePartLists[a];s||(this.activePartLists[a]=s=[]),s.push(i)}this.timeRanges=n}}},{key:"onFragBuffered",value:function(e,t){this.detectPartialFragments(t)}},{key:"hasFragment",value:function(e){var t=Si(e);return!!this.fragments[t]}},{key:"hasFragments",value:function(e){var t=this.fragments,r=Object.keys(t);if(!e)return r.length>0;for(var i=r.length;i--;){var n=t[r[i]];if((null==n?void 0:n.body.type)===e)return!0}return!1}},{key:"hasParts",value:function(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)}},{key:"getBackBufferEvictionEnd",value:function(e,t,r){for(var i=this.fragments,n=0,a=0,s=Object.keys(i),o=0;o<s.length;o++){var l=i[s[o]];if(l&&l.buffered&&l.body.type===t){var u=l.body;if(u.gap)return 0;var c=u.hasStats&&u.stats.loaded||u.byteLength||u.bitrate&&8*u.bitrate*u.duration;if(u.end<=e&&c&&(n+=c,a=Math.max(a,u.end),n>=r))return a}}return a>0?a:0}},{key:"removeFragmentsInRange",value:function(e,t,r,i,n){var a=this;i&&!this.hasGaps||Object.keys(this.fragments).forEach(function(s){var o=a.fragments[s];if(o){var l=o.body;l.type!==r||i&&!l.gap||l.start<t&&l.end>e&&(o.buffered||n)&&a.removeFragment(l)}})}},{key:"removeFragment",value:function(e){var t=Si(e);e.clearElementaryStreamInfo();var r=this.activePartLists[e.type];if(r){var i=e.sn;this.activePartLists[e.type]=Ti(r,function(e){return e.fragment.sn!==i})}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}},{key:"removeAllFragments",value:function(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;var t=null==(e=this.hls)||null==(e=e.latestLevelDetails)?void 0:e.partList;t&&t.forEach(function(e){return e.clearElementaryStreamInfo()})}}])}();function Ei(e){var t,r,i,n;return e.buffered&&!!(e.body.gap||null!=(t=e.range.video)&&t.partial||null!=(r=e.range.audio)&&r.partial||null!=(i=e.range.audiovideo)&&i.partial||null!=(n=e.range.subs)&&n.partial)}function Si(e){return"".concat(e.type,"_").concat(e.level,"_").concat(e.sn)}function Ti(e,t){return e.filter(function(e){var r=t(e);return r||e.clearElementaryStreamInfo(),r})}var Ai=0,bi=1,Ii=function(){return l(function e(t,r,i){s(this,e),this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=r,this.aesMode=i},[{key:"decrypt",value:function(e,t){switch(this.aesMode){case Ai:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case bi: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 Ri=function(){return l(function e(){s(this,e),this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()},[{key:"uint8ArrayToUint32Array_",value:function(e){for(var t=new DataView(e),r=new Uint32Array(4),i=0;i<4;i++)r[i]=t.getUint32(4*i);return r}},{key:"initTable",value:function(){var e=this.sBox,t=this.invSBox,r=this.subMix,i=r[0],n=r[1],a=r[2],s=r[3],o=this.invSubMix,l=o[0],u=o[1],c=o[2],d=o[3],h=new Uint32Array(256),f=0,v=0,g=0;for(g=0;g<256;g++)h[g]=g<128?g<<1:g<<1^283;for(g=0;g<256;g++){var p=v^v<<1^v<<2^v<<3^v<<4;p=p>>>8^255&p^99,e[f]=p,t[p]=f;var m=h[f],y=h[m],k=h[y],E=257*h[p]^16843008*p;i[f]=E<<24|E>>>8,n[f]=E<<16|E>>>16,a[f]=E<<8|E>>>24,s[f]=E,E=16843009*k^65537*y^257*m^16843008*f,l[p]=E<<24|E>>>8,u[p]=E<<16|E>>>16,c[p]=E<<8|E>>>24,d[p]=E,f?(f=m^h[h[h[k^m]]],v^=h[h[v]]):f=v=1}}},{key:"expandKey",value:function(e){for(var t=this.uint8ArrayToUint32Array_(e),r=!0,i=0;i<t.length&&r;)r=t[i]===this.key[i],i++;if(!r){this.key=t;var n=this.keySize=t.length;if(4!==n&&6!==n&&8!==n)throw new Error("Invalid aes key size="+n);var a,s,o,l,u=this.ksRows=4*(n+6+1),c=this.keySchedule=new Uint32Array(u),d=this.invKeySchedule=new Uint32Array(u),h=this.sBox,f=this.rcon,v=this.invSubMix,g=v[0],p=v[1],m=v[2],y=v[3];for(a=0;a<u;a++)a<n?o=c[a]=t[a]:(l=o,a%n===0?(l=h[(l=l<<8|l>>>24)>>>24]<<24|h[l>>>16&255]<<16|h[l>>>8&255]<<8|h[255&l],l^=f[a/n|0]<<24):n>6&&a%n===4&&(l=h[l>>>24]<<24|h[l>>>16&255]<<16|h[l>>>8&255]<<8|h[255&l]),c[a]=o=(c[a-n]^l)>>>0);for(s=0;s<u;s++)a=u-s,l=3&s?c[a]:c[a-4],d[s]=s<4||a<=4?l:g[h[l>>>24]]^p[h[l>>>16&255]]^m[h[l>>>8&255]]^y[h[255&l]],d[s]=d[s]>>>0}}},{key:"networkToHostOrderSwap",value:function(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24}},{key:"decrypt",value:function(e,t,r){for(var i,n,a,s,o,l,u,c,d,h,f,v,g,p,m=this.keySize+6,y=this.invKeySchedule,k=this.invSBox,E=this.invSubMix,S=E[0],T=E[1],A=E[2],b=E[3],I=this.uint8ArrayToUint32Array_(r),R=I[0],L=I[1],P=I[2],w=I[3],C=new Int32Array(e),D=new Int32Array(C.length),_=this.networkToHostOrderSwap;t<C.length;){for(d=_(C[t]),h=_(C[t+1]),f=_(C[t+2]),v=_(C[t+3]),o=d^y[0],l=v^y[1],u=f^y[2],c=h^y[3],g=4,p=1;p<m;p++)i=S[o>>>24]^T[l>>16&255]^A[u>>8&255]^b[255&c]^y[g],n=S[l>>>24]^T[u>>16&255]^A[c>>8&255]^b[255&o]^y[g+1],a=S[u>>>24]^T[c>>16&255]^A[o>>8&255]^b[255&l]^y[g+2],s=S[c>>>24]^T[o>>16&255]^A[l>>8&255]^b[255&u]^y[g+3],o=i,l=n,u=a,c=s,g+=4;i=k[o>>>24]<<24^k[l>>16&255]<<16^k[u>>8&255]<<8^k[255&c]^y[g],n=k[l>>>24]<<24^k[u>>16&255]<<16^k[c>>8&255]<<8^k[255&o]^y[g+1],a=k[u>>>24]<<24^k[c>>16&255]<<16^k[o>>8&255]<<8^k[255&l]^y[g+2],s=k[c>>>24]<<24^k[o>>16&255]<<16^k[l>>8&255]<<8^k[255&u]^y[g+3],D[t]=_(i^R),D[t+1]=_(s^L),D[t+2]=_(a^P),D[t+3]=_(n^w),R=d,L=h,P=f,w=v,t+=4}return D.buffer}}])}(),Li=function(){return l(function e(t,r,i){s(this,e),this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=t,this.key=r,this.aesMode=i},[{key:"expandKey",value:function(){var e=function(e){switch(e){case Ai:return"AES-CBC";case bi: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 Pi=function(){return l(function e(t,r){if(s(this,e),this.logEnabled=!0,this.decryptRange=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,!0!==r)try{var i=self.crypto;i&&(this.subtle=i.subtle||i.webkitSubtle)}catch(e){}this.useSoftware=!this.subtle},[{key:"destroy",value:function(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}},{key:"isSync",value:function(){return this.useSoftware}},{key:"flush",value:function(){var e=this.currentResult,t=this.remainderData;if(!e||t)return this.reset(),null;var r=new Uint8Array(e);this.reset();var i,n,a,s=this.decryptRange;return s?0===s.start&&s.end>=r.length?r:r.slice(s.start,s.end):(n=(i=r).byteLength,(a=n&&new DataView(i.buffer).getUint8(n-1))?i.slice(0,n-a):i)}},{key:"reset",value:function(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}},{key:"decrypt",value:function(e,t,r,i,n){var a=this;return this.decryptRange=n,this.useSoftware||n?new Promise(function(n,s){var o=ArrayBuffer.isView(e)?e:new Uint8Array(e);a.softwareDecrypt(o,t,r,i);var l=a.flush();l?n(l.buffer):s(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,r,i)}},{key:"softwareDecrypt",value:function(e,t,r,i){var n=this.currentIV,a=this.currentResult,s=this.remainderData;if(i!==Ai||16!==t.byteLength)return je.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),s&&(e=Kt(s,e),this.remainderData=null);var o=this.getValidChunk(e);if(!o.length)return null;n&&(r=n);var l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Ri),l.expandKey(t);var u=a;return this.currentResult=l.decrypt(o.buffer,0,r),this.currentIV=o.slice(-16).buffer,u||null}},{key:"webCryptoDecrypt",value:function(e,t,r,i){var n=this;if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,r,i));this.key=t,this.fastAesKey=new Li(this.subtle,t,i)}return this.fastAesKey.expandKey().then(function(t){return n.subtle?(n.logOnce("WebCrypto AES decrypt"),new Ii(n.subtle,new Uint8Array(r),i).decrypt(e.buffer,t)):Promise.reject(new Error("web crypto not initialized"))}).catch(function(a){return je.warn("[decrypter]: WebCrypto Error, disable WebCrypto API, ".concat(a.name,": ").concat(a.message)),n.onWebCryptoError(e,t,r,i)})}},{key:"onWebCryptoError",value:function(e,t,r,i){var n=this.enableSoftwareAES;if(n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,r,i);var a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(n?" and softwareDecrypt":"")+": failed to decrypt data")}},{key:"getValidChunk",value:function(e){var t=e,r=e.length-e.length%16;return r!==e.length&&(t=e.slice(0,r),this.remainderData=e.slice(r)),t}},{key:"logOnce",value:function(e){this.logEnabled&&(je.log("[decrypter]: ".concat(e)),this.logEnabled=!1)}}])}(),wi=Math.pow(2,17),Ci=function(){return l(function e(t){s(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,r,i){var n=this,a=e.url;if(!a)return Promise.reject(new xi({type:re.NETWORK_ERROR,details:ie.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a ".concat(a?"part list":"url")),networkDetails:null}));this.abort();var s=this.config,o=s.fLoader,l=s.loader;return new Promise(function(u,c){if(n.loader&&n.loader.destroy(),e.gap){if(e.tagList.some(function(e){return"GAP"===e[0]}))return void c(Mi(e));e.gap=!1}var d=n.loader=o?new o(s):new l(s),h=Di(e,null,t);e.loader=d;var f=_e(s.fragLoadPolicy.default),v={loadPolicy:f,timeout:f.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:wi};d.stats.retry=e.stats.retry,e.stats=d.stats;var g={onSuccess:function(t,r,i,a){n.resetLoader(e,d);var s=t.data;i.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(s.slice(0,16)),s=s.slice(16)),u({frag:e,part:null,payload:s,networkDetails:a})},onError:function(t,r,i,s){n.resetLoader(e,d),c(new xi({type:re.NETWORK_ERROR,details:ie.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Ie({url:a,data:void 0},t),error:new Error("HTTP Error ".concat(t.code," ").concat(t.text)),networkDetails:i,stats:s}))},onAbort:function(t,r,i){n.resetLoader(e,d),c(new xi({type:re.NETWORK_ERROR,details:ie.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:i,stats:t}))},onTimeout:function(t,r,i){n.resetLoader(e,d),c(new xi({type:re.NETWORK_ERROR,details:ie.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error("Timeout after ".concat(v.timeout,"ms")),networkDetails:i,stats:t}))}};if(r){var p=n.gateProgress(r,i);g.onProgress=function(t,r,i,n){return p({frag:e,part:null,payload:i,networkDetails:n})}}d.load(h,v,g)})}},{key:"gateProgress",value:function(e,t){var r=e;if(t){var i=[],n=!1;t.then(function(){n=!0,i.forEach(function(t){return e(t)}),i.length=0}).catch(function(){}),r=function(t){n?e(t):i.push(t)}}return r}},{key:"loadPart",value:function(e,t,r){var i=this;this.abort();var n=this.config,a=n.fLoader,s=n.loader;return new Promise(function(o,l){if(i.loader&&i.loader.destroy(),e.gap||t.gap)l(Mi(e,t));else{var u=i.loader=a?new a(n):new s(n),c=Di(e,t);e.loader=u;var d=_e(n.fragLoadPolicy.default),h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:wi};t.stats=u.stats,u.load(c,h,{onSuccess:function(n,a,s,l){i.resetLoader(e,u),i.updateStatsFromPart(e,t);var c={frag:e,part:t,payload:n.data,networkDetails:l};r(c),o(c)},onError:function(r,n,a,s){i.resetLoader(e,u),l(new xi({type:re.NETWORK_ERROR,details:ie.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:Ie({url:c.url,data:void 0},r),error:new Error("HTTP Error ".concat(r.code," ").concat(r.text)),networkDetails:a,stats:s}))},onAbort:function(r,n,a){e.stats.aborted=t.stats.aborted,i.resetLoader(e,u),l(new xi({type:re.NETWORK_ERROR,details:ie.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:a,stats:r}))},onTimeout:function(r,n,a){i.resetLoader(e,u),l(new xi({type:re.NETWORK_ERROR,details:ie.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error("Timeout after ".concat(h.timeout,"ms")),networkDetails:a,stats:r}))}})}})}},{key:"updateStatsFromPart",value:function(e,t){var r=e.stats,i=t.stats,n=i.total;if(r.loaded+=i.loaded,n){var a=Math.round(e.duration/t.duration),s=Math.min(Math.round(r.loaded/n),a),o=(a-s)*Math.round(r.loaded/s);r.total=r.loaded+o}else r.total=Math.max(r.loaded,r.total);var l=r.loading,u=i.loading;l.start?l.first+=u.first-u.start:(l.start=u.start,l.first=u.first),l.end=u.end}},{key:"resetLoader",value:function(e,t){e.loader=null,e.url=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}])}();function Di(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,r=arguments.length>2?arguments[2]:void 0,i=t||e,n={type:ce.MEDIA_FRAGMENT,frag:e,part:t,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},a=_i(e,t,r);return a.resetIV&&(n.resetIV=!0),a.byteRange&&(n.rangeStart=a.byteRange.start,n.rangeEnd=a.byteRange.end),n}function _i(e){var t,r,i=arguments.length>2?arguments[2]:void 0,n={},a=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:null)||e,s=a.byteRangeStartOffset,o=a.byteRangeEndOffset;if(Z(s)&&Z(o))if("initSegment"!==e.sn&&!i||"AES-128"!==(r=null==(t=e.decryptdata)?void 0:t.method)&&"AES-256"!==r)n.byteRange={start:s,end:o};else{var l=16*Math.floor(s/16),u=16*Math.ceil(o/16);n.decryptRange={start:s-l,end:o-l},l>=16&&(n.resetIV=!0,l-=16),n.byteRange={start:l,end:u}}return n}function Mi(e,t){var r=new Error("GAP ".concat(e.gap?"tag":"attribute"," found")),i={type:re.MEDIA_ERROR,details:ie.FRAG_GAP,fatal:!1,frag:e,error:r,networkDetails:null};return t&&(i.part=t),(t||e).stats.aborted=!0,new xi(i)}var xi=function(e){function t(e){var r;return s(this,t),(r=a(this,t,[e.error.message])).data=void 0,r.data=e,r}return f(t,e),l(t)}(w(Error)),Oi=function(e){function t(e,r){var i;return s(this,t),(i=a(this,t,[e,r]))._boundTick=void 0,i._tickTimer=null,i._tickInterval=null,i._tickCallCount=0,i._boundTick=i.tick.bind(i),i}return f(t,e),l(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):(this.log("possible exception thrown in task-loop (".concat(this.constructor.name,".doTick)")),this._tickCallCount=0)}},{key:"tickImmediate",value:function(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}},{key:"doTick",value:function(){}}])}(Be),Fi=l(function e(t,r,i){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:-1,o=arguments.length>5&&void 0!==arguments[5]&&arguments[5],l=arguments.length>6?arguments[6]:void 0,u=arguments.length>7?arguments[7]:void 0,c=arguments.length>8?arguments[8]:void 0;s(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.iframe=void 0,this.duration=void 0,this.decryptRange=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=t,this.sn=r,this.id=i,this.size=n,this.part=a,this.partial=o,this.duration=l||0,this.decryptRange=c,this.iframe=u||!1});var Ni={length:0,start:function(){return 0},end:function(){return 0}},Bi=function(){function e(){s(this,e)}return l(e,null,[{key:"isBuffered",value:function(t,r){if(t)for(var i=e.getBuffered(t),n=i.length;n--;)if(r>=i.start(n)&&r<=i.end(n))return!0;return!1}},{key:"bufferedRanges",value:function(t){if(t){var r=e.getBuffered(t);return e.timeRangesToArray(r)}return[]}},{key:"timeRangesToArray",value:function(e){for(var t=[],r=0;r<e.length;r++)t.push({start:e.start(r),end:e.end(r)});return t}},{key:"bufferInfo",value:function(t,r,i){if(t){var n=e.bufferedRanges(t);if(n.length)return e.bufferedInfo(n,r,i)}return{len:0,start:r,end:r,bufferedIndex:-1}}},{key:"bufferedInfo",value:function(e,t,r){t=Math.max(0,t),e.length>1&&e.sort(function(e,t){return e.start-t.start||t.end-e.end});var i=-1,n=[];if(r)for(var a=0;a<e.length;a++){t>=e[a].start&&t<=e[a].end&&(i=a);var s=n.length;if(s){var o=n[s-1].end;e[a].start-o<r?e[a].end>o&&(n[s-1].end=e[a].end):n.push(e[a])}else n.push(e[a])}else n=e;for(var l,u=0,c=t,d=t,h=0;h<n.length;h++){var f=n[h].start,v=n[h].end;if(-1===i&&t>=f&&t<=v&&(i=h),t+r>=f&&t<v)c=f,u=(d=v)-t;else if(t+r<f){l=f;break}}return{len:u,start:c||0,end:d||0,nextStart:l,buffered:e,bufferedIndex:i}}},{key:"getBuffered",value:function(e){try{return e.buffered||Ni}catch(e){return je.log("failed to get media.buffered",e),Ni}}}])}(),Ui=/\{\$([a-zA-Z0-9-_]+)\}/g;function Vi(e){return Ui.lastIndex=0,Ui.test(e)}function Gi(e,t){if(null!==e.variableList||e.hasVariableRefs){var r=e.variableList;return t.replace(Ui,function(t){var i=t.substring(2,t.length-1),n=null==r?void 0:r[i];return void 0===n?(e.playlistParsingError||(e.playlistParsingError=new Error('Missing preceding EXT-X-DEFINE tag for Variable Reference: "'.concat(i,'"'))),t):n})}return t}function Hi(e,t,r){var i,n,a=e.variableList;if(a||(e.variableList=a={}),"QUERYPARAM"in t){i=t.QUERYPARAM;try{var s=new self.URL(r).searchParams;if(!s.has(i))throw new Error('"'.concat(i,'" does not match any query parameter in URI: "').concat(r,'"'));n=s.get(i)}catch(t){e.playlistParsingError||(e.playlistParsingError=new Error("EXT-X-DEFINE QUERYPARAM: ".concat(t.message)))}}else i=t.NAME,n=t.VALUE;i in a?e.playlistParsingError||(e.playlistParsingError=new Error('EXT-X-DEFINE duplicate Variable Name declarations: "'.concat(i,'"'))):a[i]=n||""}function Ki(e,t,r){var i=t.IMPORT;if(r&&i in r){var n=e.variableList;n||(e.variableList=n={}),n[i]=r[i]}else e.playlistParsingError||(e.playlistParsingError=new Error('EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "'.concat(i,'"')))}var ji=/^(\d+)x(\d+)$/,qi=/(.+?)=(".*?"|.*?)(?:,|$)/g,Wi=function(){return l(function e(t,r){s(this,e),"string"==typeof t&&(t=e.parseAttrList(t,r)),Ae(this,t)},[{key:"clientAttrs",get:function(){return Object.keys(this).filter(function(e){return"X-"===e.substring(0,2)})}},{key:"decimalInteger",value:function(e){var t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}},{key:"hexadecimalInteger",value:function(e){if(this[e]){var t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;for(var r=new Uint8Array(t.length/2),i=0;i<t.length/2;i++)r[i]=parseInt(t.slice(2*i,2*i+2),16);return r}return null}},{key:"hexadecimalIntegerAsNumber",value:function(e){var t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}},{key:"decimalFloatingPoint",value:function(e){return parseFloat(this[e])}},{key:"optionalFloat",value:function(e,t){var r=this[e];return r?parseFloat(r):t}},{key:"enumeratedString",value:function(e){return this[e]}},{key:"enumeratedStringList",value:function(e,t){var r=this[e];return(r?r.split(/[ ,]+/):[]).reduce(function(e,t){return e[t.toLowerCase()]=!0,e},t)}},{key:"bool",value:function(e){return"YES"===this[e]}},{key:"decimalResolution",value:function(e){var t=ji.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}}],[{key:"parseAttrList",value:function(e,t){var r,i={};for(qi.lastIndex=0;null!==(r=qi.exec(e));){var n=r[1].trim(),a=r[2],s=0===a.indexOf('"')&&a.lastIndexOf('"')===a.length-1,o=!1;if(s)a=a.slice(1,-1);else switch(n){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(t&&(s||o))a=Gi(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":je.warn("".concat(e,": attribute ").concat(n," is missing quotes"))}i[n]=a}return i}}])}();function Yi(e){return"ID"!==e&&"CLASS"!==e&&"CUE"!==e&&"START-DATE"!==e&&"DURATION"!==e&&"END-DATE"!==e&&"END-ON-NEXT"!==e}function zi(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e||"SCTE35-CMD"===e}var Xi=function(){return l(function e(t,r){var i,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;if(s(this,e),this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==r?void 0:r.tagAnchor)||null,this.tagOrder=null!=(i=null==r?void 0:r.tagOrder)?i:n,r){var a=r.attr;for(var o in a)if(Object.prototype.hasOwnProperty.call(t,o)&&t[o]!==a[o]){je.warn('DATERANGE tag attribute: "'.concat(o,'" does not match for tags with ID: "').concat(t.ID,'"')),this._badValueForSameId=o;break}t=Ae(new Wi({}),a,t)}if(this.attr=t,r?(this._startDate=r._startDate,this._cue=r._cue,this._endDate=r._endDate,this._dateAtEnd=r._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in t){var l=(null==r?void 0:r.endDate)||new Date(t["END-DATE"]);Z(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?(je.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(Z(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&&Z(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)}},{key:"invalidReason",get:function(){return this.id?this._badValueForSameId?"Date range ".concat(this._badValueForSameId," mismatch"):Z(this.startDate.getTime())?!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr?this.isValid?null:"Unknown (check DURATION(|END|NEXT), CLASS, and CUE)":"Interstitial Date range missing X-ASSET-(LIST|URI)":"Date range invalid start date":"Missing ID"}}])}(),Qi=function(){return l(function e(t){s(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.iframesOnly=!1,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=t},[{key:"reloaded",value:function(e){if(!e)return this.advanced=!0,void(this.updated=!0);var t=this.lastPartSn-e.lastPartSn,r=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!r||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&r>0,this.updated||this.advanced?this.misses=0:this.misses=e.misses+1}},{key:"hasKey",value:function(e){return this.encryptedFragments.some(function(t){var r=t.decryptdata;return r||(t.setKeyFormat(e.keyFormat),r=t.decryptdata),!!r&&e.matches(r)})}},{key:"hasProgramDateTime",get:function(){return!!this.fragments.length&&Z(this.fragments[this.fragments.length-1].programDateTime)}},{key:"levelTargetDuration",get:function(){return this.averagetargetduration||this.targetduration||10}},{key:"drift",get:function(){var e=this.driftEndTime-this.driftStartTime;return e>0?1e3*(this.driftEnd-this.driftStart)/e:1}},{key:"edge",get:function(){return this.partEnd||this.fragmentEnd}},{key:"partEnd",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}},{key:"fragmentEnd",get:function(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}},{key:"fragmentStart",get:function(){return this.fragments.length?this.fragments[0].start:0}},{key:"age",get:function(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}},{key:"lastPartIndex",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}},{key:"maxPartIndex",get:function(){var e=this.partList;if(e){var t=this.lastPartIndex;if(-1!==t){for(var r=e.length;r--;)if(e[r].index>t)return e[r].index;return t}}return 0}},{key:"lastPartSn",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}},{key:"expired",get:function(){if(this.live&&this.age&&this.misses<3){var e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}])}();function $i(e,t){return e.length===t.length&&!e.some(function(e,r){return e!==t[r]})}function Ji(e,t){return!e&&!t||!(!e||!t)&&$i(e,t)}function Zi(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function en(e){switch(e){case"AES-128":case"AES-256":return Ai;case"AES-256-CTR":return bi;default:throw new Error("invalid full segment method ".concat(e))}}function tn(e){return Uint8Array.from(unescape(encodeURIComponent(e)),function(e){return e.charCodeAt(0)})}function rn(e){var t=function(e,t,r){var i=e[t];e[t]=e[r],e[r]=i};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function nn(e){var t,r,i=e.split(":"),n=null;if("data"===i[0]&&2===i.length){var a=i[1].split(";"),s=a[a.length-1].split(",");if(2===s.length){var o="base64"===s[0],l=s[1];o?(a.splice(-1,1),n=gt(l)):(t=tn(l).subarray(0,16),(r=new Uint8Array(16)).set(t,16-t.length),n=r)}}return n}var an="undefined"!=typeof self?self:void 0,sn={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},on="org.w3.clearkey",ln="com.apple.streamingkeydelivery",un="com.microsoft.playready",cn="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function dn(e){switch(e){case ln:return sn.FAIRPLAY;case un:return sn.PLAYREADY;case cn:return sn.WIDEVINE;case on:return sn.CLEARKEY}}var hn="edef8ba979d64acea3c827dcd51d21ed";function fn(e){switch(e){case sn.FAIRPLAY:return ln;case sn.PLAYREADY:return un;case sn.WIDEVINE:return cn;case sn.CLEARKEY:return on}}function vn(e){var t=e.drmSystems,r=e.widevineLicenseUrl,i=t?[sn.FAIRPLAY,sn.WIDEVINE,sn.PLAYREADY,sn.CLEARKEY].filter(function(e){return!!t[e]}):[];return!i[sn.WIDEVINE]&&r&&i.push(sn.WIDEVINE),i}var gn,pn=null!=an&&null!=(gn=an.navigator)&&gn.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function mn(e){var t=pt(new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2)),r=t.substring(t.indexOf("<"),t.length),i=(new DOMParser).parseFromString(r,"text/xml").getElementsByTagName("KID")[0];if(i){var n=i.childNodes[0]?i.childNodes[0].nodeValue:i.getAttribute("VALUE");if(n){var a=gt(n).subarray(0,16);return rn(a),a}}return null}var yn={},kn=function(){function e(t,r,i){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[1],a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null,o=arguments.length>5?arguments[5]:void 0;s(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.scheme=void 0,this.method=t,this.uri=r,this.keyFormat=i,this.keyFormatVersions=n,this.iv=a,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&!Zi(t),null!=o&&o.startsWith("0x")&&(this.keyId=new Uint8Array(vt(o)))}return l(e,[{key:"matches",value:function(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&$i(e.keyFormatVersions,this.keyFormatVersions)&&Ji(e.iv,this.iv)&&Ji(e.keyId,this.keyId)}},{key:"isSupported",value:function(){if(this.method){if(Zi(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case ln:case cn:case un:case on:return-1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}},{key:"getDecryptData",value:function(t,r){var i;if(!this.encrypted||!this.uri)return null;if(Zi(this.method)){var n=this.iv;return n||("number"!=typeof t&&(je.warn('missing IV for initialization segment with method="'.concat(this.method,'" - compliance issue')),t=0),n=function(e){for(var t=new Uint8Array(16),r=12;r<16;r++)t[r]=e>>8*(15-r)&255;return t}(t)),new e(this.method,this.uri,"identity",this.keyFormatVersions,n)}if(this.keyId){var a=yn[this.uri];if(a&&!$i(this.keyId,a)&&e.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}var s,o=nn(this.uri);if(o)switch(this.keyFormat){case cn:if(this.pssh=o,!this.keyId){var l=Xt(o.buffer).filter(function(e){return e.systemId===hn});if(l.length){var u,c=l[0];this.keyId=null!=(u=c.kids)&&u.length?c.kids[0]:null}}this.keyId||(this.keyId=En(r));break;case un:var d=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=zt(d,0,o),this.keyId=mn(o);break;default:var h=o.subarray(0,16);if(16!==h.length){var f=new Uint8Array(16);f.set(h,16-h.length),h=f}this.keyId=h}16!==(null==(i=this.keyId)?void 0:i.byteLength)&&(s=function(e){var t=null==e?void 0:e[cn];if(t)return t.keyId;return null}(r),s||(s=En(r))||(s=yn[this.uri]),s&&(this.keyId=s,e.setKeyIdForUri(this.uri,s)));return this}}],[{key:"clearKeyUriToKeyIdMap",value:function(){yn={}}},{key:"setKeyIdForUri",value:function(e,t){yn[e]=t}},{key:"addKeyIdForUri",value:function(e){var t=Object.keys(yn).length%Number.MAX_SAFE_INTEGER,r=new Uint8Array(16);return new DataView(r.buffer,12,4).setUint32(0,t),yn[e]=r,r}}])}();function En(e){var t=null==e?void 0:e[un];if(t){var r=nn(t.uri);if(r)return mn(r)}return null}var Sn=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(I-FRAME-STREAM-INF|SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)(?:[\r\n]+|$)/g,Tn=/#EXT-X-MEDIA:(.*)/g,An=/^#EXT(?:INF|-X-TARGETDURATION):/m,bn=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),In=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|I-FRAMES-ONLY)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|")),Rn=function(){function e(){s(this,e)}return l(e,null,[{key:"findGroup",value:function(e,t){for(var r=0;r<e.length;r++){var i=e[r];if(i.id===t)return i}}},{key:"resolve",value:function(e,t){return le.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}},{key:"isMediaPlaylist",value:function(e){return An.test(e)}},{key:"parseMasterPlaylist",value:function(t,r){var i,n={contentSteering:null,levels:[],iframeVariants:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:Vi(t)},a=[];if(Sn.lastIndex=0,!t.startsWith("#EXTM3U"))return n.playlistParsingError=new Error("no EXTM3U delimiter"),n;for(;null!=(i=Sn.exec(t));)if(i[1]){var s=Ln(new Wi(i[1],n),i[2],r,n,a);s&&n.levels.push(s)}else if(i[3]){var o=i[3],l=i[4];switch(o){case"I-FRAME-STREAM-INF":var u=new Wi(l,n),c=Ln(u,u.URI,r,n,a,!0);c&&n.iframeVariants.push(c);break;case"SESSION-DATA":var d=new Wi(l,n),h=d["DATA-ID"];h&&(null===n.sessionData&&(n.sessionData={}),n.sessionData[h]=d);break;case"SESSION-KEY":var f=Cn(l,r,n);f.encrypted&&f.isSupported()?(null===n.sessionKeys&&(n.sessionKeys=[]),n.sessionKeys.push(f)):je.warn('[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "'.concat(l,'"'));break;case"DEFINE":Hi(n,new Wi(l,n),r);break;case"CONTENT-STEERING":var v=new Wi(l,n);n.contentSteering={uri:e.resolve(v["SERVER-URI"],r),pathwayId:v["PATHWAY-ID"]||"."};break;case"START":n.startTimeOffset=Dn(l)}}var g=a.length>0&&a.length<n.levels.length;return n.levels=g?a:n.levels,0===n.levels.length&&(n.playlistParsingError=new Error("no levels found in manifest")),n}},{key:"parseMasterPlaylistMedia",value:function(t,r,i){var n,a={},s=i.levels,o={AUDIO:s.map(function(e){return{id:e.attrs.AUDIO,audioCodec:e.audioCodec}}),SUBTITLES:s.map(function(e){return{id:e.attrs.SUBTITLES,textCodec:e.textCodec}}),"CLOSED-CAPTIONS":[]},l=0;for(Tn.lastIndex=0;null!==(n=Tn.exec(t));){var u=new Wi(n[1],i),c=u.TYPE;if(c){var d=o[c],h=a[c]||[];a[c]=h;var f=u.LANGUAGE,v=u["ASSOC-LANGUAGE"],g=u.CHANNELS,p=u.CHARACTERISTICS,m=u["INSTREAM-ID"],y={attrs:u,bitrate:0,id:l++,groupId:u["GROUP-ID"]||"",name:u.NAME||f||"",type:c,default:u.bool("DEFAULT"),autoselect:u.bool("AUTOSELECT"),forced:u.bool("FORCED"),lang:f,url:u.URI?e.resolve(u.URI,r):""};if(v&&(y.assocLang=v),g&&(y.channels=g),p&&(y.characteristics=p),m&&(y.instreamId=m),null!=d&&d.length){var k=e.findGroup(d,y.groupId)||d[0];Mn(y,k,"audioCodec"),Mn(y,k,"textCodec")}h.push(y)}}return a}},{key:"parseLevelPlaylist",value:function(e,t,r,i,n,a){var s,o,l,u,c,d={url:t},h=new Qi(t),f=h.fragments,v=[],g=null,p=0,m=0,y=0,k=0,E=0,S=null,T=new ke(i,d),A=-1,b=!1,I=null;if(bn.lastIndex=0,h.m3u8=e,h.hasVariableRefs=Vi(e),"#EXTM3U"!==(null==(s=bn.exec(e))?void 0:s[0]))return h.playlistParsingError=new Error("Missing format identifier #EXTM3U"),h;for(;null!==(o=bn.exec(e));){b&&(b=!1,(T=new ke(i,d)).playlistOffset=y,T.setStart(y),T.sn=p,T.cc=k,E&&(T.bitrate=E),T.level=r,g&&(T.initSegment=g,g.rawProgramDateTime&&(T.rawProgramDateTime=g.rawProgramDateTime,g.rawProgramDateTime=null),I&&(T.setByteRange(I),I=null)));var R=o[1];if(R){T.duration=parseFloat(R);var L=(" "+o[2]).slice(1);T.title=L||null,T.tagList.push(L?["INF",R,L]:["INF",R])}else if(o[3]){if(Z(T.duration)){var P;T.playlistOffset=y,T.setStart(y),u&&Fn(T,u,h),T.sn=p,T.level=r,T.cc=k;var w=(" "+o[3]).slice(1);T.relurl=Gi(h,w),xn(T,S,v),S=T,y+=T.duration,p++,m=0;var C=T.byteRange;if(2===C.length&&(T.bitrate=8*(C[1]-C[0])/T.duration|0),h.iframesOnly&&C[0]&&(null==(P=g)?void 0:P.cc)!==k){var D=new ke(i,d);D.relurl=T.relurl,D.setByteRange("".concat(Math.min(C[0],1316),"@0")),D.level=r,D.sn="initSegment",u&&(D.levelkeys=u,u.identity&&(D._decryptdata=u.identity.getDecryptData(0))),g=D,T.initSegment=g}f.push(T),b=!0}}else{if(!(o=o[0].match(In))){je.warn("No matches on slow regex match for level playlist!");continue}for(l=1;l<o.length&&void 0===o[l];l++);var _=(" "+o[l]).slice(1),M=(" "+o[l+1]).slice(1),x=o[l+2]?(" "+o[l+2]).slice(1):null;switch(_){case"BYTERANGE":S?T.setByteRange(M,S):T.setByteRange(M);break;case"PROGRAM-DATE-TIME":T.rawProgramDateTime=M,T.tagList.push(["PROGRAM-DATE-TIME",M]),-1===A&&(A=f.length);break;case"PLAYLIST-TYPE":h.type&&Nn(h,_,o),h.type=M.toUpperCase();break;case"MEDIA-SEQUENCE":0!==h.startSN?Nn(h,_,o):null!==S&&Bn(h,_,o),h.startSN=parseInt(M),p=h.startSN+h.skippedSegments;break;case"SKIP":h.skippedSegments&&Nn(h,_,o);var O=new Wi(M,h),F=O.decimalInteger("SKIPPED-SEGMENTS");if(Z(F)){h.skippedSegments+=F;for(var N=F;N--;)f.push(null);p+=F}var B=O.enumeratedString("RECENTLY-REMOVED-DATERANGES");B&&(h.recentlyRemovedDateranges=(h.recentlyRemovedDateranges||[]).concat(B.split("\t")));break;case"TARGETDURATION":0!==h.targetduration&&Nn(h,_,o),h.targetduration=Math.max(parseInt(M),1);break;case"VERSION":null!==h.version&&Nn(h,_,o),h.version=parseInt(M);break;case"INDEPENDENT-SEGMENTS":break;case"I-FRAMES-ONLY":h.iframesOnly=!0;break;case"ENDLIST":h.live||Nn(h,_,o),h.live=!1;break;case"#":(M||x)&&T.tagList.push(x?[M,x]:[M]);break;case"DISCONTINUITY":k++,T.tagList.push(["DIS"]);break;case"GAP":T.gap=!0,T.tagList.push([_]);break;case"BITRATE":T.tagList.push([_,M]),E=1e3*parseInt(M),Z(E)?T.bitrate=E:E=0;break;case"DATERANGE":var U=new Wi(M,h),V=new Xi(U,h.dateRanges[U.ID],h.dateRangeTagCount);h.dateRangeTagCount++,V.isValid||h.skippedSegments?h.dateRanges[V.id]=V:je.log("Ignoring invalid DATERANGE tag: ".concat(V.invalidReason,": ").concat(M)),T.tagList.push(["EXT-X-DATERANGE",M]);break;case"DEFINE":var G=new Wi(M,h);"IMPORT"in G?Ki(h,G,a):Hi(h,G,t);break;case"DISCONTINUITY-SEQUENCE":0!==h.startCC&&Nn(h,_,o),h.startCC=k=parseInt(M),f.forEach(function(e){return e&&(e.cc=k)});break;case"KEY":var H=Cn(M,t,h);if(H.isSupported()){if("NONE"===H.method){u=void 0;break}u||(u={});var K=u[H.keyFormat];null!=K&&K.matches(H)||(K&&(u=Ae({},u)),u[H.keyFormat]=H)}else je.warn('[Keys] Ignoring unsupported EXT-X-KEY tag: "'.concat(M,'"'));break;case"START":h.startTimeOffset=Dn(M);break;case"MAP":var j=new Wi(M,h);if(T.duration){var q=new ke(i,d);On(q,j,r,u),g=q,T.initSegment=g,g.rawProgramDateTime&&!T.rawProgramDateTime&&(T.rawProgramDateTime=g.rawProgramDateTime)}else{var W=T.byteRangeEndOffset;if(W){var Y=T.byteRangeStartOffset;I="".concat(W-Y,"@").concat(Y)}else I=null;On(T,j,r,u),g=T,b=!0}g.cc=k;break;case"SERVER-CONTROL":c&&Nn(h,_,o),c=new Wi(M),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&&Nn(h,_,o);var z=new Wi(M);h.partTarget=z.decimalFloatingPoint("PART-TARGET");break;case"PART":var X=h.partList;X||(X=h.partList=[]);var Q=m>0?X[X.length-1]:void 0,$=m++,J=new Wi(M,h),ee=new Ee(J,T,d,$,Q);X.push(ee),T.duration+=ee.duration;break;case"PRELOAD-HINT":var te=new Wi(M,h);h.preloadHint=te;break;case"RENDITION-REPORT":var re=new Wi(M,h);h.renditionReports=h.renditionReports||[],h.renditionReports.push(re);break;default:je.warn("line parsed but not handled: ".concat(o))}}}S&&!S.relurl?(f.pop(),y-=S.duration,h.partList&&(h.fragmentHint=S)):h.partList&&(xn(T,S,v),T.cc=k,h.fragmentHint=T,u&&Fn(T,u,h)),h.targetduration||(h.playlistParsingError=new Error("Missing Target Duration"));var ie=f.length,ne=f[0],ae=f[ie-1];if((y+=h.skippedSegments*h.targetduration)>0&&ie&&ae){h.averagetargetduration=y/ie;var se=ae.sn;h.endSN="initSegment"!==se?se:0,h.live||(ae.endList=!0),A>0&&(!function(e,t,r){if(r||(r=e[t]),!r)return;for(var i=t;i--;){var n=e[i];if(!n)return;n.programDateTime=r.programDateTime-1e3*n.duration,r=n}}(f,A,A>ie-1?T:null),ne&&v.unshift(ne))}return h.fragmentHint&&(y+=h.fragmentHint.duration),h.totalduration=y,v.length&&h.dateRangeTagCount&&ne&&Pn(v,h),h.endCC=k,h}}])}();function Ln(e,t,r,i,n,a){var s;if(void 0===t)return null;var o=Gi(i,t),l={attrs:e,bitrate:e.decimalInteger("BANDWIDTH")||e.decimalInteger("AVERAGE-BANDWIDTH"),name:e.NAME,url:Rn.resolve(o,r)},u=e.decimalResolution("RESOLUTION");u&&(l.width=u.width,l.height=u.height),_n(e.CODECS,l);var c=e["SUPPLEMENTAL-CODECS"];return c&&(l.supplemental={},_n(c,l.supplemental)),null!=(s=l.unknownCodecs)&&s.length||n.push(l),a&&(l.iframes=!0),l}function Pn(e,t){var r=e.length;if(!r){if(!t.hasProgramDateTime)return;var i=t.fragments[t.fragments.length-1];e.push(i),r++}for(var n=e[r-1],a=t.live?1/0:t.totalduration,s=Object.keys(t.dateRanges),o=s.length;o--;){var l=t.dateRanges[s[o]],u=l.startDate.getTime();l.tagAnchor=n.ref;for(var c=r;c--;){var d;if((null==(d=e[c])?void 0:d.sn)<t.startSN)break;var h=wn(t,u,e,c,a);if(h){l.tagAnchor=h.ref;break}}}}function wn(e,t,r,i,n){var a=r[i];if(a){var s,o=a.programDateTime;if(t>=o||0===i)if(t<=o+1e3*(((null==(s=r[i+1])?void 0:s.start)||n)-a.start)){var l=a.sn-e.startSN,u=e.fragments;if(l>=0&&l<u.length){if(u.length>r.length)for(var c=r[i+1]||u[u.length-1],d=Math.min(c.sn-e.startSN,u.length-1);d>l;d--){var h=u[d].programDateTime;if(t>=h&&t<h+1e3*u[d].duration)return u[d]}return u[l]}}}return null}function Cn(e,t,r){var i,n,a=new Wi(e,r),s=null!=(i=a.METHOD)?i:"",o=a.URI,l=a.hexadecimalInteger("IV"),u=a.KEYFORMATVERSIONS,c=null!=(n=a.KEYFORMAT)?n:"identity";o&&a.IV&&!l&&je.error("Invalid IV: ".concat(a.IV));var d=o?Rn.resolve(o,t):"",h=(u||"1").split("/").map(Number).filter(Number.isFinite);return new kn(s,d,c,h,l,a.KEYID)}function Dn(e){var t=new Wi(e).decimalFloatingPoint("TIME-OFFSET");return Z(t)?t:null}function _n(e,t){var r=(e||"").split(/[ ,]+/).filter(function(e){return e});["video","audio","text","image"].forEach(function(e){var i=r.filter(function(t){return sr(t,e)});i.length&&(t["".concat(e,"Codec")]=i.map(function(e){return e.split("/")[0]}).join(","),r=r.filter(function(e){return-1===i.indexOf(e)}))}),t.unknownCodecs=r}function Mn(e,t,r){var i=t[r];i&&(e[r]=i)}function xn(e,t,r){e.rawProgramDateTime?r.push(e):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function On(e,t,r,i){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=r,e.sn="initSegment",i&&(e.levelkeys=i),e.initSegment=null}function Fn(e,t,r){e.levelkeys=t;var i=r.encryptedFragments;i.length&&i[i.length-1].levelkeys===t||!Object.keys(t).some(function(e){return t[e].isCommonEncryption})||i.push(e)}function Nn(e,t,r){e.playlistParsingError=new Error("#EXT-X-".concat(t," must not appear more than once (").concat(r[0],")"))}function Bn(e,t,r){e.playlistParsingError=new Error("#EXT-X-".concat(t," must appear before the first Media Segment (").concat(r[0],")"))}function Un(e,t){var r=t.startPTS;if(Z(r)){var i,n=0;t.sn>e.sn?(n=r-e.start,i=e):(n=e.start-r,i=t),i.duration!==n&&i.setDuration(n)}else if(t.sn>e.sn){e.cc===t.cc&&e.minEndPTS?t.setStart(e.start+(e.minEndPTS-e.start)):t.setStart(e.start+e.duration)}else t.setStart(Math.max(e.start-t.duration,0))}function Vn(e,t,r,i,n,a,s,o){i-r<=0&&(o.warn("Fragment should have a positive duration",t),i=r+t.duration,a=n+t.duration);var l=r,u=i,c=t.startPTS,d=t.endPTS;if(Z(c)){var h=Math.abs(c-r);e&&h>e.totalduration?o.warn("media timestamps and playlist times differ by ".concat(h,"s for level ").concat(t.level," ").concat(e.url)):Z(t.deltaPTS)?t.deltaPTS=Math.max(h,t.deltaPTS):t.deltaPTS=h,l=Math.max(r,c),r=Math.min(r,c),n=void 0!==t.startDTS?Math.min(n,t.startDTS):n,u=Math.min(i,d),i=Math.max(i,d),a=void 0!==t.endDTS?Math.max(a,t.endDTS):a}var f=r-t.start;0!==t.start&&t.setStart(r),t.setDuration(i-t.start),t.startPTS=r,t.maxStartPTS=l,t.startDTS=n,t.endPTS=i,t.minEndPTS=u,t.endDTS=a;var v,g=t.sn;if(!e||g<e.startSN||g>e.endSN)return 0;var p=g-e.startSN,m=e.fragments;for(m[p]=t,v=p;v>0;v--)Un(m[v],m[v-1]);for(v=p;v<m.length-1;v++)Un(m[v],m[v+1]);return e.fragmentHint&&Un(m[m.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,f}function Gn(e,t,r){if(e!==t){for(var i,n=null,a=e.fragments,s=a.length-1;s>=0;s--){var o=a[s].initSegment;if(o){n=o;break}}e.fragmentHint&&delete e.fragmentHint.endPTS,function(e,t,r){for(var i,n=t.skippedSegments,a=Math.max(e.startSN,t.startSN)-t.startSN,s=(e.fragmentHint?1:0)+(n?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,o=t.startSN-e.startSN,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,u=null!=(i=e.fragmentHint)&&i.duration?e.fragments.concat(e.fragmentHint):e.fragments,c=a;c<=s;c++){var d=u[o+c],h=l[c];if(n&&!h&&d&&(h=t.fragments[c]=d),d&&h){r(d,h,c,l);var f=d.relurl,v=h.relurl;if(f&&Xn(f,v))return void(t.playlistParsingError=Hn("media sequence mismatch ".concat(h.sn,":"),e,t,d,h));if(d.cc!==h.cc)return void(t.playlistParsingError=Hn("discontinuity sequence mismatch (".concat(d.cc,"!=").concat(h.cc,")"),e,t,d,h))}}}(e,t,function(e,r,a,s){if((!t.startCC||t.skippedSegments)&&r.cc!==e.cc){for(var o=e.cc-r.cc,l=a;l<s.length;l++)s[l].cc+=o;t.endCC=s[s.length-1].cc}Z(e.startPTS)&&Z(e.endPTS)&&(r.setStart(r.startPTS=e.startPTS),r.startDTS=e.startDTS,r.maxStartPTS=e.maxStartPTS,r.endPTS=e.endPTS,r.endDTS=e.endDTS,r.minEndPTS=e.minEndPTS,r.setDuration(e.endPTS-e.startPTS),r.duration&&(i=r),t.PTSKnown=t.alignedSliding=!0),e.hasStreams&&(r.elementaryStreams=e.elementaryStreams),r.loader=e.loader,e.hasStats&&(r.stats=e.stats),e.initSegment&&(r.initSegment=e.initSegment,n=e.initSegment)});var l=t.fragments,u=t.fragmentHint?l.concat(t.fragmentHint):l;if(n&&u.forEach(function(e){var t;!e||e.initSegment&&e.initSegment.relurl!==(null==(t=n)?void 0:t.relurl)||(e.initSegment=n)}),t.skippedSegments){if(t.deltaUpdateFailed=l.some(function(e){return!e}),t.deltaUpdateFailed){r.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(var c=t.skippedSegments;c--;)l.shift();t.startSN=l[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=function(e,t,r){var i=t.dateRanges,n=t.recentlyRemovedDateranges,a=Ae({},e);n&&n.forEach(function(e){delete a[e]});var s=Object.keys(a).length;if(!s)return i;return Object.keys(i).forEach(function(e){var t=a[e],n=new Xi(i[e].attr,t);n.isValid?(a[e]=n,t||(n.tagOrder+=s)):r.warn('Ignoring invalid Playlist Delta Update DATERANGE tag: "'.concat(Nr(i[e].attr),'"'))}),a}(e.dateRanges,t,r));var d=e.fragments.filter(function(e){return e.rawProgramDateTime});if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(var h=1;h<u.length;h++)null===u[h].programDateTime&&xn(u[h],u[h-1],d);Pn(d,t)}t.endCC=l[l.length-1].cc}if(!t.startCC){var f,v=qn(e,t.startSN-1);t.startCC=null!=(f=null==v?void 0:v.cc)?f:l[0].cc}if(function(e,t,r){if(e&&t)for(var i=0,n=0,a=e.length;n<a;n++){var s=e[n],o=t[n+i];s&&o&&s.index===o.index&&s.fragment.sn===o.fragment.sn?r(s,o):i--}}(e.partList,t.partList,function(e,t){t.elementaryStreams=e.elementaryStreams,t.stats=e.stats,t.gap=e.gap||t.gap}),i){t.iframesOnly&&(i.type,de.MAIN);Vn(t,i,i.startPTS,i.endPTS,i.startDTS,i.endDTS,0,r)}else Kn(e,t);l.length&&(t.totalduration=t.edge-l[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;var g=t.advancedDateTime;if(t.advanced&&g){var p=t.edge;t.driftStart||(t.driftStartTime=g,t.driftStart=p),t.driftEndTime=g,t.driftEnd=p}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;-1===t.requestScheduled&&(t.requestScheduled=e.requestScheduled)}}function Hn(e,t,r,i,n){return new Error("".concat(e," ").concat(n.url,"\nPlaylist starting @").concat(t.startSN,"\n").concat(t.m3u8,"\n\nPlaylist starting @").concat(r.startSN,"\n").concat(r.m3u8))}function Kn(e,t){var r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],i=arguments.length>3?arguments[3]:void 0,n=t.startSN+t.skippedSegments-e.startSN,a=e.fragments,s=n>=0,o=0;if(s&&n<a.length)o=a[n].start,null==i||i.log("Aligning playlists based on SN ".concat(t.startSN," (diff: ").concat(o,")"));else if(s&&t.startSN===e.endSN+1)o=e.fragmentEnd,null==i||i.log("Aligning playlists based on first/last SN ".concat(t.startSN," (diff: ").concat(o,")"));else if(s&&r)o=e.fragmentStart+n*t.levelTargetDuration;else{if(t.skippedSegments||0!==t.fragmentStart)return o;o=e.fragmentStart,null==i||i.log("Aligning playlists based on first SN ".concat(t.startSN," (diff: ").concat(o,")"))}return function(e,t){if(t){for(var r=e.fragments,i=e.skippedSegments;i<r.length;i++)r[i].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}(t,o),o}function jn(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1/0,r=1e3*e.targetduration;if(e.updated){var i=e.fragments;if(i.length&&4*r>t){var n=1e3*i[i.length-1].duration;n>0&&n<r&&(r=n)}}else r/=2;return Math.round(r)}function qn(e,t,r){var i;if(!e)return null;var n=e.fragments[t-e.startSN];return n||((null==(i=n=e.fragmentHint)?void 0:i.sn)===t?n:r&&t<e.startSN&&r.sn===t?r:null)}function Wn(e,t,r){return e?Yn(e.partList,t,r):null}function Yn(e,t,r){if(e)for(var i=e.length;i--;){var n=e[i];if(n.index===r&&n.fragment.sn===t)return n}return null}function zn(e){e.forEach(function(e,t){var r;null==(r=e.details)||r.fragments.forEach(function(e){e.level=t,e.initSegment&&(e.initSegment.level=t)})})}function Xn(e,t){return!(e===t||!t)&&Qn(e)!==Qn(t)}function Qn(e){return e.replace(/\?[^?]*$/,"")}function $n(e,t){for(var r=0,i=e.length;r<i;r++){var n;if((null==(n=e[r])?void 0:n.cc)===t)return e[r]}return null}function Jn(e,t){var r=e.start+t;e.setStart(r)}function Zn(e,t){for(var r=t.fragments,i=0,n=r.length;i<n;i++)Jn(r[i],e);t.fragmentHint&&Jn(t.fragmentHint,e),t.alignedSliding=!0}function ea(e,t,r){e&&(!function(e,t,r){if(!function(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}(t,e))return;var i=Math.min(t.endCC,e.endCC),n=$n(t.fragments,i),a=$n(e.fragments,i);if(!n||!a)return;var s=n.start-a.start;r.log("Aligning playlists using dicontinuity sequence ".concat(i," (diff: ").concat(s,")")),Zn(s,e)}(t,e,r),t.alignedSliding||function(e,t,r){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;var i,n,a=e.fragments,s=t.fragments;if(!a.length||!s.length)return;var o=Math.min(t.endCC,e.endCC);t.startCC<o&&e.startCC<o&&(i=$n(s,o),n=$n(a,o));i&&n||(n=$n(a,(i=s[Math.floor(s.length/2)]||s.filter(function(e){return!!e})[0]).cc)||a[Math.floor(a.length/2)]);var l=i.programDateTime,u=n.programDateTime;if(!l||!u)return;var c=(u-l)/1e3;if(Math.abs(c)>Math.max(60,e.totalduration))return void r.log("Cannot align playlists using PDT without overlap (".concat(Math.abs(c)," > ").concat(e.totalduration,")"));var d=c-(n.start-i.start);r.log("Aligning playlists using PDT (diff: ".concat(d,")")),Zn(d,e)}(t,e,r),t.alignedSliding||t.skippedSegments||Kn(e,t,!1,r))}function ta(e,t,r){ra(e,t,r),e.addEventListener(t,r)}function ra(e,t,r){e.removeEventListener(t,r)}function ia(e){for(var t="",r=e.length,i=0;i<r;i++)t+="[".concat(e.start(i).toFixed(3),"-").concat(e.end(i).toFixed(3),"]");return t}var na="STOPPED",aa="IDLE",sa="KEY_LOADING",oa="FRAG_LOADING",la="FRAG_LOADING_WAITING_RETRY",ua="WAITING_TRACK",ca="PARSING",da="PARSED",ha="ENDED",fa="ERROR",va="WAITING_INIT_PTS",ga="WAITING_LEVEL",pa=function(e){function t(e,r,i,n,o){var l;return s(this,t),(l=a(this,t,[n,e.logger])).hls=void 0,l.fragPrevious=null,l.fragCurrent=null,l.fragPlaying=null,l.fragmentTracker=void 0,l.transmuxer=null,l._state=na,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=-1,l.startTimeOffset=null,l.retryDate=0,l.levels=null,l.fragmentLoader=void 0,l.initFragmentLoader=void 0,l.keyLoader=void 0,l.levelLastLoaded=null,l.startFragRequested=!1,l.decrypter=void 0,l.initPTS=[],l.buffering=!0,l.loadingParts=!1,l.loopSn=void 0,l.onMediaSeeking=function(){var e=l,t=e.config,r=e.fragCurrent,i=e.media,n=e.mediaBuffer,a=e.state,s=i?i.currentTime:0,o=Bi.bufferInfo(n||i,s,t.maxBufferHole),u=o.len;if(l.log("Media seeking to ".concat(s,", state: ").concat(a,", ").concat(u?"in":"out of"," buffer")),l.state===ha)l.resetLoadingState();else if(r){var c=t.maxFragLookUpTolerance,d=r.start-c,h=r.start+r.duration+c;if(!u||h<o.start||d>o.end){var f=s<d,v=s>h;(f||v)&&(!r.loader||!v&&l.isFragmentNearlyDownloaded(r)?l.fragPrevious=null:(l.log("Cancelling fragment load for seek (sn: ".concat(r.sn,") - ").concat(f?"backward":"forward"," seek")),r.abortRequests(),l.resetLoadingState()))}}if(i&&(l.fragmentTracker.removeFragmentsInRange(s,1/0,l.playlistType,!0),s>l.lastCurrentTime&&(l.lastCurrentTime=s),!l.loadingParts)){var g=Math.max(o.end,s),p=l.shouldLoadParts(l.getLevelDetails(),g);p&&(l.log("LL-Part loading ON after seeking to ".concat(s," with buffer @").concat(g)),l.loadingParts=p)}var m=!Bi.isBuffered(i,s);l.hls.hasEnoughToStart&&!m||(l.log("Setting ".concat(m?"startPosition":"nextLoadPosition"," to ").concat(s," for seek without enough to start")),l.nextLoadPosition=s,m&&(l.startPosition=s)),u<1&&l.state===aa&&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 Ci(e.config),l.initFragmentLoader=new Ci(e.config),l.keyLoader=i,l.fragmentTracker=r,l.config=e.config,l.decrypter=new Pi(e.config),l}return f(t,e),l(t,[{key:"registerListeners",value:function(){var e=this.hls;e.on(ne.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ne.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ne.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(ne.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(ne.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ne.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ne.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(ne.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!==na){this.fragmentLoader.abort(),this.initFragmentLoader.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=na}}},{key:"startPositionValue",get:function(){var e=this.nextLoadPosition,t=this.startPosition;if(-1===t&&e){var r=this.getLevelDetails();return null!=r&&r.live?(this.hls.liveSyncPosition||r.fragmentStart)+this.timelineOffset:e}return t}},{key:"bufferingEnabled",get:function(){return this.buffering}},{key:"backtrackFragment",get:function(){},set:function(e){}},{key:"couldBacktrack",get:function(){return!1},set:function(e){}},{key:"pauseBuffering",value:function(){this.buffering=!1}},{key:"resumeBuffering",value:function(){this.buffering=!0}},{key:"inFlightFrag",get:function(){return{frag:this.fragCurrent,state:this.state}}},{key:"_streamEnded",value:function(e,t){if(t.live||!this.media)return!1;var r=e.end||0,i=this.config.timelineOffset||0;if(r<=i)return!1;var n=e.buffered;this.config.maxBufferHole&&n&&n.length>1&&(e=Bi.bufferedInfo(n,e.start,0));var a=e.nextStart;if(a&&a>i&&a<t.edge)return!1;if(this.media.currentTime<e.start)return!1;var s=t.partList;if(null!=s&&s.length){var o=s[s.length-1];return Bi.isBuffered(this.media,o.start+o.duration/2)}var l=t.fragments[t.fragments.length-1];return this.fragmentTracker.isEndListAppended(l.type)}},{key:"getLevelDetails",value:function(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}},{key:"timelineOffset",get:function(){var e,t=this.config.timelineOffset;return t?(null==(e=this.getLevelDetails())?void 0:e.appliedTimelineOffset)||t:0}},{key:"onMediaAttached",value:function(e,t){var r=this.media=this.mediaBuffer=t.media;ta(r,"seeking",this.onMediaSeeking),ta(r,"ended",this.onMediaEnded);var i=this.config;this.levels&&i.autoStartLoad&&this.state===na&&this.startLoad(i.startPosition)}},{key:"onMediaDetaching",value:function(e,t){this.fragPlaying=null;var r=!!t.transferMedia,i=this.media;if(null!==i){if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),ra(i,"seeking",this.onMediaSeeking),ra(i,"ended",this.onMediaEnded),this.media=this.mediaBuffer=null,this.loopSn=void 0,r)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}},{key:"onManifestLoading",value:function(){this.initPTS=[],this.fragPlaying=this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=0,this.startPosition=-1,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),A(t,"onHandlerDestroying",this,3)([]),this.hls=this.onMediaSeeking=this.onMediaEnded=null}},{key:"onHandlerDestroyed",value:function(){this.state=na,this.fragmentLoader&&this.fragmentLoader.destroy(),this.initFragmentLoader&&this.initFragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.decrypter=this.keyLoader=null,this.fragmentLoader=this.initFragmentLoader=this.fragmentTracker=null,A(t,"onHandlerDestroyed",this,3)([])}},{key:"loadFragment",value:function(e,t,r){this.startFragRequested=!0,this._loadFragForPlayback(e,t,r)}},{key:"_loadFragForPlayback",value:function(e,t,r){var i=this;this._doFragLoad(e,t,r,function(e){var t=e.frag;if(i.fragContextChanged(t))return i.warn("".concat(t.type," sn: ").concat(t.sn).concat(e.part?" part: "+e.part.index:""," of ").concat(i.fragInfo(t,!1,e.part)," was dropped during download.")),void i.fragmentTracker.removeFragment(t);var r=++t.stats.chunkCount;i.log("load progress ".concat(t.type," sn: ").concat(t.sn).concat(e.part?" part: "+e.part.index:""," of ").concat(i.fragInfo(t,!1,e.part)," chunk: ").concat(r)),i._handleFragmentLoadProgress(e)}).then(function(e){if(e){var t=i.state,r=e.frag;i.fragContextChanged(r)?(t===oa||!i.fragCurrent&&t===ca)&&(i.fragmentTracker.removeFragment(r),i.state=aa):("payload"in e&&(i.log("Loaded ".concat(r.type," sn: ").concat(r.sn," of ").concat(i.playlistLabel()," ").concat(r.level," (bytes ").concat(r.stats.loaded,")")),i.hls.trigger(ne.FRAG_LOADED,e)),i._handleFragmentLoadComplete(e))}}).catch(function(t){i.state!==na&&i.state!==fa&&(i.log("Frag error ".concat(e.type," sn:").concat(e.sn," cc:").concat(e.cc,": ").concat((null==t?void 0:t.message)||t)),i.resetFragmentLoading(e))})}},{key:"clearTrackerIfNeeded",value:function(e){var t,r=this.fragmentTracker;if(r.getState(e)===pi){var i=e.type,n=this.getFwdBufferInfo(this.mediaBuffer,i),a=Math.max(e.duration,n?n.len:this.config.maxBufferLength),s=this.backtrackFragment;(1===(s?e.sn-s.sn:0)||this.reduceMaxBufferLength(a,e.duration))&&r.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?r.removeAllFragments():r.hasParts(e.type)&&(r.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),r.getState(e)===mi&&r.removeFragment(e))}},{key:"checkLiveUpdate",value:function(e){if(e.updated&&!e.live){var t=this.fragmentTracker,r=e.fragments[e.fragments.length-1];if(r.endList&&!t.isEndListAppended(this.playlistType)){var i=t.getPartialFragment(r.end);i&&(t.removeFragment(i),t.fragBuffered(r,!0))}t.detectPartialFragments({frag:r,part:null,stats:r.stats,id:r.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}},{key:"waitForLive",value:function(e){var t=e.details;return(null==t?void 0:t.live)&&"EVENT"!==t.type&&(this.levelLastLoaded!==e||t.expired)}},{key:"flushMainBuffer",value:function(e,t){if(e-t){var r={startOffset:e,endOffset:t,type:arguments.length>2&&void 0!==arguments[2]?arguments[2]:null};this.hls.trigger(ne.BUFFER_FLUSHING,r)}}},{key:"_loadInitSegment",value:function(e){var t=this,r=this.hls;return this.initFragmentLoader.abort(),r.trigger(ne.FRAG_LOADING,{frag:e,targetBufferTime:0}),this.initFragmentLoader.load(e).then(function(e){var r,i=e.frag;if(!t.levels||!ye(i,null==(r=t.fragCurrent)?void 0:r.initSegment))throw new xi({type:re.NETWORK_ERROR,details:ie.INTERNAL_ABORTED,error:new Error("init load aborted"),fatal:!1,frag:i,networkDetails:null});return e}).then(function(e){var i=e.frag,n=e.payload,a=i.decryptdata;if(n&&n.byteLength>0&&null!=a&&a.key&&a.iv&&Zi(a.method)){var s=self.performance.now(),o=_i(i,null,t.iframesOnly).decryptRange;return t.decrypter.decrypt(new Uint8Array(n),a.key.buffer,a.iv.buffer,en(a.method),o).catch(function(e){throw r.trigger(ne.ERROR,{type:re.MEDIA_ERROR,details:ie.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:i}),t.fragmentLoader.abort(),e}).then(function(n){var a=self.performance.now();return r.trigger(ne.FRAG_DECRYPTED,{frag:i,part:null,payload:n,stats:{tstart:s,tdecrypt:a}}),e.payload=n,t.completeInitSegmentLoad(e)})}return t.completeInitSegmentLoad(e)})}},{key:"completeInitSegmentLoad",value:function(e){var t=e.frag.stats;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()}},{key:"loadInitSegmentIfNeeded",value:function(e){var t,r=this,i=e.initSegment;if(!this.bitrateTest&&pe(e)&&i&&!i.data)return(!i.encrypted||null!=(t=i.decryptdata)&&t.key?this._loadInitSegment(i):this.keyLoader.load(i).then(function(){return r._loadInitSegment(i)})).catch(function(t){if(r.state===na||r.state===fa)throw t;throw"data"in t&&(t.data.frag=e,r.fragmentLoader.abort(),r.handleFragLoadError(t)),r.resetFragmentLoading(e),t})}},{key:"unhandledEncryptionError",value:function(e,t){var r,i,n=e.tracks;if(n&&!t.encrypted&&(null!=(r=n.audio)&&r.encrypted||null!=(i=n.video)&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){var a=this.media,s=new Error("Encrypted track with no key in ".concat(this.fragInfo(t)," (media ").concat(a?"attached mediaKeys: "+a.mediaKeys:"detached",")"));return this.warn(s.message),!a||a.mediaKeys?!1:(this.hls.trigger(ne.ERROR,{type:re.KEY_SYSTEM_ERROR,details:ie.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||!ye(e,t)}},{key:"fragBufferedComplete",value:function(e,t){var r=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log("Buffered ".concat(e.type," sn: ").concat(e.sn).concat(t?" part: "+t.index:""," of ").concat(this.fragInfo(e,!1,t)," > buffer:").concat(r?ia(Bi.getBuffered(r)):"(detached)",")")),pe(e)){var i;if(e.type!==de.SUBTITLE){var n=e.elementaryStreams;if(!Object.keys(n).some(function(e){return!!n[e]}))return void(this.state=aa)}var a=null==(i=this.levels)?void 0:i[e.level];null!=a&&a.fragmentError&&(t||this.fragmentTracker.getState(e)!==mi)&&(this.log("Resetting level fragment error count of ".concat(a.fragmentError," on frag buffered")),a.fragmentError=0,e.stats.retry=0)}this.state=aa}},{key:"_handleFragmentLoadComplete",value:function(e){var t=this.transmuxer;if(t){var r=e.frag,i=e.part,n=e.partsLoaded,a=!n||0===n.length||n.some(function(e){return!e}),s=_i(r,i).decryptRange,o=new Fi(r.level,r.sn,r.stats.chunkCount+1,0,i?i.index:-1,!a,r.duration,this.iframesOnly,s);this.log("load complete ".concat(r.type," sn: ").concat(r.sn).concat(i?" part: "+i.index:""," of ").concat(this.fragInfo(r,!1,i))),t.flush(o)}}},{key:"_handleFragmentLoadProgress",value:function(e){}},{key:"loadKeyFor",value:function(e,t,r){var i,n=this,a=null;return!e.encrypted||null!=(i=e.decryptdata)&&i.key?e.encrypted||(a=this.keyLoader.loadClear(e,t.encryptedFragments,this.startFragRequested))&&this.log("[eme] blocking frag sn: ".concat(e.sn," load until media-keys acquired")):(this.log("Loading key for ".concat(e.sn," of [").concat(t.startSN,"-").concat(t.endSN,"], ").concat(this.playlistLabel()," ").concat(e.level)),this.state=sa,a=this.keyLoader.load(e,r).then(function(e){if(!n.fragContextChanged(e.frag))return n.hls.trigger(ne.KEY_LOADED,e),n.state===sa&&(n.state=aa),e}),this.hls.trigger(ne.KEY_LOADING,{frag:e})),a}},{key:"_doFragLoad",value:function(e,t){var r=this,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,n=arguments.length>3?arguments[3]:void 0;this.fragCurrent=e;var a=t.details;if(!this.levels||!a)throw new Error("frag load aborted, missing level".concat(a?"":" detail","s"));var s,o=this.fragPrevious;if(!me(e,o)){var l=this.shouldLoadParts(t.details,e.end);l!==this.loadingParts&&(this.log("LL-Part loading ".concat(l?"ON":"OFF"," loading sn ").concat(null==o?void 0:o.sn,"->").concat(e.sn)),this.loadingParts=l)}if(i=Math.max(e.start,i||0),this.loadingParts){var u=a.partList;if(u&&n){i>a.fragmentEnd&&a.fragmentHint&&(e=a.fragmentHint);var c=this.getNextPart(u,e,i);if(c>-1){var d=u[c];if(!me(e=this.fragCurrent=d.fragment,o)&&!this.shouldLoadParts(t.details,e.end))return this.log("LL-Part loading OFF @".concat(this.playhead," next part: ").concat(this.fragInfo(e,!1,d))),this.loadingParts=!1,Promise.resolve(null);if(!this.filterReplacedPrimary(d,t.details))return Promise.resolve(null);var h,f=this.loadKeyFor(e,a);if(this.fragContextChanged(e))return Promise.resolve(null);this.log("Loading ".concat(e.type," sn: ").concat(e.sn," part: ").concat(d.index," (").concat(c,"/").concat(u.length-1,") of ").concat(this.fragInfo(e,!1,d)," cc: ").concat(e.cc," [").concat(a.startSN,"-").concat(a.endSN,"], target: ").concat(i).concat(d.byteRange.length?" range:".concat(d.byteRange.join("-")):"")),this.nextLoadPosition=d.start+d.duration,this.state=oa;var v=this.loadInitSegmentIfNeeded(e);if(f||v){var g=!!f;h=Promise.all([f,v]).then(function(i){var a=S(i,1)[0];return!g||a&&!r.fragContextChanged(a.frag)?r.doFragPartsLoad(e,d,t,n):null}).catch(function(e){return r.handleFragLoadError(e)})}else h=this.doFragPartsLoad(e,d,t,n).catch(function(e){return r.handleFragLoadError(e)});return this.hls.trigger(ne.FRAG_LOADING,{frag:e,part:d,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):h}if(!e.url||this.loadedEndOfParts(u,i))return Promise.resolve(null)}}if(this.loadingParts)this.log("LL-Part loading OFF after next part miss @".concat(i," Check buffer at sn: ").concat(e.sn," loaded parts: ").concat(null==(s=a.partList)?void 0:s.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);if(!this.filterReplacedPrimary(e,t.details))return Promise.resolve(null);var p,m=this.loadInitSegmentIfNeeded(e),y=this.loadKeyFor(e,a,m);if(this.fragContextChanged(e))return this.log("Context changed in KEY_LOADING sn: ".concat(e.sn," ").concat(e.relurl," > ").concat(null==(p=this.fragCurrent)?void 0:p.relurl)),null==m||m.catch(function(){return null}),null==y||y.catch(function(){return null}),Promise.resolve(null);this.log("Loading ".concat(e.type," sn: ").concat(e.sn," of ").concat(this.fragInfo(e,!1)," cc: ").concat(e.cc," ").concat("["+a.startSN+"-"+a.endSN+"]",", target: ").concat(i).concat(e.byteRange.length?" range:".concat(e.byteRange.join("-")):"")),Z(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=oa;var k,E=this.config.progressive&&e.type!==de.SUBTITLE;return k=E&&y?y.then(function(t){return!t||r.fragContextChanged(t.frag)?null:r.fragmentLoader.load(e,r.iframesOnly,n,m)}).catch(function(e){return r.handleFragLoadError(e)}):Promise.all([this.fragmentLoader.load(e,this.iframesOnly,E?n:void 0,E?m:void 0),y,m]).then(function(e){var t=S(e,1)[0];return!E&&n&&n(t),t}).catch(function(e){return r.handleFragLoadError(e)}),this.hls.trigger(ne.FRAG_LOADING,{frag:e,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):Promise.all([k,m]).then(function(e){return S(e,1)[0]})}},{key:"doFragPartsLoad",value:function(e,t,r,i){var n=this;return new Promise(function(a,s){var o,l=[],u=null==(o=r.details)?void 0:o.partList,c=function(t){n.fragmentLoader.loadPart(e,t,i).then(function(i){l[t.index]=i;var s=i.part;n.hls.trigger(ne.FRAG_LOADED,i);var o=Wn(r.details,e.sn,t.index+1)||Yn(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===ie.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===re.KEY_SYSTEM_ERROR&&!t.fatal&&(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)),this.hls.trigger(ne.ERROR,t)}else this.hls.trigger(ne.ERROR,{type:re.OTHER_ERROR,details:ie.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}},{key:"_handleTransmuxerFlush",value:function(e){var t=this.getCurrentContext(e);if(t&&this.state===ca){var r=t.frag,i=t.part,n=t.level,a=self.performance.now();r.stats.parsing.end=a,i&&(i.stats.parsing.end=a);var s=this.getLevelDetails(),o=s&&r.sn>s.endSN||this.shouldLoadParts(s,r.end);o!==this.loadingParts&&(this.log("LL-Part loading ".concat(o?"ON":"OFF"," after parsing segment ending @").concat(r.end)),this.loadingParts=o),this.updateLevelTiming(r,i,n,e)}else this.fragCurrent||this.state===na||this.state===fa||(this.state=aa)}},{key:"shouldLoadParts",value:function(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList&&!this.iframesOnly){var r,i=e.partList[0];if(t>=i.end+((null==(r=e.fragmentHint)?void 0:r.duration)||0))if(this.playhead>i.start-i.fragment.duration)return!0}}return!1}},{key:"getCurrentContext",value:function(e){var t=this.levels,r=this.fragCurrent,i=e.level,n=e.sn,a=e.part;if(null==t||!t[i])return this.warn("Levels object was unset while buffering fragment ".concat(n," of ").concat(this.playlistLabel()," ").concat(i,". The current chunk will not be buffered.")),null;var s=t[i],o=s.details,l=a>-1?Wn(o,n,a):null,u=l?l.fragment:qn(o,n,r);return u?(r&&r!==u&&(u.stats=r.stats),{frag:u,part:l,level:s}):null}},{key:"bufferFragmentData",value:function(e,t,r,i,n){if(this.state===ca){pe(t)&&!this.fragContextChanged(t)&&(this.fragPrevious=t);var a=e.data1,s=e.data2,o=a;if(s&&(o=Kt(a,s)),o.length){var l=this.initPTS[t.cc],u=l?-l.baseTime/l.timescale:void 0,c={type:e.type,frag:t,part:r,chunkMeta:i,offset:u,parent:t.type,data:o};if(this.hls.trigger(ne.BUFFER_APPENDING,c),e.dropped&&e.independent&&!r){if(n)return;this.flushBufferGap(t)}}}}},{key:"flushBufferGap",value:function(e){var t=this.media;if(t)if(Bi.isBuffered(t,t.currentTime)){var r=t.currentTime,i=Bi.bufferInfo(t,r,0),n=e.duration,a=Math.min(2*this.config.maxFragLookUpTolerance,.25*n),s=Math.max(Math.min(e.start-a,i.end-a),r+a);e.start-s>a&&this.flushMainBuffer(s,e.start)}else this.flushMainBuffer(0,e.start)}},{key:"getFwdBufferInfo",value:function(e,t){var r,i=this.playhead,n=this.lastCurrentTime>i||null!=(r=this.media)&&r.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,i,t,n)}},{key:"getFwdBufferInfoAtPos",value:function(e,t,r,i){var n=Bi.bufferInfo(e,t,i);if(0===n.len&&void 0!==n.nextStart){var a=this.fragmentTracker.getBufferedFrag(t,r);if(a&&(n.nextStart<=a.end||a.gap)){var s=Math.max(Math.min(n.nextStart,a.end)-t,i);return Bi.bufferInfo(e,t,s)}}return n}},{key:"getMaxBufferLength",value:function(e){var t,r=this.config;return t=e?Math.max(8*r.maxBufferSize/e,r.maxBufferLength):r.maxBufferLength,Math.min(t,r.maxMaxBufferLength)}},{key:"exceedsMaxBuffer",value:function(e,t,r){var i=e.nextStart;if(i&&r.start>i){var n=e.buffered;if(n){for(var a=e.len,s=e.bufferedIndex,o=n.length-1;o>s;o--)n[o].start<r.start&&(a+=n[o].end-n[o].start);return a>=t}}return!1}},{key:"reduceMaxBufferLength",value:function(e,t){var r=this.config,i=Math.max(Math.min(e-t,r.maxBufferLength),t/2),n=Math.max(e-3*t,r.maxMaxBufferLength/2,i);return n>=i&&(r.maxMaxBufferLength=n,this.warn("Reduce max buffer length to ".concat(n,"s")),!0)}},{key:"getAppendedFrag",value:function(e){var t=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,this.playlistType):null;return t&&"fragment"in t?t.fragment:t}},{key:"getNextFragment",value:function(e,t){var r=t.fragments,i=r.length;if(!i)return null;var n=this.config,a=t.fragmentStart,s=n.lowLatencyMode&&!!t.partList,o=null;if(t.live){var l=n.initialLiveManifestSize;if(i<l)return this.warn("Not enough fragments to start playback (have: ".concat(i,", need: ").concat(l,")")),null;if(this.startFragRequested||!s||this.loadingParts||(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),!t.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||e<a){var u;o=this.getInitialLiveFragment(t);var c,d,h=this.config.startPosition,f=this.hls.startPosition,v=this.hls.liveSyncPosition,g=(null==(u=o)?void 0:u.start)||0;if(-1!==f&&f>=a?(c=f,d=f===h?"config":"next load start"):v?(c=v,d="live edge"):(c=e,d="buffer pos"),c<g&&(c=g,d="live frag start"),c<a&&(c=a,d="playlist start"),this.startPosition!=c||this.nextLoadPosition!=c){var p=t.live&&!this.filterReplacedPrimary(o,t)?-1:c;this.log("Setting startPosition to ".concat(p," next load ").concat(c," ").concat(-1===f?"":"(from ".concat(h,") "),"based on ").concat(d,". live edge: ").concat(v," live frag start: ").concat(g," playlist start: ").concat(a," buffer pos: ").concat(e)),this.startPosition=p,this.nextLoadPosition=c}}}else e<=a&&(o=r[0]);if(!o){var m=this.loadingParts?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,m,t)}var y=this.filterReplacedPrimary(o,t);return!y&&o&&(y=ei(t,o.sn))&&(this.nextLoadPosition=y.start),y}},{key:"isLoopLoading",value:function(e,t){if(this.nextLoadPosition<=t)return!1;var r=this.fragmentTracker.getState(e);if(r===yi)return!0;if(r===mi){if(e.gap)return!0;if(e.stats.retry>1)return!0}return!1}},{key:"getNextFragmentLoopLoading",value:function(e,t,r,i,n){var a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t))&&!a.gap&&r.nextStart){var s=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,r.nextStart,i,0);if(null!==s&&r.len+s.len>=n){var o=a.sn;return this.loopSn!==o&&(this.log('buffer full after gaps in "'.concat(i,'" playlist starting at sn: ').concat(o)),this.loopSn=o),null}}return this.loopSn=void 0,a}},{key:"primaryPrefetch",get:function(){var e;if(ya(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(ya(this.config)&&("type"in e?e:e.fragment).type!==de.SUBTITLE){var r=this.hls.interstitialsManager,i=null==r?void 0:r.bufferingItem;if(i){var n=i.event;if(n){if(!n.appendInPlace&&(Math.abs(e.start-i.start)>1||0===i.start))return null}else{if(e.end<=i.start&&!1===(null==t?void 0:t.live))return null;if(e.start>=i.end&&i.nextEvent&&(i.nextEvent.appendInPlace&&!i.nextEvent.hasPlayed||e.start-i.end>1))return null}}if(ma(e,null==r?void 0:r.playerQueue,this.playhead))return null}return e}},{key:"getNextPart",value:function(e,t,r){for(var i=-1,n=!1,a=!0,s=0,o=e.length;s<o;s++){var l=e[s];if(a=a&&!l.independent,i>-1&&r<l.start)break;var u=l.loaded||l.gap;u?i=-1:(n||(l.independent||a)&&l.fragment===t)&&(i=s),n=u&&!l.gap}var c=e[i];return c&&c.fragment!==t&&this.log("Need buffer at ".concat(r," but next unloaded part starts at ").concat(c.start," (sn: ").concat(t.sn," -> ").concat(c.fragment.sn,")")),i}},{key:"loadedEndOfParts",value:function(e,t){for(var r,i=e.length;i--;){if(!(r=e[i]).loaded)return!1;if(t>r.start)return!0}return!1}},{key:"getInitialLiveFragment",value:function(e){var t=e.fragments,r=this.fragPrevious,i=null;if(r){if(e.hasProgramDateTime&&(i=function(e,t,r){if(null===t||!Array.isArray(e)||!e.length||!Z(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;for(var i=0;i<e.length;++i){var n=e[i];if(Jr(t,r,n))return n}return null}(t,r.endProgramDateTime,this.config.maxFragLookUpTolerance),i&&this.log("Live playlist, switching playlist, load frag with same PDT: ".concat(r.programDateTime))),!i){var n=r.sn+1;if(n>=e.startSN&&n<=e.endSN){var a=t[n-e.startSN];r.cc===a.cc&&(i=a,this.log("Live playlist, switching playlist, load frag with next SN: ".concat(i.sn)))}i||(i=Zr(e,r.cc,r.end))&&this.log("Live playlist, switching playlist, load frag with same CC: ".concat(i.sn))}}else{var s=this.hls.liveSyncPosition;null!==s&&(i=this.getFragmentAtPosition(s,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}},{key:"getFragmentAtPosition",value:function(e,t,r){var i,n,a=this.config,s=this.fragPrevious,o=r.fragments,l=r.endSN,u=r.fragmentHint,c=a.maxFragLookUpTolerance,d=r.partList,h=!!(this.loadingParts&&null!=d&&d.length&&u);(h&&!this.bitrateTest&&d[d.length-1].fragment.sn===u.sn&&(o=o.concat(u),l=u.sn),s&&this.fragmentTracker.getState(s)===gi&&(s=null),e<t)?i=Qr(s,o,e,e<this.lastCurrentTime||e>t-c||null!=(n=this.media)&&n.paused||!this.startFragRequested?0:c):i=o[o.length-1];if(i){var f=i.sn-r.startSN,v=this.fragmentTracker.getState(i);if((v===yi||v===mi&&i.gap)&&(s=i),me(i,s)&&(!h||d[0].fragment.sn>i.sn||!r.live)){var g=o[f+1];i=i.sn<l&&this.fragmentTracker.getState(g)!==yi?g:null}}return i}},{key:"alignPlaylists",value:function(e,t,r){var i=e.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;var n=e.fragmentStart,a=!t,s=e.alignedSliding&&Z(n);if(a||!s&&!n){ea(r,e,this);var o=e.fragmentStart;return this.log("Live playlist sliding: ".concat(o," start-sn: ").concat(t?t.startSN:"na","->").concat(e.startSN," fragments: ").concat(i)),o}return n}},{key:"waitForCdnTuneIn",value:function(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}},{key:"setStartPosition",value:function(e,t){var r=this.startPosition;r<t&&(r=-1);var i=this.timelineOffset;if(-1===r){var n=null!==this.startTimeOffset,a=n?this.startTimeOffset:e.startTimeOffset;if(null!==a&&Z(a))r=t+a,a<0&&(r+=e.edge),r=Math.min(Math.max(t,r),t+e.totalduration),this.log("Setting startPosition to ".concat(r," for start time offset ").concat(a," found in ").concat(n?"multivariant":"media"," playlist")),this.startPosition=r;else if(e.live){var s=this.hls.liveSyncPosition;r=s||t,this.log("Setting startPosition to -1 to start at ".concat(s?"live edge":"playlist start"," ").concat(r)),this.startPosition=-1}else this.log("setting startPosition to 0 by default"),this.startPosition=r=0;this.lastCurrentTime=r+i}this.nextLoadPosition=r+i}},{key:"getLoadPosition",value:function(){var e,t=this.media,r=0;return null!=(e=this.hls)&&e.hasEnoughToStart&&t&&!this.iframesOnly?r=t.currentTime:this.nextLoadPosition>=0&&(r=this.nextLoadPosition),r}},{key:"playhead",get:function(){var e;if(null!=(e=this.hls)&&e.hasEnoughToStart){var t,r=null==(t=this.media)?void 0:t.currentTime;return Z(r)?r:this.lastCurrentTime}return this.getLoadPosition()}},{key:"iframesOnly",get:function(){var e;if(this.playlistType!==de.MAIN)return!1;var t=this.getLevelDetails();return t?t.iframesOnly:null==(e=this.levelLastLoaded)?void 0:e.iframes}},{key:"handleFragLoadAborted",value:function(e,t){this.transmuxer&&e.type===this.playlistType&&pe(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===la)||(this.state=aa)}},{key:"onFragmentOrKeyLoadError",value:function(e,t){if(t.chunkMeta&&!t.frag){var r=this.getCurrentContext(t.chunkMeta);r&&(t.frag=r.frag)}var i=t.frag,n=t.part;if(i&&this.levels&&i.type===e)if(this.fragContextChanged(i)){var a;this.warn("Frag load error must match current frag to retry ".concat(i.relurl," > ").concat(null==(a=this.fragCurrent)?void 0:a.relurl))}else{var s=t.details===ie.FRAG_GAP;s&&this.fragmentTracker.addAsGap(i);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===ni,g=f&&!o.resolved&&u&si,p=this.hls.latestLevelDetails,m=null==p?void 0:p.live;if(!v&&g&&pe(i)&&m&&i.sn<p.endSN&&!we(t))this.resetFragmentErrors(e),n?n.gap=!0:this.treatAsGap(i),o.resolved=!0;else if((v||g)&&d<h.maxNumRetry){var y,k=xe(null==(y=t.response)?void 0:y.code),E=De(h,d);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+E,this.state=la,o.resolved=!0,k)return this.log("Waiting for connection (offline)"),this.retryDate=1/0,void(t.reason="offline");this.warn("Fragment ".concat(i.sn," of ").concat(e," ").concat(i.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===ii||(o.resolved=!0)}else this.state=l===ri?ga:fa;this.tickImmediate()}else this.state=fa}}},{key:"checkRetryDate",value:function(){var e=self.performance.now(),t=this.retryDate,r=t===1/0;(!t||e>=t||r&&!xe(0))&&(r&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=aa)}},{key:"reduceLengthAndFlushBuffer",value:function(e){if(this.state===ca||this.state===da){var t=e.frag,r=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,r),n=i&&i.len>.5;n&&this.reduceMaxBufferLength(i.len,(null==t?void 0:t.duration)||10);var a=!n;return a?this.warn("Buffer full error while media.currentTime (".concat(this.playhead,") is not buffered, flush ").concat(r," buffer")):i.nextStart&&t&&i.nextStart>t.start&&this.flushMainBuffer(i.nextStart,Number.POSITIVE_INFINITY,r===de.AUDIO?r:void 0),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}},{key:"resetFragmentErrors",value:function(e){e===de.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==na&&(this.state=aa)}},{key:"afterBufferFlushed",value:function(e,t){if(e){var r=Bi.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,this.playlistType),this.state===ha&&this.resetLoadingState()}}},{key:"resetLoadingState",value:function(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==na&&(this.state=aa)}},{key:"resetStartWhenNotLoaded",value:function(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;var e=this.getLevelDetails();null!=e&&e.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(e,e.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}},{key:"resetWhenMissingContext",value:function(e){this.log("Loading context changed while buffering sn ".concat(e.sn," of ").concat(this.playlistLabel()," ").concat(-1===e.level?"<removed>":e.level,". This chunk will not be buffered.")),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}},{key:"removeUnbufferedFrags",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}},{key:"updateLevelTiming",value:function(e,t,r,i){var n=this,a=r.details;if(a){if(this.log("update level timing ".concat(e.type," sn: ").concat(e.sn).concat(t?" part: "+t.index:""," of ").concat(this.fragInfo(e,!1,t))),!Object.keys(e.elementaryStreams).reduce(function(t,s){var o=e.elementaryStreams[s];if(o){var l=o.endPTS-o.startPTS;if(l<=0)return n.warn("Could not parse fragment ".concat(e.sn," ").concat(s," duration reliably (").concat(l,")")),t||!1;var u=i.partial?0:Vn(a,e,o.startPTS,o.endPTS,o.startDTS,o.endDTS,n.iframesOnly,n);return n.hls.trigger(ne.LEVEL_PTS_UPDATED,{details:a,level:r,drift:u,type:s,frag:e,start:o.startPTS,end:o.endPTS}),!0}return t},!1)){var s,o,l,u,c=null===(null==(s=this.transmuxer)?void 0:s.error),d=null!=(null==(o=this.transmuxer)?void 0:o.error),h=(null!=(l=null==(u=this.levels)?void 0:u.length)?l:0)>1;if((0===r.fragmentError||c&&(r.fragmentError<2||e.endList)||d&&h)&&this.treatAsGap(e,r),c){var f=new Error("Found no media in ".concat(this.playlistLabel()," ").concat(e.level," ").concat(t?"part: ".concat(t.index," of "):"","sn: ").concat(e.sn," at playlist time: ").concat(e.start,". Resetting transmuxer to fallback to playlist timing"));if(this.warn(f.message),this.hls.trigger(ne.ERROR,{type:re.MEDIA_ERROR,details:ie.FRAG_PARSING_ERROR,fatal:!1,error:f,frag:e,reason:"Found no media in msn ".concat(e.sn," of ").concat(this.playlistLabel(),' "').concat(r.url,'"')}),!this.hls)return;this.resetTransmuxer()}}this.state=da,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(ne.FRAG_PARSED,{frag:e,part:t,chunkMeta:i})}else this.warn("level.details undefined")}},{key:"playlistLabel",value:function(){return"".concat(this.playlistType," playlist")}},{key:"fragInfo",value:function(e){var t,r,i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],n=arguments.length>2?arguments[2]:void 0;return"".concat(this.playlistLabel()," ").concat(e.level," (").concat(n?"part":"frag",":[").concat(null!=(t=i&&!n?e.startPTS:(n||e).start)?t:NaN,"-").concat(null!=(r=i&&!n?e.endPTS:(n||e).end)?r:NaN,"]").concat(n&&"main"===e.type?"INDEPENDENT="+(n.independent?"YES":"NO"):"",")")}},{key:"treatAsGap",value:function(e,t){t&&t.fragmentError++,this.fragmentTracker.addAsGap(e)}},{key:"resetTransmuxer",value:function(){var e;null==(e=this.transmuxer)||e.reset()}},{key:"isFragmentNearlyDownloaded",value:function(e){var t,r=null==(t=e.loader)?void 0:t.stats;if(!r)return!1;var i=r.loading.first>0,n=(r.total-r.loaded)/(this.hls.bandwidthEstimate||this.hls.config.abrEwmaDefaultEstimate);return i&&n<=.15}},{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)))}},{key:"calculateOptimalSwitchPoint",value:function(e,t){var r=0,i=this.hls,n=this.media,a=this.config,s=this.levels,o=this.playlistType,l=this.getLevelDetails();if(n&&!n.paused&&s){var u,c=o===de.AUDIO?br(e.audioCodec,128e3):e.maxBitrate,d=1+i.ttfbEstimate/1e3,h=i.bandwidthEstimate*a.abrBandWidthUpFactor;r=d+c*(l&&(this.loadingParts?l.partTarget:l.averagetargetduration)||(null==(u=this.fragCurrent)?void 0:u.duration)||6)/h,e.details||(r+=d)}var f=this.playhead;return{fetchdelay:r,okToFlushForwardBuffer:!(null!=l&&l.live)||t.end-f>1.5*r}}},{key:"scheduleTrackSwitch",value:function(e,t,r){var i=this.media,n=this.playlistType;if(i&&e){var a=r?this.getBufferedFrag(this.playhead+t):null;if(a){var s=this.followingBufferedFrag(a);if(s){var o;this.abortCurrentFrag();var l=s.maxStartPTS?s.maxStartPTS:s.start,u=s.duration,c=Math.max(a.end,l+Math.min(Math.max(u-this.config.maxFragLookUpTolerance,u*(this.couldBacktrack?.5:.125)),u*(this.couldBacktrack?.75:.25)));if(((null==(o=this.getLevelDetails())?void 0:o.fragmentStart)||0)>c)return;var d=n===de.MAIN?null:"audio";this.flushMainBuffer(c,Number.POSITIVE_INFINITY,d),this.cleanupBackBuffer()}}}}},{key:"cleanupBackBuffer",value:function(){var e=this.media,t=this.playlistType;if(e){var r=this.getAppendedFrag(this.playhead);if(r&&r.start>1){var i=t===de.AUDIO;this.flushMainBuffer(0,r.start-(i?0:1),i?"audio":null)}}}},{key:"getBufferedFrag",value:function(e){return this.fragmentTracker.getBufferedFrag(e,this.playlistType)}},{key:"followingBufferedFrag",value:function(e){return e?this.getBufferedFrag(e.end+.5):null}},{key:"abortCurrentFrag",value:function(){var e=this.fragCurrent;switch(this.fragCurrent=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case sa:case oa:case la:case ca:case da:this.state=aa}this.nextLoadPosition=this.playhead}},{key:"checkFragPlaying",value:function(){var e=this.media,t=null;if(e&&e.readyState>1&&!1===e.seeking){var r=e.currentTime;if(Bi.isBuffered(e,r)?t=this.getAppendedFrag(r):Bi.isBuffered(e,r+.1)&&(t=this.getAppendedFrag(r+.1)),t&&(this.backtrackFragment=void 0,!me(t,this.fragPlaying)))return this.fragPlaying=t,!0}return!1}},{key:"getBufferOutput",value:function(){return null}},{key:"nextLevelSwitch",value:function(){var e=this.levels,t=this.media,r=this.hls,i=this.config,n=this.playlistType;if(null!=t&&t.readyState&&e&&r&&i){var a=this.getBufferOutput(),s=this.getFwdBufferInfo(a,n);if(!s)return;var o=e[n===de.AUDIO?r.nextAudioTrack:r.nextLoadLevel],l=this.calculateOptimalSwitchPoint(o,s),u=l.fetchdelay,c=l.okToFlushForwardBuffer;this.scheduleTrackSwitch(s,u,c)}this.tickImmediate()}}])}(Oi);function ma(e,t,r){if(t)for(var i=t.length;i--;){var n=t[i].interstitial,a=n.startTime,s=Math.min(a+n.duration,n.resumeTime);if(n.appendInPlace){if(e.start>=a&&e.end<=s)return!0;if(r>e.start&&e.end>a&&e.start<s)return!0}}return!1}function ya(e){return!!e.interstitialsController&&!1!==e.enableInterstitialPlayback}var ka=function(){return l(function e(){s(this,e),this.chunks=[],this.dataLength=0},[{key:"push",value:function(e){this.chunks.push(e),this.dataLength+=e.length}},{key:"flush",value:function(){var e,t=this.chunks,r=this.dataLength;return t.length?(e=1===t.length?t[0]:function(e,t){for(var r=new Uint8Array(t),i=0,n=0;n<e.length;n++){var a=e[n];r.set(a,i),i+=a.length}return r}(t,r),this.reset(),e):new Uint8Array(0)}},{key:"reset",value:function(){this.chunks.length=0,this.dataLength=0}}])}();var Ea,Sa={exports:{}};var Ta=(Ea||(Ea=1,function(e){var t=Object.prototype.hasOwnProperty,r="~";function i(){}function n(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function a(e,t,i,a,s){if("function"!=typeof i)throw new TypeError("The listener must be a function");var o=new n(i,a||e,s),l=r?r+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function s(e,t){0===--e._eventsCount?e._events=new i:delete e._events[t]}function o(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(r=!1)),o.prototype.eventNames=function(){var e,i,n=[];if(0===this._eventsCount)return n;for(i in e=this._events)t.call(e,i)&&n.push(r?i.slice(1):i);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(e)):n},o.prototype.listeners=function(e){var t=r?r+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var n=0,a=i.length,s=new Array(a);n<a;n++)s[n]=i[n].fn;return s},o.prototype.listenerCount=function(e){var t=r?r+e:e,i=this._events[t];return i?i.fn?1:i.length:0},o.prototype.emit=function(e,t,i,n,a,s){var o=r?r+e:e;if(!this._events[o])return!1;var l,u,c=this._events[o],d=arguments.length;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),d){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,i),!0;case 4:return c.fn.call(c.context,t,i,n),!0;case 5:return c.fn.call(c.context,t,i,n,a),!0;case 6:return c.fn.call(c.context,t,i,n,a,s),!0}for(u=1,l=new Array(d-1);u<d;u++)l[u-1]=arguments[u];c.fn.apply(c.context,l)}else{var h,f=c.length;for(u=0;u<f;u++)switch(c[u].once&&this.removeListener(e,c[u].fn,void 0,!0),d){case 1:c[u].fn.call(c[u].context);break;case 2:c[u].fn.call(c[u].context,t);break;case 3:c[u].fn.call(c[u].context,t,i);break;case 4:c[u].fn.call(c[u].context,t,i,n);break;default:if(!l)for(h=1,l=new Array(d-1);h<d;h++)l[h-1]=arguments[h];c[u].fn.apply(c[u].context,l)}}return!0},o.prototype.on=function(e,t,r){return a(this,e,t,r,!1)},o.prototype.once=function(e,t,r){return a(this,e,t,r,!0)},o.prototype.removeListener=function(e,t,i,n){var a=r?r+e:e;if(!this._events[a])return this;if(!t)return s(this,a),this;var o=this._events[a];if(o.fn)o.fn!==t||n&&!o.once||i&&o.context!==i||s(this,a);else{for(var l=0,u=[],c=o.length;l<c;l++)(o[l].fn!==t||n&&!o[l].once||i&&o[l].context!==i)&&u.push(o[l]);u.length?this._events[a]=1===u.length?u[0]:u:s(this,a)}return this},o.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&s(this,t)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=r,o.EventEmitter=o,e.exports=o}(Sa)),Sa.exports),Aa=ae(Ta),ba="1.7.3",Ia={};function Ra(e,t){return 255===e[t]&&240==(246&e[t+1])}function La(e,t){return 1&e[t+1]?7:9}function Pa(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function wa(e,t){return t+1<e.length&&Ra(e,t)}function Ca(e,t){if(wa(e,t)){var r=La(e,t);if(t+r>=e.length)return!1;var i=Pa(e,t);if(i<=r)return!1;var n=t+i;return n===e.length||wa(e,n)}return!1}function Da(e,t,r,i,n){if(!e.samplerate){var a=function(e,t,r,i){var n=t[r+2],a=n>>2&15;if(!(a>12)){var s,o=1+(n>>6&3),l=t[r+3]>>6&3|(1&n)<<2,u=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][a],c=a;5!==o&&29!==o||(c-=3);var d=(14&c)>>1,h=(1&c)<<7|l<<3,f=0;if(1===o&&a>=6){var v=a-3;s=[(f=5)<<3|d,h|(14&v)>>1,(1&v)<<7|8,0]}else s=[o<<3|d,h];var g="mp4a.40."+(f||o);return je.log("manifest codec:".concat(i,", parsed codec:").concat(g,", channels:").concat(l,", rate:").concat(u," (ADTS object type:").concat(o," sampling index:").concat(a," esds config:[").concat(s.join(","),"])")),{config:s,samplerate:u,channelCount:l,codec:g,parsedCodec:g,manifestCodec:i}}var p=new Error("invalid ADTS sampling index:".concat(a));e.emit(ne.ERROR,ne.ERROR,{type:re.MEDIA_ERROR,details:ie.FRAG_PARSING_ERROR,fatal:!0,error:p,reason:p.message})}(t,r,i,n);if(!a)return;Ae(e,a)}}function _a(e){return 9216e4/e}function Ma(e,t,r,i,n){var a,s=i+n*_a(e.samplerate),o=function(e,t){var r=La(e,t);if(t+r<=e.length){var i=Pa(e,t)-r;if(i>0)return{headerLength:r,frameLength:i}}}(t,r);if(o){var l=o.frameLength,u=o.headerLength,c=u+l,d=Math.max(0,r+c-t.length);d?(a=new Uint8Array(c-u)).set(t.subarray(r+u,t.length),0):a=t.subarray(r+u,r+c);var h={unit:a,pts:s};return d||e.samples.push(h),{sample:h,length:c,missing:d}}var f=t.length-r;return(a=new Uint8Array(f)).set(t.subarray(r,t.length),0),{sample:{unit:a,pts:s},length:f,missing:-1}}var xa=function(e){return e.audioId3="org.id3",e.dateRange="com.apple.quicktime.HLS",e.emsg="https://aomedia.org/emsg/ID3",e.misbklv="urn:misb:KLV:bin:1910.1",e}({});function Oa(){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 Fa=function(){return l(function e(){s(this,e),this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null},[{key:"resetInitSegment",value:function(e,t,r,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}},{key:"resetTimeStamp",value:function(e){this.initPTS=e,this.resetContiguity()}},{key:"resetContiguity",value:function(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}},{key:"canParse",value:function(e,t){return!1}},{key:"appendFrame",value:function(e,t,r){}},{key:"demux",value:function(e,t){this.cachedData&&(e=Kt(this.cachedData,e),this.cachedData=null);var r,i=it(e,0),n=i?i.length:0,a=this._audioTrack,s=this._id3Track,o=i?ht(i):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&Z(o))&&(this.basePTS=Na(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),i&&i.length>0&&s.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:xa.audioId3,duration:Number.POSITIVE_INFINITY});n<l;){if(this.canParse(e,n)){var u=this.appendFrame(a,e,n);u?(this.frameIndex++,this.lastPTS=u.sample.pts,r=n+=u.length):n=l}else tt(e,n)?(i=it(e,n),s.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:xa.audioId3,duration:Number.POSITIVE_INFINITY}),r=n+=i.length):n++;if(n===l&&r!==l){var c=e.slice(r);this.cachedData?this.cachedData=Kt(this.cachedData,c):this.cachedData=c}}return{audioTrack:a,videoTrack:Oa(),id3Track:s,textTrack:Oa()}}},{key:"demuxSampleAes",value:function(e,t,r){return Promise.reject(new Error("[".concat(this,"] This demuxer does not support Sample-AES decryption")))}},{key:"flush",value:function(e){var t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:Oa(),id3Track:this._id3Track,textTrack:Oa()}}},{key:"destroy",value:function(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}])}(),Na=function(e,t,r){return Z(e)?90*e:9e4*t+(r?9e4*r.baseTime/r.timescale:0)},Ba=[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],Ua=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Va=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Ga=[0,1,1,4];function Ha(e,t,r,i,n){if(!(r+24>t.length)){var a=Ka(t,r);if(a&&r+a.frameLength<=t.length){var s=i+n*(9e4*a.samplesPerFrame/a.sampleRate),o={unit:t.subarray(r,r+a.frameLength),pts:s,dts:s};return e.config=[],e.channelCount=a.channelCount,e.samplerate=a.sampleRate,e.samples.push(o),{sample:o,length:a.frameLength,missing:0}}}}function Ka(e,t){var r=e[t+1]>>3&3,i=e[t+1]>>1&3,n=e[t+2]>>4&15,a=e[t+2]>>2&3;if(1!==r&&0!==n&&15!==n&&3!==a){var s=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*Ba[14*(3===r?3-i:3===i?3:4)+n-1],u=Ua[3*(3===r?0:2===r?1:2)+a],c=3===o?1:2,d=Va[r][i],h=Ga[i],f=8*d*h,v=Math.floor(d*l/u+s)*h,g=ir();return!!g&&g<=87&&2===i&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:u,channelCount:c,frameLength:v,samplesPerFrame:f}}}function ja(e,t){return!(255!==e[t]||224&~e[t+1]||!(6&e[t+1]))}function qa(e,t){return t+1<e.length&&ja(e,t)}function Wa(e,t){if(t+1<e.length&&ja(e,t)){var r=Ka(e,t),i=4;null!=r&&r.frameLength&&(i=r.frameLength);var n=t+i;return n===e.length||qa(e,n)}return!1}var Ya=function(){return l(function e(t,r,i){s(this,e),this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Pi(r,!0)},[{key:"decryptBuffer",value:function(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Ai,{start:0,end:e.byteLength})}},{key:"decryptAacSample",value:function(e,t,r){var i=this,n=e[t].unit;if(!(n.length<=16)){var a=n.subarray(16,n.length-n.length%16),s=a.buffer.slice(a.byteOffset,a.byteOffset+a.length);this.decryptBuffer(s).then(function(a){var s=new Uint8Array(a);n.set(s,16),i.decrypter.isSync()||i.decryptAacSamples(e,t+1,r)}).catch(r)}}},{key:"decryptAacSamples",value:function(e,t,r){for(;;t++){if(t>=e.length)return void r();if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,r),!this.decrypter.isSync()))return}}},{key:"getAvcEncryptedData",value:function(e){for(var t=16*Math.floor((e.length-48)/160)+16,r=new Int8Array(t),i=0,n=32;n<e.length-16;n+=160,i+=16)r.set(e.subarray(n,n+16),i);return r}},{key:"getAvcDecryptedUnit",value:function(e,t){for(var r=new Uint8Array(t),i=0,n=32;n<e.length-16;n+=160,i+=16)e.set(r.subarray(i,i+16),n);return e}},{key:"decryptAvcSample",value:function(e,t,r,i,n){var a=this,s=Yt(n.data),o=this.getAvcEncryptedData(s);this.decryptBuffer(o.buffer).then(function(o){n.data=a.getAvcDecryptedUnit(s,o),a.decrypter.isSync()||a.decryptAvcSamples(e,t,r+1,i)}).catch(i)}},{key:"decryptAvcSamples",value:function(e,t,r,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,r=0){if(t>=e.length)return void i();for(var n=e[t].units;!(r>=n.length);r++){var a=n[r];if(!(a.data.length<=48||1!==a.type&&5!==a.type||(this.decryptAvcSample(e,t,r,i,a),this.decrypter.isSync())))return}}}}])}(),za=function(e){function t(e,r){var i;return s(this,t),(i=a(this,t)).observer=void 0,i.config=void 0,i.sampleAes=null,i.observer=e,i.config=r,i}return f(t,e),l(t,[{key:"resetInitSegment",value:function(e,r,i,n){A(t,"resetInitSegment",this,3)([e,r,i,n]),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:r,duration:n,inputTimeScale:9e4,dropped:0}}},{key:"canParse",value:function(e,t){return function(e,t){return function(e,t){return t+5<e.length}(e,t)&&Ra(e,t)&&Pa(e,t)<=e.length-t}(e,t)}},{key:"appendFrame",value:function(e,t,r){Da(e,this.observer,t,r,e.manifestCodec);var i=Ma(e,t,r,this.basePTS,this.frameIndex);if(0===(null==i?void 0:i.missing))return i}},{key:"demuxSampleAes",value:function(e,t,r){var i=this.demux(e,r),n=this.sampleAes=new Ya(this.observer,this.config,t);return new Promise(function(e){n.decryptAacSamples(i.audioTrack.samples,0,function(){e(i)})})}}],[{key:"probe",value:function(e,t){if(!e)return!1;var r=it(e,0),i=(null==r?void 0:r.length)||0;if(Wa(e,i))return!1;for(var n=e.length;i<n;i++)if(Ca(e,i))return t.log("ADTS sync word found !"),!0;return!1}}])}(Fa),Xa=function(e,t){var r=0,i=5;t+=i;for(var n=new Uint32Array(1),a=new Uint32Array(1),s=new Uint8Array(1);i>0;){s[0]=e[t];var o=Math.min(i,8),l=8-o;a[0]=4278190080>>>24+l<<l,n[0]=(s[0]&a[0])>>l,r=r?r<<o|n[0]:n[0],t+=1,i-=o}return r},Qa=function(e){function t(e){var r;return s(this,t),(r=a(this,t)).observer=void 0,r.observer=e,r}return f(t,e),l(t,[{key:"resetInitSegment",value:function(e,r,i,n){A(t,"resetInitSegment",this,3)([e,r,i,n]),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:r,duration:n,inputTimeScale:9e4,dropped:0}}},{key:"canParse",value:function(e,t){return t+64<e.length}},{key:"appendFrame",value:function(e,t,r){var i=$a(e,t,r,this.basePTS,this.frameIndex);if(-1!==i)return{sample:e.samples[e.samples.length-1],length:i,missing:0}}}],[{key:"probe",value:function(e){if(!e)return!1;var t=it(e,0);if(!t)return!1;var r=t.length;if(11===e[r]&&119===e[r+1]&&void 0!==ht(t)){if(Xa(e,r)<16)return!0;throw new Error("Containerless ec-3 is not supported")}return!1}}])}(Fa);function $a(e,t,r,i,n){if(r+8>t.length)return-1;if(11!==t[r]||119!==t[r+1])return-1;var a=t[r+4]>>6;if(a>=3)return-1;var s=[48e3,44100,32e3][a],o=63&t[r+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+a];if(r+l>t.length)return-1;var u=t[r+6]>>5,c=0;2===u?c+=2:(1&u&&1!==u&&(c+=2),4&u&&(c+=2));var d=(t[r+6]<<8|t[r+7])>>12-c&1,h=[2,1,2,3,3,4,4,5][u]+d,f=t[r+5]>>3,v=7&t[r+5],g=new Uint8Array([a<<6|f<<1|v>>2,(3&v)<<6|u<<3|d<<2|o>>4,o<<4&224]),p=i+n*(1536/s*9e4),m=t.subarray(r,r+l);return e.config=g,e.channelCount=h,e.samplerate=s,e.samples.push({unit:m,pts:p}),l}var Ja=function(e){function t(){return s(this,t),a(this,t,arguments)}return f(t,e),l(t,[{key:"resetInitSegment",value:function(e,r,i,n){A(t,"resetInitSegment",this,3)([e,r,i,n]),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:r,duration:n,inputTimeScale:9e4,dropped:0}}},{key:"canParse",value:function(e,t){return function(e,t){return ja(e,t)&&4<=e.length-t}(e,t)}},{key:"appendFrame",value:function(e,t,r){if(null!==this.basePTS)return Ha(e,t,r,this.basePTS,this.frameIndex)}}],[{key:"probe",value:function(e){if(!e)return!1;var t=it(e,0),r=(null==t?void 0:t.length)||0;if(t&&11===e[r]&&119===e[r+1]&&void 0!==ht(t)&&Xa(e,r)<=16)return!1;for(var i=e.length;r<i;r++)if(Wa(e,r))return je.log("MPEG Audio sync word found !"),!0;return!1}}])}(Fa),Za=/\/emsg[-/]ID3/i,es=function(){return l(function e(t,r,i){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:je;s(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.initData=void 0,this.logger=void 0,this.config=r,this.logger=n},[{key:"resetTimeStamp",value:function(){}},{key:"resetInitSegment",value:function(e,t,r,i){var n=this.videoTrack=Oa("video",1),a=this.audioTrack=Oa("audio",1),s=this.txtTrack=Oa("text",1);if(this.id3Track=Oa("id3",1),this.initData=void 0,this.timeOffset=0,null!=e&&e.byteLength){var o=this.initData=Mt(e);if(o.video){var l=o.video,u=l.id,c=l.timescale,d=l.codec,h=l.supplemental;n.id=u,n.timescale=s.timescale=c,n.codec=d,n.supplemental=h}if(o.audio){var f=o.audio,v=f.id,g=f.timescale,p=f.codec;a.id=v,a.timescale=g,a.codec=p}s.id=Et.text,n.sampleDuration=0,n.duration=a.duration=i}}},{key:"resetContiguity",value:function(){this.remainderData=null}},{key:"demux",value:function(e,t,r){this.timeOffset=t;var i=e,n=this.videoTrack,a=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=Kt(this.remainderData,e));var s=function(e){var t={valid:null,remainder:null},r=Ct(e,["moof"]);if(r.length<2)return t.remainder=e,t;var i=r[r.length-1];return t.valid=e.slice(0,i.byteOffset-8),t.remainder=e.slice(i.byteOffset-8),t}(i);this.remainderData=s.remainder,n.samples=s.valid||new Uint8Array}else n.samples=i;var o=this.extractID3Track(n,t),l=this.parseFragment(n,a,t,r);return{videoTrack:n,audioTrack:this.audioTrack,id3Track:o,textTrack:this.txtTrack,initData:this.initData,sampleData:l}}},{key:"flush",value:function(e,t){var r=this.timeOffset,i=this.videoTrack,n=this.txtTrack;i.samples=this.remainderData||new Uint8Array,this.remainderData=null;var a=this.extractID3Track(i,this.timeOffset),s=this.parseFragment(i,n,r,t);return{videoTrack:i,audioTrack:Oa(),id3Track:a,textTrack:Oa(),initData:this.initData,sampleData:s}}},{key:"parseFragment",value:function(e,t,r,i){var n=this.initData;if(n&&i){var a=function(e,t,r,i){var n=arguments.length>4&&void 0!==arguments[4]&&arguments[4],a=[];return{samples:a,sampleData:{includeSampleDetails:n,tracks:Ht(t.samples,r,i,n,{isHEVCFlavor:jt(t.codec),samples:a,timeOffset:e,timescale:t.timescale,trackId:t.id})}}}(r,e,n,this.logger,i.iframe),s=a.samples,o=a.sampleData;return t.samples=s,o}t.samples=function(e,t){var r=[],i=t.samples,n=t.timescale,a=t.id,s=!1;return Ct(i,["moof"]).map(function(o){var l=o.byteOffset-8;Ct(o,["traf"]).map(function(o){var u=Ct(o,["tfdt"]).map(function(e){var t=e[0],r=Tt(e,4);return 1===t&&(r*=Math.pow(2,32),r+=Tt(e,8)),r/n})[0];return void 0!==u&&(e=u),Ct(o,["tfhd"]).map(function(u){var c=Tt(u,4),d=16777215&Tt(u,0),h=!!(1&d),f=0,v=!!(2&d),g=!!(8&d),p=0,m=!!(16&d),y=0,k=!!(32&d),E=!h&&!!(131072&d),S=8;c===a&&(h?(f=Tt(u,S),S+=4,f*=Math.pow(2,32),f+=Tt(u,S),S+=4):E&&(f=l),v&&(S+=4),g&&(p=Tt(u,S),S+=4),m&&(y=Tt(u,S),S+=4),k&&(S+=4),"video"===t.type&&(s=jt(t.codec)),Ct(o,["trun"]).map(function(a){var o=a[0],l=16777215&Tt(a,0),u=!!(1&l),c=0,d=!!(4&l),h=!!(256&l),v=0,g=!!(512&l),m=0,k=!!(1024&l),E=!!(2048&l),S=0,T=Tt(a,4),A=8;u&&(c=Tt(a,A),A+=4),d&&(A+=4);for(var b=f+c,I=0;I<T;I++){if(h?(v=Tt(a,A),A+=4):v=p,g?(m=Tt(a,A),A+=4):m=y,k&&(A+=4),E&&(S=0===o?Tt(a,A):It(a,A),A+=4),t.type===fe)for(var R=0;R<m;){var L=Tt(i,b);qt(s,i[b+=4])&&Wt(i.subarray(b,b+L),s?2:1,e+S/n,r),b+=L,R+=L+4}e+=v/n}}))})})}),r}(r,e)}},{key:"extractID3Track",value:function(e,t){var r=this,i=this.id3Track;if(e.samples.length){var n=Ct(e.samples,["emsg"]);n&&n.forEach(function(e){var n=function(e){var t,r=e[0],i="",n="",a=0,s=0,o=0,l=0,u=4;if(0===r){var c=bt(e,u),d=null!==c?bt(e,u+c.length):null;null!==c&&null!==d?(i=c,n=d,a=Tt(e,u+=c.length+d.length),s=Tt(e,u+=4),o=Tt(e,u+=4),l=Tt(e,u+=4),u+=4):(je.warn("Unterminated ".concat(null===c?"scheme_id_uri":"value"," in parsing emsg box: version 0 box ends inside a string, dropping all of its fields")),u=e.length)}else if(1===r){a=Tt(e,u);var h=Tt(e,u+=4),f=Tt(e,u+=4);u+=4,t=Math.pow(2,32)*h+f,ee(t)||(t=Number.MAX_SAFE_INTEGER,je.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=Tt(e,u),l=Tt(e,u+=4);var v=bt(e,u+=4),g=null!==v?bt(e,u+v.length):null;null!==v&&(i=v,u+=v.length),null!==g?(n=g,u+=g.length):(je.warn("Unterminated ".concat(null===v?"scheme_id_uri":"value"," in parsing emsg box: version 1 box ends inside a string, dropping its ").concat(null===v?"strings and payload":"value and payload")),u=e.length)}return{schemeIdUri:i,value:n,timeScale:a,presentationTime:t,presentationTimeDelta:s,eventDuration:o,id:l,payload:e.subarray(u,e.byteLength)}}(e);if(Za.test(n.schemeIdUri)){var a=ts(n,t),s=4294967295===n.eventDuration?Number.POSITIVE_INFINITY:n.eventDuration/n.timeScale;s<=.001&&(s=Number.POSITIVE_INFINITY);var o=n.payload;i.samples.push({data:o,len:o.byteLength,dts:a,pts:a,type:xa.emsg,duration:s})}else if(r.config.enableEmsgKLVMetadata){var l=r.config.emsgKLVSchemaUri||xa.misbklv;if(n.schemeIdUri.startsWith(l)){var u=ts(n,t);i.samples.push({data:n.payload,len:n.payload.byteLength,dts:u,pts:u,type:xa.misbklv,duration:Number.POSITIVE_INFINITY})}}})}return i}},{key:"demuxSampleAes",value:function(e,t,r){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}},{key:"destroy",value:function(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0,this.initData=void 0}}],[{key:"probe",value:function(e){return function(e,t){for(var r=e.byteLength,i=0;i<r;){var n=Tt(e,i);if(n>8&&Tt(e,i+4)===kt[t])return!0;i=n>1?i+n:r}return!1}(e,"moof")}}])}();function ts(e,t){return Z(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}var rs=function(){return l(function e(){s(this,e),this.VideoSample=null},[{key:"createVideoSample",value:function(e,t,r){return{key:e,frame:!1,pts:t,dts:r,units:[],length:0}}},{key:"getLastNalUnit",value:function(e){var t,r,i=this.VideoSample;if(i&&0!==i.units.length||(i=e[e.length-1]),null!=(t=i)&&t.units){var n=i.units;r=n[n.length-1]}return r}},{key:"pushAccessUnit",value:function(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){var r=t.samples,i=r.length;if(!i)return void t.dropped++;var n=r[i-1];e.pts=n.pts,e.dts=n.dts}t.samples.push(e)}}},{key:"parseNALu",value:function(e,t,r){var i=t.byteLength;if(0===i)return[];var n=e.naluState||0,a=-1===n?0:n,s=[],o=0,l=0,u=-1,c=0;for(-1===n&&(u=0,c=this.getNALuType(t,0),l=1);l<i;){var d=t.indexOf(1,l);if(-1===d)break;l=d+1;for(var h=d;h>0&&0===t[h-1];)h--;if(!(d-h+(0===h?a:0)<2)){if(u>=0)s.push({data:t.subarray(u,h),type:c});else{var f=this.getLastNalUnit(e.samples);f&&(h>0?f.data=Kt(f.data,t.subarray(0,h)):a>0&&(f.data=f.data.subarray(0,f.data.byteLength-a)),f.state=0)}if(!(l<i)){o=-1,u=-1;break}u=l,c=this.getNALuType(t,l)}}if(-1!==o){for(var v=i;v>0&&0===t[v-1];)v--;o=i-v+(0===v?a:0)}if(u>=0)s.push({data:t.subarray(u),type:c,state:o});else if(0===s.length&&-1!==o){var g=this.getLastNalUnit(e.samples);g&&(g.data=Kt(g.data,t),g.state=o)}return e.naluState=o,s}}])}(),is=function(){return l(function e(t){s(this,e),this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0},[{key:"loadWord",value:function(){var e=this.data,t=this.bytesAvailable,r=e.byteLength-t,i=new Uint8Array(4),n=Math.min(4,t);if(0===n)throw new Error("no bytes available");i.set(e.subarray(r,r+n)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*n,this.bytesAvailable-=n}},{key:"skipBits",value:function(e){var t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,e-=(t=e>>3)<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}},{key:"readBits",value:function(e){var t=Math.min(this.bitsAvailable,e),r=this.word>>>32-t;if(e>32&&je.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return(t=e-t)>0&&this.bitsAvailable?r<<t|this.readBits(t):r}},{key:"skipLZ",value:function(){var e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}},{key:"skipUEG",value:function(){this.skipBits(1+this.skipLZ())}},{key:"skipEG",value:function(){this.skipBits(1+this.skipLZ())}},{key:"readUEG",value:function(){var e=this.skipLZ();return this.readBits(e+1)-1}},{key:"readEG",value:function(){var e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}},{key:"readBoolean",value:function(){return 1===this.readBits(1)}},{key:"readUByte",value:function(){return this.readBits(8)}}])}(),ns=function(e){function t(){return s(this,t),a(this,t,arguments)}return f(t,e),l(t,[{key:"parsePES",value:function(e,t,r,i,n){var a,s=this,o=n.iframe,l=this.parseNALu(e,r.data,i),u=this.VideoSample,c=!1;r.data=null,u&&l.length&&!e.audFound&&(this.pushAccessUnit(u,e),u=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),l.forEach(function(i){var n,l;switch(i.type){case 1:if(o)break;var d=!1;a=!0;var h,f=i.data;if(c&&f.length>4){var v=s.readSliceType(f);2!==v&&4!==v&&7!==v&&9!==v||(d=!0)}if(d)null!=(h=u)&&h.frame&&!u.key&&(s.pushAccessUnit(u,e),u=s.VideoSample=null);u||(u=s.VideoSample=s.createVideoSample(!0,r.pts,r.dts)),u.frame=!0,u.key=d;break;case 5:a=!0,null!=(n=u)&&n.frame&&!u.key&&(s.pushAccessUnit(u,e),u=s.VideoSample=null),u||(u=s.VideoSample=s.createVideoSample(!0,r.pts,r.dts)),u.key=!0,u.frame=!0;break;case 6:if(o)break;a=!0,Wt(i.data,1,r.pts,t.samples);break;case 7:var g,p;a=!0,c=!0;var m=i.data,y=s.readSPS(m);if(!e.sps||e.width!==y.width||e.height!==y.height||(null==(g=e.pixelRatio)?void 0:g[0])!==y.pixelRatio[0]||(null==(p=e.pixelRatio)?void 0:p[1])!==y.pixelRatio[1]){e.width=y.width,e.height=y.height,e.pixelRatio=y.pixelRatio,e.sps=[m];for(var k=m.subarray(1,4),E="avc1.",S=0;S<3;S++){var T=k[S].toString(16);T.length<2&&(T="0"+T),E+=T}e.codec=E}break;case 8:a=!0,e.pps=[i.data];break;case 9:a=!0,e.audFound=!0,null!=(l=u)&&l.frame&&(s.pushAccessUnit(u,e),u=null),u||(u=s.VideoSample=s.createVideoSample(!1,r.pts,r.dts));break;case 12:a=!0;break;default:a=!1}u&&a&&u.units.push(i)}),i&&u&&(this.pushAccessUnit(u,e),this.VideoSample=null)}},{key:"getNALuType",value:function(e,t){return 31&e[t]}},{key:"readSliceType",value:function(e){var t=new is(e);return t.readUByte(),t.readUEG(),t.readUEG()}},{key:"skipScalingList",value:function(e,t){for(var r=8,i=8,n=0;n<e;n++)0!==i&&(i=(r+t.readEG()+256)%256),r=0===i?r:i}},{key:"readSPS",value:function(e){var t,r,i,n=new is(e),a=0,s=0,o=0,l=0,u=n.readUByte.bind(n),c=n.readBits.bind(n),d=n.readUEG.bind(n),h=n.readBoolean.bind(n),f=n.skipBits.bind(n),v=n.skipEG.bind(n),g=n.skipUEG.bind(n),p=this.skipScalingList.bind(this);u();var m=u();if(c(5),f(3),u(),g(),100===m||110===m||122===m||244===m||44===m||83===m||86===m||118===m||128===m){var y=d();if(3===y&&f(1),g(),g(),f(1),h())for(r=3!==y?8:12,i=0;i<r;i++)h()&&p(i<6?16:64,n)}g();var k=d();if(0===k)d();else if(1===k)for(f(1),v(),v(),t=d(),i=0;i<t;i++)v();g(),f(1);var E=d(),S=d(),T=c(1);0===T&&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*(E+1)-2*a-2*s),height:(2-T)*(S+1)*16-(T?2:4)*(o+l),pixelRatio:A}}}])}(rs),as=function(e){function t(){var e;s(this,t);for(var r=arguments.length,i=new Array(r),n=0;n<r;n++)i[n]=arguments[n];return(e=a(this,t,[].concat(i))).initVPS=null,e}return f(t,e),l(t,[{key:"parsePES",value:function(e,t,r,i){var n,a=this,s=this.parseNALu(e,r.data,i),o=this.VideoSample,l=!1;r.data=null;var u=function(e){return o=a.VideoSample=a.createVideoSample(e,r.pts,r.dts)};s.forEach(function(i,s){var c,d;if(a.startsNewAccessUnit(o,e,i,s)){a.pushAccessUnit(o,e);var h=i.type>=16&&i.type<=23;o=u(h),l=!1}switch(i.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:o||(o=u(!1)),o.frame=!0,n=!0;break;case 16:case 17:case 18:case 21:case 22:case 23:var f;if(n=!0,l)null!=(f=o)&&f.frame&&!o.key&&(a.pushAccessUnit(o,e),o=a.VideoSample=null);o||(o=u(!0)),o.key=!0,o.frame=!0;break;case 19:case 20:n=!0,null!=(c=o)&&c.frame&&!o.key&&(a.pushAccessUnit(o,e),o=a.VideoSample=null),o||(o=u(!0)),o.key=!0,o.frame=!0;break;case 39:n=!0,Wt(i.data,2,r.pts,t.samples);break;case 32:n=!0,e.vps||("object"!==R(e.params)&&(e.params={}),e.params=Ae(e.params,a.readVPS(i.data)),a.initVPS=i.data),e.vps=[i.data];break;case 33:if(n=!0,l=!0,void 0===e.vps||e.vps[0]===a.initVPS||void 0===e.sps||a.matchSPS(e.sps[0],i.data)||(a.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){var v=a.readSPS(i.data);for(var g in e.width=v.width,e.height=v.height,e.pixelRatio=v.pixelRatio,e.codec=v.codecString,e.sps=[],"object"!==R(e.params)&&(e.params={}),v.params)e.params[g]=v.params[g]}a.pushParameterSet(e.sps,i.data,e.vps),o||(o=u(!1));break;case 34:if(n=!0,"object"===R(e.params)){if(!e.pps){e.pps=[];var p=a.readPPS(i.data);for(var m in p)e.params[m]=p[m]}a.pushParameterSet(e.pps,i.data,e.vps)}break;case 35:n=!0,e.audFound=!0,null!=(d=o)&&d.frame&&(a.pushAccessUnit(o,e),o=null),o||(o=u(!1));break;default:n=!1}o&&n&&o.units.push(i)}),i&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}},{key:"pushParameterSet",value:function(e,t,r){(r&&r[0]===this.initVPS||!r&&!e.length)&&e.push(t)}},{key:"startsNewAccessUnit",value:function(e,t,r,i){if(!e)return!1;if(!t.audFound&&0===i)return!0;if(!e.frame)return!1;var n=r.type,a=r.data;return!!(n>=32&&n<=35||39===n||n>=41&&n<=44||n>=48&&n<=55)||n<=31&&a.length>2&&!!(128&a[2])}},{key:"getNALuType",value:function(e,t){return(126&e[t])>>>1}},{key:"ebsp2rbsp",value:function(e){for(var t=new Uint8Array(e.byteLength),r=0,i=0;i<e.byteLength;i++)i>=2&&3===e[i]&&0===e[i-1]&&0===e[i-2]||(t[r]=e[i],r++);return new Uint8Array(t.buffer,0,r)}},{key:"pushAccessUnit",value:function(e,r){A(t,"pushAccessUnit",this,3)([e,r]),this.initVPS&&(this.initVPS=null)}},{key:"readVPS",value:function(e){var t=new is(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 is(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);var r=t.readBits(3);t.readBoolean();for(var i=t.readBits(2),n=t.readBoolean(),a=t.readBits(5),s=t.readUByte(),o=t.readUByte(),l=t.readUByte(),u=t.readUByte(),c=t.readUByte(),d=t.readUByte(),h=t.readUByte(),f=t.readUByte(),v=t.readUByte(),g=t.readUByte(),p=t.readUByte(),m=[],y=[],k=0;k<r;k++)m.push(t.readBoolean()),y.push(t.readBoolean());if(r>0)for(var E=r;E<8;E++)t.readBits(2);for(var S=0;S<r;S++)m[S]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),y[S]&&t.readUByte();t.readUEG();var T=t.readUEG();3==T&&t.skipBits(1);var A=t.readUEG(),b=t.readUEG(),I=t.readBoolean(),R=0,L=0,P=0,w=0;I&&(R+=t.readUEG(),L+=t.readUEG(),P+=t.readUEG(),w+=t.readUEG());for(var C=t.readUEG(),D=t.readUEG(),_=t.readUEG(),M=t.readBoolean()?0:r;M<=r;M++)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 x=0;x<4;x++)for(var O=0;O<(3===x?2:6);O++){if(t.readBoolean()){var F=Math.min(64,1<<4+(x<<1));x>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,V=0;V<B;V++){var G=!1;if(0!==V&&(G=t.readBoolean()),G){V===B&&t.readUEG(),t.readBoolean(),t.readUEG();for(var H=0,K=0;K<=U;K++){var j=t.readBoolean(),q=!1;j||(q=t.readBoolean()),(j||q)&&H++}U=H}else{var W=t.readUEG(),Y=t.readUEG();U=W+Y;for(var z=0;z<W;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,re=!0,ie=1,ne=0;t.readBoolean(),t.readBoolean();if(t.readBoolean()){if(t.readBoolean()){var ae=t.readUByte();ae>0&&ae<16?(ee=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][ae-1],te=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][ae-1]):255===ae&&(ee=t.readBits(16),te=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean())t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte());if(t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean())if(ie=t.readBits(32),ne=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean()){var se=t.readBoolean(),oe=t.readBoolean(),le=!1;(se||oe)&&((le=t.readBoolean())&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),le&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(var ue=0;ue<=r;ue++){var ce=!1;(re=t.readBoolean())||t.readBoolean()?t.readEG():ce=t.readBoolean();var de=ce?1:t.readUEG()+1;if(se)for(var he=0;he<de;he++)t.readUEG(),t.readUEG(),le&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(oe)for(var fe=0;fe<de;fe++)t.readUEG(),t.readUEG(),le&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),Z=t.readUEG())}var ve=A,ge=b;if(I){var pe=1,me=1;1===T?pe=me=2:2==T&&(pe=2),ve=A-pe*L-pe*R,ge=b-me*w-me*P}for(var ye=i?["A","B","C"][i]:"",ke=s<<24|o<<16|l<<8|u,Ee=0,Se=0;Se<32;Se++)Ee=(Ee|(ke>>Se&1)<<31-Se)>>>0;var Te=Ee.toString(16);1===a&&"2"===Te&&(Te="6");var Ae=n?"H":"L";return{codecString:"hvc1.".concat(ye).concat(a,".").concat(Te,".").concat(Ae).concat(p,".B0"),params:{general_tier_flag:n,general_profile_idc:a,general_profile_space:i,general_profile_compatibility_flags:[s,o,l,u],general_constraint_indicator_flags:[c,d,h,f,v,g],general_level_idc:p,bit_depth:C+8,bit_depth_luma_minus8:C,bit_depth_chroma_minus8:D,min_spatial_segmentation_idc:Z,chroma_format_idc:T,frame_rate:{fixed:re,fps:ne/ie}},width:ve,height:ge,pixelRatio:[ee,te]}}},{key:"readPPS",value:function(e){var t=new is(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);var r=t.readBoolean(),i=t.readBoolean(),n=1;return i&&r?n=0:i?n=3:r&&(n=2),{parallelismType:n}}},{key:"matchSPS",value:function(e,t){return pt(e).substring(3)===pt(t).substring(3)}}])}(rs),ss=188,os=function(){function e(t,r,i,n){s(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._klvPid=-1,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.videoIntegrityChecker=null,this.observer=t,this.config=r,this.typeSupported=i,this.logger=n,this.videoParser=null}return l(e,[{key:"resetInitSegment",value:function(t,r,i,n,a,s){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=e.createTrack("video"),this._videoTrack.duration=n,this.videoIntegrityChecker="skip"===this.config.handleMpegTsVideoIntegrityErrors?new gs(this.logger):null,this._audioTrack=e.createTrack("audio",n),this._id3Track=e.createTrack("id3"),this._txtTrack=e.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=r,this.videoCodec=i,t&&this.demux(t,0,s,"SAMPLE-AES"===(null==a?void 0:a.method))}},{key:"resetTimeStamp",value:function(){}},{key:"resetContiguity",value:function(){var e=this._audioTrack,t=this._videoTrack,r=this._id3Track;e&&(e.pesData=null),t&&(t.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.remainderData=null}},{key:"demux",value:function(t,r,i){var n,a=arguments.length>3&&void 0!==arguments[3]&&arguments[3],s=arguments.length>4&&void 0!==arguments[4]&&arguments[4];a||(this.sampleAes=null);var o=this._videoTrack,l=this.videoIntegrityChecker,u=this._audioTrack,c=this._id3Track,d=this._txtTrack,h=i.iframe,f=o.pid,v=o.pesData,g=u.pid,p=c.pid,m=this._klvPid,y=u.pesData,k=c.pesData,E=null,S=null,T=this.pmtParsed,A=this._pmtId,b=t.length;if(this.remainderData&&(b=(t=Kt(this.remainderData,t)).length,this.remainderData=null),b<ss&&!s)return this.remainderData=t,{audioTrack:u,videoTrack:o,id3Track:c,textTrack:d};var I=Math.max(0,e.syncOffset(t));(b-=(b-I)%ss)<t.byteLength&&!s&&(this.remainderData=new Uint8Array(t.buffer,b,t.buffer.byteLength-b));for(var R=0,L=I;L<b;L+=ss)if(71===t[L]){var P=!!(64&t[L+1]),w=ls(t,L),C=void 0;if((48&t[L+3])>>4>1){if((C=L+5+t[L+4])===L+ss)continue}else C=L+4;switch(w){case f:P&&(!v||null!=l&&l.isCorrupted||!(n=fs(v,this.logger))||(this.readyVideoParser(o.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(o,d,n,!1,i)),v={data:[],size:0},null==l||l.reset(f)),null==l||l.handlePacket(t.subarray(L)),v&&(v.data.push(t.subarray(C,L+ss)),v.size+=L+ss-C);break;case g:if(h)break;if(P){if(y&&(n=fs(y,this.logger)))switch(u.segmentCodec){case"aac":this.parseAACPES(u,n,i);break;case"mp3":this.parseMPEGPES(u,n);break;case"ac3":this.parseAC3PES(u,n)}y={data:[],size:0}}y&&(y.data.push(t.subarray(C,L+ss)),y.size+=L+ss-C);break;case p:if(h)break;P&&(k&&(n=fs(k,this.logger))&&this.parseID3PES(c,n),k={data:[],size:0}),k&&(k.data.push(t.subarray(C,L+ss)),k.size+=L+ss-C);break;case m:if(h)break;P&&(E&&(n=fs(E,this.logger))&&this.parseKlvPES(c,n),E={data:[],size:0}),E&&(E.data.push(t.subarray(C,L+ss)),E.size+=L+ss-C);break;case 0:P&&(C+=t[C]+1),A=this._pmtId=us(t,C);break;case A:P&&(C+=t[C]+1);var D=cs(t,C,this.typeSupported,a,this.observer,this.logger,this.config,i);(f=D.videoPid)>0&&(o.pid=f,o.segmentCodec=D.segmentVideoCodec),(g=D.audioPid)>0&&(u.pid=g,u.segmentCodec=D.segmentAudioCodec),(p=D.id3Pid)>0&&(c.pid=p),(m=D.klvPid)>0&&(this._klvPid=m),null===S||T||(this.logger.warn("MPEG-TS PMT found at ".concat(L," after unknown PID '").concat(S,"'. Backtracking to sync byte @").concat(I," to parse all TS packets.")),S=null,L=I-188),T=this.pmtParsed=!0;break;case 17:case 8191:break;default:S=w}}else R++;R>0&&ds(this.observer,new Error("Found ".concat(R," TS packet/s that do not start with 0x47")),i,void 0,this.logger),o.pesData=v,u.pesData=y,c.pesData=k;var _={audioTrack:u,videoTrack:o,id3Track:c,textTrack:d};return s&&this.extractRemainingSamples(_,i),_}},{key:"flush",value:function(e,t){var r,i=this.remainderData;return this.remainderData=null,r=i?this.demux(i,0,t,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(r,t),this.sampleAes?this.decrypt(r,this.sampleAes):r}},{key:"extractRemainingSamples",value:function(e,t){var r,i=e.audioTrack,n=e.videoTrack,a=e.id3Track,s=e.textTrack,o=n.pesData,l=i.pesData,u=a.pesData,c=this.videoIntegrityChecker;if(!o||null!=c&&c.isCorrupted||!(r=fs(o,this.logger))?n.pesData=o:(this.readyVideoParser(n.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(n,s,r,!0,t),n.pesData=null)),l&&(r=fs(l,this.logger))){switch(i.segmentCodec){case"aac":this.parseAACPES(i,r,t);break;case"mp3":this.parseMPEGPES(i,r);break;case"ac3":this.parseAC3PES(i,r)}i.pesData=null}else null!=l&&l.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),i.pesData=l;u&&(r=fs(u,this.logger))?(this.parseID3PES(a,r),a.pesData=null):a.pesData=u}},{key:"demuxSampleAes",value:function(e,t,r,i){var n=this.demux(e,r,i,!0,!this.config.progressive),a=this.sampleAes=new Ya(this.observer,this.config,t);return this.decrypt(n,a)}},{key:"readyVideoParser",value:function(e){null===this.videoParser&&("avc"===e?this.videoParser=new ns:"hevc"===e&&(this.videoParser=new as))}},{key:"decrypt",value:function(e,t){return new Promise(function(r){var i=e.audioTrack,n=e.videoTrack;i.samples&&"aac"===i.segmentCodec?t.decryptAacSamples(i.samples,0,function(){n.samples?t.decryptAvcSamples(n.samples,0,0,function(){r(e)}):r(e)}):n.samples&&t.decryptAvcSamples(n.samples,0,0,function(){r(e)})})}},{key:"destroy",value:function(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0,this.videoIntegrityChecker=null}},{key:"parseAACPES",value:function(e,t,r){var i,n,a,s=0,o=this.aacOverFlow,l=t.data;if(o){this.aacOverFlow=null;var u=o.missing,c=o.sample.unit.byteLength;if(-1===u)l=Kt(o.sample.unit,l);else{var d=c-u;o.sample.unit.set(l.subarray(0,u),d),e.samples.push(o.sample),s=o.missing}}for(i=s,n=l.length;i<n-1&&!wa(l,i);i++);if(i!==s){var h,f=i<n-1;if(h=f?"AAC PES did not start with ADTS header,offset:".concat(i):"No ADTS header found in AAC PES",ds(this.observer,new Error(h),r,f,this.logger),!f)return}if(Da(e,this.observer,l,i,this.audioCodec),void 0!==t.pts)a=t.pts;else{if(!o)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");var v=_a(e.samplerate);a=o.sample.pts+v}for(var g,p=0;i<n;){if(i+=(g=Ma(e,l,i,a,p)).length,g.missing){this.aacOverFlow=g;break}for(p++;i<n-1&&!wa(l,i);i++);}}},{key:"parseMPEGPES",value:function(e,t){var r=t.data,i=r.length,n=0,a=0,s=t.pts;if(void 0!==s)for(;a<i;)if(qa(r,a)){var o=Ha(e,r,a,s,n);if(!o)break;a+=o.length,n++}else a++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}},{key:"parseAC3PES",value:function(e,t){var r=t.data,i=t.pts;if(void 0!==i)for(var n,a=r.length,s=0,o=0;o<a&&(n=$a(e,r,o,i,s++))>0;)o+=n;else this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS")}},{key:"parseID3PES",value:function(e,t){if(void 0!==t.pts){var r=Ae({},t,{type:this._videoTrack?xa.emsg:xa.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(r)}else this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS")}},{key:"parseKlvPES",value:function(e,t){var r,i=null!=(r=t.pts)?r:t.dts;if(void 0!==i){var n=t.data;if(n.length<16)this.logger.warn("[tsdemuxer]: KLV PES payload too short");else for(var a=0;a<n.length;){var s;if(a+16>n.length)break;var o=a;if((a+=16)>=n.length)break;var l=n[a];a+=1;var u=0;if(128&l){var c=127&l;if(0===c||c>4||a+c>n.length){this.logger.warn("[tsdemuxer]: Invalid KLV length encoding");break}for(var d=0;d<c;d++)u=u<<8|n[a+d];a+=c}else u=l;if(a+u>n.length){this.logger.warn("[tsdemuxer]: KLV value extends beyond PES payload");break}var h=a+u,f=n.subarray(o,h),v={data:f,len:f.byteLength,pts:i,dts:null!=(s=t.dts)?s:i,type:xa.misbklv,duration:Number.POSITIVE_INFINITY};e.samples.push(v),a=h}}else this.logger.warn("[tsdemuxer]: KLV PES unknown PTS and DTS")}}],[{key:"probe",value:function(t,r){var i=e.syncOffset(t);return i>0&&r.warn("MPEG2-TS detected but first sync word found @ offset ".concat(i)),-1!==i}},{key:"syncOffset",value:function(e){for(var t=e.length,r=Math.min(940,t-ss)+1,i=0;i<r;){for(var n=!1,a=-1,s=0,o=i;o<t;o+=ss){if(71!==e[o]||t-o!==ss&&71!==e[o+ss]){if(s)return-1;break}if(s++,-1===a&&0!==(a=o)&&(r=Math.min(a+18612,e.length-ss)+1),n||(n=0===ls(e,o)),n&&s>1&&(0===a&&s>2||o+ss>r))return a}i++}return-1}},{key:"createTrack",value:function(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:Et[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}}])}();function ls(e,t){return((31&e[t+1])<<8)+e[t+2]}function us(e,t){return(31&e[t+10])<<8|e[t+11]}function cs(e,t,r,i,n,a,s,o){var l={audioPid:-1,videoPid:-1,id3Pid:-1,klvPid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},u=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t<u;){var c=ls(e,t),d=(15&e[t+3])<<8|e[t+4];switch(e[t]){case 207:if(!i){hs("ADTS AAC",a);break}case 15:-1===l.audioPid&&(l.audioPid=c);break;case 21:-1===l.id3Pid&&(l.id3Pid=c);break;case 219:if(!i){hs("H.264",a);break}case 27:-1===l.videoPid&&(l.videoPid=c);break;case 3:case 4:r.mpeg||r.mp3?-1===l.audioPid&&(l.audioPid=c,l.segmentAudioCodec="mp3"):a.log("MPEG audio found, not supported in this browser");break;case 193:if(!i){hs("AC-3",a);break}case 129:r.ac3?-1===l.audioPid&&(l.audioPid=c,l.segmentAudioCodec="ac3"):a.log("AC-3 audio found, not supported in this browser");break;case 6:if(d>0)for(var h=t+5,f=d;f>2;){switch(e[h]){case 106:-1===l.audioPid&&(!0!==r.ac3?a.log("AC-3 audio found, not supported in this browser for now"):(l.audioPid=c,l.segmentAudioCodec="ac3"));break;case 5:-1===l.klvPid&&s.enableEmsgKLVMetadata&&(l.klvPid=c,a.log("KLV metadata PID found: ".concat(c)))}var v=e[h+1]+2;h+=v,f-=v}break;case 194:case 135:return ds(n,new Error("Unsupported EC-3 in M2TS found"),o,void 0,a),l;case 36:-1===l.videoPid&&(l.videoPid=c,l.segmentVideoCodec="hevc",a.log("HEVC in M2TS found"))}t+=d+5}return l}function ds(e,t,r,i,n){n.warn("parsing error: ".concat(t.message)),e.emit(ne.ERROR,ne.ERROR,{type:re.MEDIA_ERROR,details:ie.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,chunkMeta:r,error:t,reason:t.message})}function hs(e,t){t.log("".concat(e," with AES-128-CBC encryption found in unencrypted stream"))}function fs(e,t){var r,i,n,a,s,o=0,l=e.data;if(!e||0===e.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=Kt(l[0],l[1]),l.splice(1,1);if(1===((r=l[0])[0]<<16)+(r[1]<<8)+r[2]){if((i=(r[4]<<8)+r[5])&&i>e.size-6)return null;var u=r[7];192&u&&(a=536870912*(14&r[9])+4194304*(255&r[10])+16384*(254&r[11])+128*(255&r[12])+(254&r[13])/2,64&u?a-(s=536870912*(14&r[14])+4194304*(255&r[15])+16384*(254&r[16])+128*(255&r[17])+(254&r[18])/2)>54e5&&(t.warn("".concat(Math.round((a-s)/9e4),"s delta between PTS and DTS, align them")),a=s):s=a);var c=(n=r[8])+9;if(e.size<=c)return null;e.size-=c;for(var d=new Uint8Array(e.size),h=0,f=l.length;h<f;h++){var v=(r=l[h]).byteLength;if(c){if(c>v){c-=v;continue}r=r.subarray(c),v-=c,c=0}d.set(r,o),o+=v}return i&&(i-=n+3),{data:d,pts:a,dts:s,len:i}}return null}var vs,gs=function(){return l(function e(t){s(this,e),this.logger=void 0,this.pid=0,this.lastContinuityCounter=-1,this.integrityState="ok",this.logger=t},[{key:"isCorrupted",get:function(){return"ok"!==this.integrityState}},{key:"reset",value:function(e){this.pid=e,this.lastContinuityCounter=-1,this.integrityState="ok"}},{key:"handlePacket",value:function(e){if(!(e.byteLength<4)){var t=ls(e,0);if(t===this.pid){var r=(48&e[3])>>4;if(0!==r){var i=15&e[3],n=this.lastContinuityCounter;this.lastContinuityCounter=i;var a=!!(1&r);if(!(!!(2&r)&&0!=e[4]&&!!(128&e[5])||n<0)){var s=a?n+1&15:n;return i!==s?(this.logger.warn("MPEG-TS Continuity Counter check failed for PID='".concat(t,"', CC=").concat(i,", Expected-CC=").concat(s," Last-CC=").concat(n)),void(this.integrityState="cc-failed")):128&e[1]?(this.logger.warn("MPEG-TS Packet had TEI flag set for PID='".concat(t,"'")),void(this.integrityState="tei-bit")):void 0}}}else this.logger.debug("Packet PID mismatch, expected ".concat(this.pid," got ").concat(t))}}}])}(),ps=function(){return l(function e(){s(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])}}}])}(),ms={video: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]),audio: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])},ys=new Uint8Array([0,0,0,0,0,0,0,0]),ks=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Es=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Ss=new Uint8Array([0,0,0,0,0,0,0,0]),Ts=new Uint8Array([0,0,0,0,0,0,0,1]),As=new Uint8Array([105,115,111,109]),bs=new Uint8Array([97,118,99,49]),Is=new Uint8Array([0,0,0,1]),Rs=function(){function e(){s(this,e)}return l(e,null,[{key:"box",value:function(e){for(var t=8,r=arguments.length,i=new Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];for(var a=i.length,s=a;a--;)t+=i[a].byteLength;var o=new Uint8Array(t);for(Rt(o,0,t),Rt(o,4,e),a=0,t=8;a<s;a++)o.set(i[a],t),t+=i[a].byteLength;return o}},{key:"hdlr",value:function(t){return e.box(kt.hdlr,ms[t])}},{key:"mdat",value:function(t){return e.box(kt.mdat,t)}},{key:"mdhd",value:function(t,r){r*=t;var i=Math.floor(r/(yt+1)),n=Math.floor(r%(yt+1));return e.box(kt.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n,85,196,0,0]))}},{key:"mdia",value:function(t){return e.box(kt.mdia,e.mdhd(t.timescale||0,t.duration||0),e.hdlr(t.type),e.minf(t))}},{key:"mfhd",value:function(t){return e.box(kt.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(kt.minf,e.box(kt.smhd,Ss),e.DINF,e.stbl(t)):e.box(kt.minf,e.box(kt.vmhd,Es),e.DINF,e.stbl(t))}},{key:"moof",value:function(t,r,i){return e.box(kt.moof,e.mfhd(t),e.traf(i,r))}},{key:"moov",value:function(t){for(var r=t.length,i=[];r--;)i[r]=e.trak(t[r]);return e.box.apply(null,[kt.moov,e.mvhd(t[0].timescale||0,t[0].duration||0)].concat(i).concat(e.mvex(t)))}},{key:"mvex",value:function(t){for(var r=t.length,i=[];r--;)i[r]=e.trex(t[r]);return e.box.apply(null,[kt.mvex].concat(i))}},{key:"mvhd",value:function(t,r){r*=t;var i=Math.floor(r/(yt+1)),n=Math.floor(r%(yt+1)),a=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return e.box(kt.mvhd,a)}},{key:"sdtp",value:function(t){var r,i,n=t.samples||[],a=new Uint8Array(4+n.length);for(r=0;r<n.length;r++)i=n[r].flags,a[r+4]=i.dependsOn<<4|i.isDependedOn<<2|i.hasRedundancy;return e.box(kt.sdtp,a)}},{key:"stbl",value:function(t){return e.box(kt.stbl,e.stsd(t),e.box(kt.stts,ys),e.box(kt.stsc,ys),e.box(kt.stsz,ks),e.box(kt.stco,ys))}},{key:"avc1",value:function(t){var r,i,n,a=[],s=[];for(r=0;r<t.sps.length;r++)n=(i=t.sps[r]).byteLength,a.push(n>>>8&255),a.push(255&n),a=a.concat(Array.prototype.slice.call(i));for(r=0;r<t.pps.length;r++)n=(i=t.pps[r]).byteLength,s.push(n>>>8&255),s.push(255&n),s=s.concat(Array.prototype.slice.call(i));var o=e.box(kt.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(kt.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(kt.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(kt.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,r=t.length;return new Uint8Array([0,0,0,0,3,23+r,0,1,0,4,15+r,64,21,0,0,0,0,0,0,0,0,0,0,0,5,r].concat(b(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(kt.mp4a,e.audioStsd(t),e.box(kt.esds,e.esds(t)))}},{key:"mp3",value:function(t){return e.box(kt[".mp3"],e.audioStsd(t))}},{key:"ac3",value:function(t){return e.box(kt["ac-3"],e.audioStsd(t),e.box(kt.dac3,t.config))}},{key:"stsd",value:function(t){var r=t.segmentCodec;if("audio"===t.type){if("aac"===r)return e.box(kt.stsd,Ts,e.mp4a(t));if("ac3"===r&&t.config)return e.box(kt.stsd,Ts,e.ac3(t));if("mp3"===r&&"mp3"===t.codec)return e.box(kt.stsd,Ts,e.mp3(t))}else{if(!t.pps||!t.sps)throw new Error("video track missing pps or sps");if("avc"===r)return e.box(kt.stsd,Ts,e.avc1(t));if("hevc"===r&&t.vps)return e.box(kt.stsd,Ts,e.hvc1(t))}throw new Error("unsupported ".concat(t.type," segment codec (").concat(r,"/").concat(t.codec,")"))}},{key:"tkhd",value:function(t){var r=t.id,i=(t.duration||0)*(t.timescale||0),n=t.width||0,a=t.height||0,s=Math.floor(i/(yt+1)),o=Math.floor(i%(yt+1));return e.box(kt.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,r>>24&255,r>>16&255,r>>8&255,255&r,0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,o>>24,o>>16&255,o>>8&255,255&o,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,n>>8&255,255&n,0,0,a>>8&255,255&a,0,0]))}},{key:"traf",value:function(t,r){var i=e.sdtp(t),n=t.id,a=Math.floor(r/(yt+1)),s=Math.floor(r%(yt+1));return e.box(kt.traf,e.box(kt.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n])),e.box(kt.tfdt,new Uint8Array([1,0,0,0,a>>24,a>>16&255,a>>8&255,255&a,s>>24,s>>16&255,s>>8&255,255&s])),e.trun(t,i.length+16+20+8+16+8+8),i)}},{key:"trak",value:function(t){return t.duration=t.duration||4294967295,e.box(kt.trak,e.tkhd(t),e.mdia(t))}},{key:"trex",value:function(t){var r=t.id;return e.box(kt.trex,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}},{key:"trun",value:function(t,r){var i,n,a,s,o,l,u=t.samples||[],c=u.length,d=12+16*c,h=new Uint8Array(d);for(r+=8+d,h.set(["video"===t.type?1:0,0,15,1,c>>>24&255,c>>>16&255,c>>>8&255,255&c,r>>>24&255,r>>>16&255,r>>>8&255,255&r],0),i=0;i<c;i++)a=(n=u[i]).duration,s=n.size,o=n.flags,l=n.cts,h.set([a>>>24&255,a>>>16&255,a>>>8&255,255&a,s>>>24&255,s>>>16&255,s>>>8&255,255&s,o.isLeading<<2|o.dependsOn,o.isDependedOn<<6|o.hasRedundancy<<4|o.paddingValue<<1|o.isNonSync,61440&o.degradPrio,15&o.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*i);return e.box(kt.trun,h)}},{key:"initSegment",value:function(t){var r=e.moov(t);return Kt(e.FTYP,r)}},{key:"hvc1",value:function(t){for(var r=t.params,i=[t.vps,t.sps,t.pps],n=new Uint8Array([1,r.general_profile_space<<6|(r.general_tier_flag?32:0)|r.general_profile_idc,r.general_profile_compatibility_flags[0],r.general_profile_compatibility_flags[1],r.general_profile_compatibility_flags[2],r.general_profile_compatibility_flags[3],r.general_constraint_indicator_flags[0],r.general_constraint_indicator_flags[1],r.general_constraint_indicator_flags[2],r.general_constraint_indicator_flags[3],r.general_constraint_indicator_flags[4],r.general_constraint_indicator_flags[5],r.general_level_idc,240|r.min_spatial_segmentation_idc>>8,255&r.min_spatial_segmentation_idc,252|r.parallelismType,252|r.chroma_format_idc,248|r.bit_depth_luma_minus8,248|r.bit_depth_chroma_minus8,0,parseInt(r.frame_rate.fps),3|r.temporal_id_nested<<2|r.num_temporal_layers<<3|(r.frame_rate.fixed?64:0),i.length]),a=n.length,s=0;s<i.length;s+=1){a+=3;for(var o=0;o<i[s].length;o+=1)a+=2+i[s][o].length}var l=new Uint8Array(a);l.set(n,0),a=n.length;for(var u=i.length-1,c=0;c<i.length;c+=1){l.set(new Uint8Array([32+c|(c===u?128:0),0,i[c].length]),a),a+=3;for(var d=0;d<i[c].length;d+=1)l.set(new Uint8Array([i[c][d].length>>8,255&i[c][d].length]),a),a+=2,l.set(i[c][d],a),a+=i[c][d].length}var h=e.box(kt.hvcC,l),f=t.width,v=t.height,g=t.pixelRatio[0],p=t.pixelRatio[1];return e.box(kt.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(kt.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(kt.pasp,new Uint8Array([g>>24,g>>16&255,g>>8&255,255&g,p>>24,p>>16&255,p>>8&255,255&p])))}}])}();vs=Rs,Rs.FTYP=vs.box(kt.ftyp,As,Is,As,bs),Rs.DINF=vs.box(kt.dinf,vs.box(kt.dref,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1])));function Ls(e,t){var r=e*t*(arguments.length>2&&void 0!==arguments[2]?arguments[2]:1);return arguments.length>3&&void 0!==arguments[3]&&arguments[3]?Math.round(r):r}function Ps(e){return Ls(e,1e3,1/9e4,arguments.length>1&&void 0!==arguments[1]&&arguments[1])}function ws(e){var t=e.baseTime,r=e.timescale,i=e.trackId;return"".concat(t/r," (").concat(t,"/").concat(r,") trackId: ").concat(i)}var Cs=8589934592;function Ds(e,t,r,i){return{duration:t,size:r,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1,paddingValue:0}}}var _s=function(e){function t(e,r,i,n){var o;return s(this,t),(o=a(this,t,["mp4-remuxer",n])).observer=void 0,o.config=void 0,o.typeSupported=void 0,o.ISGenerated=!1,o._initPTS=null,o._initDTS=null,o.nextVideoTs=null,o.nextAudioTs=null,o.videoSampleDuration=null,o.isAudioContiguous=!1,o.isVideoContiguous=!1,o.videoTrackConfig=void 0,o.observer=e,o.config=r,o.typeSupported=i,o.ISGenerated=!1,o}return f(t,e),l(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?ws(t):t," > ").concat(e?ws(e):e)),this._initPTS=this._initDTS=e}},{key:"resetNextTimestamp",value:function(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}},{key:"resetInitSegment",value:function(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}},{key:"getVideoStartPts",value:function(e){var t=!1,r=e[0].pts,i=e.reduce(function(e,i){var n=i.pts,a=n-e;return a<-4294967296&&(t=!0,a=(n=Ms(n,r))-e),a>0?e:n},r);return t&&this.debug("PTS rollover detected"),i}},{key:"remux",value:function(e,t,r,i,n,a,s,o,l){var u,c,d,h,f,v,g=n,p=n,m=!l.iframe&&e.pid>-1,y=t.pid>-1,k=t.samples.length,E=e.samples.length>0,S=s&&k>0||k>1;if((!m||E)&&(!y||S)||this.ISGenerated||s){if(this.ISGenerated){var T,A,b,I,R=this.videoTrackConfig;(R&&(t.width!==R.width||t.height!==R.height||(null==(T=t.pixelRatio)?void 0:T[0])!==(null==(A=R.pixelRatio)?void 0:A[0])||(null==(b=t.pixelRatio)?void 0:b[1])!==(null==(I=R.pixelRatio)?void 0:I[1]))||!R&&S||null===this.nextAudioTs&&E)&&this.resetInitSegment()}this.ISGenerated||(d=this.generateIS(e,t,n,a));var L,P=this.isVideoContiguous,w=-1;if(S&&(w=function(e){for(var t=0;t<e.length;t++)if(e[t].key)return t;return-1}(t.samples),!P&&this.config.forceKeyFrameOnDiscontinuity))if(v=!0,w>0){this.warn("Dropped ".concat(w," out of ").concat(k," video samples due to a missing keyframe"));var C=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(w),t.dropped+=w,L=p+=(t.samples[0].pts-C)/t.inputTimeScale}else-1===w&&(this.warn("No keyframe found out of ".concat(k," video samples")),v=!1);if(this.ISGenerated){if(E&&S&&n){var D=this.getVideoStartPts(t.samples),_=(Ms(e.samples[0].pts,D)-D)/t.inputTimeScale;g+=Math.max(0,_),p+=Math.max(0,-_)}if(E){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),d=this.generateIS(e,t,n,a)),c=this.remuxAudio(e,g,this.isAudioContiguous,a,y||S||o===de.AUDIO?p:void 0,l),S){var M=c?c.endPTS-c.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),d=this.generateIS(e,t,n,a)),u=this.remuxVideo(t,p,P,M,l)}}else S&&(u=this.remuxVideo(t,p,P,0,l));u&&(u.firstKeyFrame=w,u.independent=-1!==w,u.firstKeyFramePTS=L)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(f=xs(r,n,this._initPTS,this._initDTS)),i.samples.length&&(h=Os(i,n,this._initPTS))),{audio:c,video:u,initSegment:d,independent:v,text:h,id3:f}}},{key:"computeInitPts",value:function(e,t,r,i){var n=Math.round(r*t),a=Ms(e,n);if(a<n)for(this.log("Adjusting PTS for rollover in timeline near ".concat((n-a)/t," ").concat(i));a<n;)a+=Cs;return a-n}},{key:"generateIS",value:function(e,t,r,i){var n,a,s,o=e.samples,l=t.samples,u=this.typeSupported,c={},d=this._initPTS,h=!d||i,f="audio/mp4",v=-1;if(h&&(n=a=1/0),e.config&&o.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":u.mpeg?(f="audio/mpeg",e.codec=""):u.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}if(c.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&u.mpeg?new Uint8Array(0):Rs.initSegment([e]),metadata:{channelCount:e.channelCount}},h){v=e.id,s=e.inputTimeScale;var g=this.computeInitPts(o[0].pts,s,r,"audio");(!d||s!==d.timescale||0===r&&g<d.baseTime)&&(n=a=g)}}if(t.sps&&t.pps&&l.length){if(t.timescale=t.inputTimeScale,c.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:Rs.initSegment([t]),metadata:{width:t.width,height:t.height}},h){v=t.id,s=t.inputTimeScale;var p=this.getVideoStartPts(l),m=Ms(l[0].dts,p),y=this.computeInitPts(m,s,r,"video"),k=this.computeInitPts(p,s,r,"video");(!d||s!==d.timescale||Z(n)||0===r&&k<d.baseTime)&&(a=Math.min(a,y),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&&Z(n)?(d&&this.warn("Timestamps at playlist time: ".concat(i?"":"~").concat(r," ").concat(n/s," != initPTS: ").concat(d.baseTime/d.timescale," (").concat(d.baseTime,"/").concat(d.timescale,") trackId: ").concat(d.trackId)),this.log("Found initPTS at playlist time: ".concat(r," offset: ").concat(n/s," (").concat(n,"/").concat(s,") trackId: ").concat(v)),this._initPTS={baseTime:n,timescale:s,trackId:v},this._initDTS={baseTime:a,timescale:s,trackId:v}):n=s=void 0,{tracks:c,initPTS:n,timescale:s,trackId:v}}},{key:"remuxVideo",value:function(e,t,r,i,n){var a,s,o=e.inputTimeScale,l=e.samples,u=[],c=l.length,d=this._initPTS,h=d.baseTime*o/d.timescale,f=this.nextVideoTs,v=8,g=this.videoSampleDuration,p=Number.POSITIVE_INFINITY,m=Number.NEGATIVE_INFINITY,y=!1;if(!r||null===f){var k=h+t*o,E=l[0].pts-Ms(l[0].dts,l[0].pts);ir()&&null!==f&&Math.abs(k-E-(f+h))<15e3?r=!0:f=k-E-h}for(var S=f+h,T=0;T<c;T++){var A=l[T];A.pts=Ms(A.pts,S),A.dts=Ms(A.dts,S),A.dts<l[T>0?T-1:T].dts&&(y=!0)}y&&l.sort(function(e,t){var r=e.dts-t.dts,i=e.pts-t.pts;return r||i}),a=l[0].dts;var b=(s=l[l.length-1].dts)-a,I=b?Math.round(b/(c-1)):g||e.inputTimeScale/30;if(r){var R=a-S,L=R>I,P=R<-1;if((L||P)&&(L?this.warn("".concat((e.segmentCodec||"").toUpperCase(),": ").concat(Ps(R,!0)," ms (").concat(R,"dts) hole between fragments detected at ").concat(t.toFixed(3))):this.warn("".concat((e.segmentCodec||"").toUpperCase(),": ").concat(Ps(-R,!0)," ms (").concat(R,"dts) overlapping between fragments detected at ").concat(t.toFixed(3))),!P||S>=l[0].pts||ir())){a=S;var w=l[0].pts-R;if(L)l[0].dts=a,l[0].pts=w;else for(var C=!0,D=0;D<l.length&&!(l[D].dts>w&&C);D++){var _=l[D].pts;if(l[D].dts-=R,l[D].pts-=R,D<l.length-1){var M=l[D+1].pts;C=M<=l[D].pts==M<=_}}this.log("Video: Initial PTS/DTS adjusted: ".concat(Ps(w,!0),"/").concat(Ps(a,!0),", delta: ").concat(Ps(R,!0)," ms"))}}for(var x=0,O=0,F=a=Math.max(0,a),N=0;N<c;N++){for(var B=l[N],U=B.units,V=U.length,G=0,H=0;H<V;H++)G+=U[H].data.length;O+=G,x+=V,B.length=G,B.dts<F?(B.dts=F,F+=I/4|0||1):F=B.dts,p=Math.min(B.pts,p),m=Math.max(B.pts,m)}s=l[c-1].dts;var K,j=O+4*x+8;try{K=new Uint8Array(j)}catch(e){return void this.observer.emit(ne.ERROR,ne.ERROR,{type:re.MUX_ERROR,details:ie.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:n,error:e,bytes:j,reason:"fail allocating video mdat ".concat(j)})}Rt(K,0,j),Rt(K,4,kt.mdat);for(var q=!1,W=Number.POSITIVE_INFINITY,Y=Number.POSITIVE_INFINITY,z=Number.NEGATIVE_INFINITY,X=Number.NEGATIVE_INFINITY,Q=0;Q<c;Q++){for(var $=l[Q],J=$.units,Z=0,ee=0,te=J.length;ee<te;ee++){var ae=J[ee],se=ae.data,oe=ae.data.byteLength;Rt(K,v,oe),v+=4,K.set(se,v),v+=oe,Z+=4+oe}var le=void 0;if(Q<c-1)g=l[Q+1].dts-$.dts,le=l[Q+1].pts-$.pts;else{var ue=this.config,ce=Q>0?$.dts-l[Q-1].dts:I;if(le=Q>0?$.pts-l[Q-1].pts:I,ue.stretchShortVideoTrack&&null!==this.nextAudioTs){var de=Math.floor(ue.maxBufferHole*o),he=(i?p+i*o:this.nextAudioTs+h)-$.pts;he>de?((g=he-ce)<0?g=ce:q=!0,this.log("It is approximately ".concat(he/90," ms to the next segment; using duration ").concat(g/90," ms for the last video frame."))):g=ce}else g=ce}var fe=Math.round($.pts-$.dts);if(W=Math.min(W,g),z=Math.max(z,g),Y=Math.min(Y,le),X=Math.max(X,le),!r&&0===Q&&fe>g){var ve=Math.round(fe/I)*I;ve-fe===1&&(this.log("pad first CTS ".concat(fe," -> ").concat(ve," of sn: ").concat(n.sn)),fe=ve)}u.push(Ds($.key,g,Z,fe))}if(u.length){var ge=ir();if(ge){if(ge<70){var pe=u[0].flags;pe.dependsOn=2,pe.isNonSync=0}}else if(function(){if(void 0===Zt){var e=er.match(/Safari\/(\d+)/i);Zt=e?parseInt(e[1]):0}return Zt}()&&X-Y<z-W&&I/z<.025&&0===u[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");for(var me=a,ye=0,ke=u.length;ye<ke;ye++){var Ee=me+u[ye].duration,Se=me+u[ye].cts;if(ye<ke-1){var Te=Ee+u[ye+1].cts;u[ye].duration=Te-Se}else u[ye].duration=ye?u[ye-1].duration:I;u[ye].cts=0,me=Ee}}}var be=s+(g=q||!g?I:g);this.nextVideoTs=f=be-h,this.videoSampleDuration=g,this.isVideoContiguous=!0,n.iframe&&(1===u.length?(u[0].duration=g=n.duration*o,this.nextVideoTs=f=a+g-h):this.warn("Not adjusting IFrame duration (sample count ".concat(u.length,")")));var Ie={data1:Rs.moof(n.sn,a,Ae(e,{samples:u})),data2:K,startPTS:(p-h)/o,endPTS:(m+g-h)/o,startDTS:(a-h)/o,endDTS:f/o,type:"video",hasAudio:!1,hasVideo:!0,nb:u.length,dropped:e.dropped};return e.samples=[],e.dropped=0,Ie}},{key:"getSamplesPerFrame",value:function(e){switch(e.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}},{key:"remuxAudio",value:function(e,t,r,i,n,a){var s=e.inputTimeScale,o=s/(e.samplerate?e.samplerate:s),l=this.getSamplesPerFrame(e),u=l*o,c=this._initPTS,d="mp3"===e.segmentCodec&&this.typeSupported.mpeg,h=[],f=void 0!==n,v=e.samples,g=d?0:8,p=this.nextAudioTs||-1,m=c.baseTime*s/c.timescale,y=m+t*s;if(this.isAudioContiguous=r=r||v.length&&p>0&&(i&&Math.abs(y-(p+m))<9e3||Math.abs(Ms(v[0].pts,y)-(p+m))<20*u),v.forEach(function(e){e.pts=Ms(e.pts,y)}),!r||p<0){var k=v.length;if(v=v.filter(function(e){return e.pts>=0}),k!==v.length&&this.warn("Removed ".concat(v.length-k," of ").concat(k," samples (initPTS ").concat(m," / ").concat(s,")")),!v.length)return;p=0===n?0:i&&!f?Math.max(0,y-m):v[0].pts-m}if("aac"===e.segmentCodec)for(var E=this.config.maxAudioFramesDrift,S=0,T=p+m;S<v.length;S++){var A=v[S],b=A.pts,I=b-T,R=Math.abs(1e3*I/s);if(I<=-E*u&&f)0===S&&(this.warn("Audio frame @ ".concat((b/s).toFixed(3),"s overlaps marker by ").concat(Math.round(1e3*I/s)," ms.")),this.nextAudioTs=p=b-m,T=b);else if(I>=E*u&&R<1e4&&f){var L=Math.round(I/u);for(T=b-L*u;T<0&&L&&u;)L--,T+=u;0===S&&(this.nextAudioTs=p=T-m),this.warn("Injecting ".concat(L," audio frames @ ").concat(((T-m)/s).toFixed(3),"s due to ").concat(Math.round(1e3*I/s)," ms gap."));for(var P=0;P<L;P++){var w=ps.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=A.unit.subarray()),v.splice(S,0,{unit:w,pts:T}),T+=u,S++}}A.pts=T,T+=u}for(var C,D=null,_=null,M=0,x=v.length;x--;)M+=v[x].unit.byteLength;for(var O=0,F=v.length;O<F;O++){var N=v[O],B=N.unit,U=N.pts;if(null!==_){h[O-1].duration=Math.round((U-_)/o)}else{if(r&&"aac"===e.segmentCodec&&(U=p+m),D=U,!(M>0))return;M+=g;try{C=new Uint8Array(M)}catch(e){return void this.observer.emit(ne.ERROR,ne.ERROR,{type:re.MUX_ERROR,details:ie.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:a,error:e,bytes:M,reason:"fail allocating audio mdat ".concat(M)})}d||(Rt(C,0,M),Rt(C,4,kt.mdat))}C&&C.set(B,g);var V=B.byteLength;g+=V,h.push(Ds(!0,l,V,0)),_=U}var G=h.length;if(G){var H=h[h.length-1];p=_-m,this.nextAudioTs=p+o*H.duration;var K=d?new Uint8Array(0):Rs.moof(e.sequenceNumber++,D/o,Ae({},e,{samples:h}));e.samples=[];var j=(D-m)/s,q=this.nextAudioTs/s,W={data1:K,data2:C,startPTS:j,endPTS:q,startDTS:j,endDTS:q,type:"audio",hasAudio:!0,hasVideo:!1,nb:G};return this.isAudioContiguous=!0,W}}}])}(Be);function Ms(e,t){var r;if(null===t)return e;for(r=t<e?-8589934592:Cs;Math.abs(e-t)>4294967296;)e+=r;return e}function xs(e,t,r,i){var n=e.samples.length;if(n){for(var a=e.inputTimeScale,s=0;s<n;s++){var o=e.samples[s];o.pts=Ms(o.pts-r.baseTime*a/r.timescale,t*a)/a,o.dts=Ms(o.dts-i.baseTime*a/i.timescale,t*a)/a}var l=e.samples;return e.samples=[],{samples:l}}}function Os(e,t,r){var i=e.samples.length;if(i){for(var n=e.inputTimeScale,a=0;a<i;a++){var s=e.samples[a];s.pts=Ms(s.pts-r.baseTime*n/r.timescale,t*n)/n}e.samples.sort(function(e,t){return e.pts-t.pts});var o=e.samples;return e.samples=[],{samples:o}}}var Fs,Ns=function(e){function t(e,r,i,n){var o;return s(this,t),(o=a(this,t,["passthrough-remuxer",n])).observer=void 0,o.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.videoOnlyRemux=!1,o.decryptdata=null,o.pendingInitSegment=void 0,o.observer=e,o}return f(t,e),l(t,[{key:"destroy",value:function(){this.observer&&this.observer.removeAllListeners(),this.observer=null}},{key:"resetTimeStamp",value:function(e){this.lastEndTime=null;var t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}},{key:"resetNextTimestamp",value:function(){this.isVideoContiguous=!1,this.lastEndTime=null}},{key:"resetInitSegment",value:function(e,t,r,i){this.audioCodec=t,this.videoCodec=r,this.decryptdata=i,this.pendingInitSegment=e,this.videoOnlyRemux=!1,this.initTracks=void 0,this.initData=void 0,this.emitInitSegment=!0}},{key:"generateInitSegment",value:function(e,t,r){this.videoOnlyRemux=!1;var i=this.audioCodec,n=this.videoCodec;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);var a=this.initData=r||Mt(e),s=a.audio,o=a.video;if(t)!function(e,t){if(e&&t){var r=t.keyId;16===(null==r?void 0:r.byteLength)&&t.isCommonEncryption&&Ut(e,function(e,t){var i=e.subarray(8,24);i.some(function(e){return 0!==e})||(je.log("[eme] Patching keyId in 'enc".concat(t?"a":"v",">sinf>>tenc' box: ").concat(ft(i)," -> ").concat(ft(r))),e.set(r,8))})}}(e,t);else{var l=s||o;null!=l&&l.encrypted&&this.warn('Init segment with encrypted track with has no key ("'.concat(l.codec,'")!'))}s&&(i=Us(s,he,this)),o&&(n=Us(o,fe,this));var u={};s&&o?u.audiovideo={container:"video/mp4",codec:i+","+n,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:s?u.audio={container:"audio/mp4",codec:i,encrypted:s.encrypted,initSegment:e,id:"audio"}:o?u.video={container:"video/mp4",codec:n,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=u}},{key:"remux",value:function(e,t,r,i,n,a,s,o,l,u,c){var d,h,f=this.initPTS,v=this.lastEndTime,g={audio:void 0,video:void 0,text:void 0,id3:r,initSegment:void 0};Z(v)||(v=this.lastEndTime=n||0);var p=t.samples;if(!p.length)return g;var m=this.pendingInitSegment;m&&(this.pendingInitSegment=void 0,this.generateInitSegment(m,this.decryptdata,u));var y={initPTS:void 0,timescale:void 0,trackId:void 0},k=this.initData;if(null!=(d=k)&&d.length||(this.generateInitSegment(p),k=this.initData),null==(h=k)||!h.length)return this.warn("Failed to generate initSegment."),g;if(l.iframe&&k.audio&&k.video){var E,S,T=null==(E=this.initTracks)||null==(E=E.audiovideo)?void 0:E.initSegment,A=T?function(e){var t=Ct(e,["moov"]);if(1!==t.length||Ct(e,["moof"]).length)return null;for(var r=e.byteOffset,i=[],n=[],a=!1,s=Ct(t[0],["trak"]),o=0;o<s.length;o++){var l=s[o],u=Ct(l,["mdia","hdlr"])[0];if("vide"!==(u?pt(u.subarray(8,12)):"")){var c=Ct(l,["tkhd"])[0];if(!c)return null;var d=c[0];n.push(Tt(c,0===d?12:20)),i.push(Pt(l,r))}else a=!0}if(!a||!i.length)return null;var h=Ct(t[0],["mvex"])[0],f=0;if(h)for(var v=Ct(h,["trex"]),g=0;g<v.length;g++){var p=v[g];-1!==n.indexOf(Tt(p,4))&&(i.push(Pt(p,r)),f+=p.byteLength+8)}var m=wt(e,i),y=m.result,k=m.dropped,E=m.droppedBefore;if(Rt(y,t[0].byteOffset-r-8,t[0].byteLength+8-k),h&&f){var S=h.byteOffset-r-8;Rt(y,S-E(S),h.byteLength+8-f)}return y}(T):null;if(A)this.log("Converted muxed init segment to video-only for I-Frame playback"),this.generateInitSegment(A,this.decryptdata),null!=(S=this.initData)&&S.length&&(k=this.initData,this.emitInitSegment=!0,this.videoOnlyRemux=!0)}this.emitInitSegment&&(y.tracks=this.initTracks,g.initSegment=y,this.emitInitSegment=!1);var I=l.iframe,R=!c||I&&!c.includeSampleDetails?function(e,t,r,i){return Ht(e,t,i,!(arguments.length>4&&void 0!==arguments[4])||arguments[4])}(p,k,l,this,I):c.tracks,L=k.audio?R[k.audio.id]:null,P=k.video?R[k.video.id]:null,w=!!k.audio,C=!!k.video,D="";w&&(D+="audio"),C&&(D+="video");var _,M=Bs(P,1/0),x=Bs(L,1/0),O=Bs(P,0,!0),F=Bs(L,0,!0),N=0;P&&L&&k.audio&&(x>O||M>F)&&this.warn("audio and video track sample timestamps do not overlap. v: ".concat(M,"-").concat(O," a: ").concat(x,"-").concat(F,"}"),P,L);var B=!!L&&(!P||!f&&x<M||!!f&&f.trackId===k.audio.id),U=B?L:P;if(!U)return this.log("No media samples found in ".concat(o," ").concat(l.level," ").concat(-1===l.part?"":"part: ".concat(l.part," of")," sn: ").concat(l.sn," at playlist time: ").concat(n)),g;var V,G=p;if(P&&P.sampleCount>=1&&k.video&&l.iframe){var H,K=P.trun,j=P.start,q=1===K.length,W=K.length?q?K[0].samples:(H=K[0].samples).concat.apply(H,b(K.slice(1).map(function(e){return e.samples}))):[];if(W.length){for(var Y=K[0],z=Y,X=K.length;X--;)if(K[X].samples.length){z=K[X];break}var Q=z.lastSampleDurationOffset,$=Y.defaultSampleDurationOffset,J=Math.abs(l.duration-(O-M))>.05,ee=W.length<P.sampleCount;if(J||ee||this.videoOnlyRemux||!q){var te=ee?z.sampleOffset+z.samples.reduce(function(e,t){return e+t.size},0):void 0,re=J?l.duration:O-M,ie=function(e,t,r,i){if(void 0!==r){for(var n=e[e.length-1],a=t,s=0;s<e.length-1;s++)a-=e[s].duration;return a<=0&&(a=n.duration),n.duration=a,{durationOffset:r,value:a}}if(void 0===i)return;for(var o=Math.round(t/e.length),l=0;l<e.length;l++)e[l].duration=o;return{durationOffset:i,value:o}}(W,re*k.video.timescale,Q,$),ne=function(e,t,r,i,n){if(r<1)return null;var a=Ct(e,["moof"]);if(1!==a.length)return null;for(var s=a[0],o=e.byteOffset,l=[],u=[],c=Ct(s,["traf"]),d=!0,h=0;h<c.length;h++){var f=c[h],v=Ct(f,["tfhd"])[0];if(!v)return null;Tt(v,4)===t?(l.push(f),131072&Tt(v,0)||(d=!1)):u.push(Pt(f,o))}if(!l.length)return null;if(u.length&&!d)return null;if(void 0!==i){for(var g=r,p=0;p<l.length;p++){for(var m=l[p],y=0,k=Ct(m,["trun"]),E=0;E<k.length;E++){var S=k[E],T=Math.min(g,Tt(S,4));if(T){Rt(e,S.byteOffset-o+4,T);var A=16777215&Tt(S,0);Lt(e,S,8+(1&A?4:0)+(4&A?4:0)+T*((256&A?4:0)+(512&A?4:0)+(1024&A?4:0)+(2048&A?4:0)))}else Rt(e,S.byteOffset-o-4,kt.free);g-=T,y+=T}var b=Ct(m,["senc"])[0];b&&Rt(e,b.byteOffset-o+4,y);var I=Ct(m,["saiz"])[0];if(I){var R=4;1&(I[1]<<16|I[2]<<8|I[3])&&(R+=8);var L=I[R];R+=1,Rt(e,I.byteOffset-o+R,y),Lt(e,I,R+4+(0===L?y:0))}}var P=Ct(e,["mdat"]);if(1===P.length){var w=P[0].byteOffset-o-8;Rt(e,w,i-w)}}var C=e,D=0,_=function(){return 0};if(u.length){var M=wt(e,u);C=M.result,D=M.dropped,_=M.droppedBefore,Rt(C,s.byteOffset-o-8,s.byteLength+8-D);for(var x=0;x<l.length;x++){for(var O=l[x],F=_(O.byteOffset-o),N=Ct(O,["trun"]),B=0;B<N.length;B++){var U=N[B];1&Tt(U,0)&&Rt(C,U.byteOffset-o-F+8,Tt(U,8)-D)}if(F)for(var V=Ct(O,["saio"]),G=0;G<V.length;G++){var H=V[G],K=0===H[0]?4:8,j=1&Tt(H,0)?12:4,q=Tt(H,j);for(j+=4;q--;j+=K){var W=j+K-4;Rt(C,H.byteOffset-o-F+W,Tt(H,W)-F)}}}}if(n){var Y=n.durationOffset,z=n.value;Rt(C,Y-_(Y),z)}return void 0!==i?C.subarray(0,i-D):C}(p,k.video.id,W.length,te,ie);ne?(G=ne,V=function(e,t){for(var r=e,i=e,n=0;n<t.length;n++){var a=t[n],s=a.cts,o=a.duration;i=Math.max(i,r+(s||0)+o),r+=o}return i}(j,W)):this.warn("IFrame remux skipped (sn ".concat(l.sn,"); using native sample duration")),N=ne&&ie?re:O-M}else N=O-M}else this.warn("Could not remux IFrame track fragment (no samples in range, trun count ".concat(K.length,")")),N=O-M}else N=B?F-x:O-M;if(this.videoOnlyRemux&&G===p)return this.warn("Dropping muxed I-Frame fragment that could not be remuxed to video-only (sn: ".concat(l.sn,")")),g;var ae=U.timescale,se=U.start-n*ae,oe=B?k.audio.id:k.video.id;if(_=U.start/ae,(a||!f)&&(function(e,t,r,i){if(null===e)return!0;var n=Math.max(i,1),a=t-e.baseTime/e.timescale;return Math.abs(a-r)>=n}(f,_,n,N)||ae!==f.timescale)){var le=!1,ue=B?"audio":"video";if(f){var ce=0!==n?_/n:1+_/1;le=_>=0&&Math.abs(1-ce)<.001,this.log("".concat(ue," timestamps in track ").concat(oe," at playlist time: ").concat(a?"":"~").concat(n," maps to ").concat(_," with initPTS: ").concat(f.baseTime/f.timescale," (").concat(se/ae-f.baseTime/f.timescale,"s diff) (").concat(D,") drift estimate: ").concat(ce," ").concat(le?"(ignoring drift)":"remapping timestamps (initPTS)"))}le||(this.log("Found initPTS in ".concat(ue," track ").concat(oe," at playlist time: ").concat(n," offset: ").concat(_-n," (").concat(se,"/").concat(ae,")")),f=null,y.initPTS=se,y.timescale=ae,y.trackId=oe)}f?(y.initPTS=f.baseTime,y.timescale=f.timescale,y.trackId=f.trackId):(y.timescale&&void 0!==y.trackId&&void 0!==y.initPTS||(this.warn("Could not set initPTS"),y.initPTS=_,y.timescale=1,y.trackId=-1),this.initPTS=f={baseTime:y.initPTS,timescale:y.timescale,trackId:y.trackId});var de=_-f.baseTime/f.timescale,he=de+N,fe=C&&void 0!==(null==U?void 0:U.ptsMin)?U.ptsMin/U.timescale-f.baseTime/f.timescale:de,ve=void 0!==V&&P?V/P.timescale-f.baseTime/f.timescale:C&&null!=U&&U.ptsMax?U.ptsMax/U.timescale-f.baseTime/f.timescale:he;N>0?this.lastEndTime=he:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());var ge={data1:G,data2:void 0,startPTS:fe,startDTS:de,endPTS:ve,endDTS:he,type:D,hasAudio:w,hasVideo:C,nb:1,dropped:0,encrypted:!!k.audio&&k.audio.encrypted||!!k.video&&k.video.encrypted};g.audio=w&&!C?ge:void 0,g.video=C?ge:void 0;var pe=this.isVideoContiguous,me=null==P?void 0:P.sampleCount;if(me){var ye=P.keyFrameIndex,ke=-1!==ye;ge.nb=me,ge.dropped=0===ye||pe?0:ke?ye:me,ge.independent=ke,ge.firstKeyFrame=ye,ke&&P.keyFrameStart&&(ge.firstKeyFramePTS=(P.keyFrameStart-f.baseTime)/f.timescale),pe||(g.independent=ke),this.isVideoContiguous||(this.isVideoContiguous=ke),ge.dropped&&this.warn("fmp4 does not start with IDR: firstIDR ".concat(ye,"/").concat(me," dropped: ").concat(ge.dropped," start: ").concat(ge.firstKeyFramePTS||"NA"))}return g.initSegment=y,g.id3=xs(r,n,f,f),i.samples.length&&(g.text=Os(i,n,f)),g}}])}(Be);function Bs(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return void 0!==(null==e?void 0:e.start)?(e.start+(r?e.duration:0))/e.timescale:t}function Us(e,t,r){var i=e.codec;if(i&&i.length>4)return i;if(t===he){if("ec-3"===i||"ac-3"===i||"alac"===i)return i;if("fLaC"===i||"Opus"===i){return vr(i,!1)}return r.warn('Unhandled audio codec "'.concat(i,'" in mp4 MAP')),i||"mp4a"}return"mjpg"===i?i:(r.warn('Unhandled video codec "'.concat(i,'" in mp4 MAP')),i||"avc1")}try{Fs=self.performance.now.bind(self.performance)}catch(e){Fs=Date.now}var Vs=[{demux:es,remux:Ns},{demux:os,remux:_s},{demux:za,remux:_s},{demux:Ja,remux:_s}];Vs.splice(2,0,{demux:Qa,remux:_s});var Gs=function(){return l(function e(t,r,i,n,a,o){s(this,e),this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=t,this.typeSupported=r,this.config=i,this.id=a,this.logger=o},[{key:"configure",value:function(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}},{key:"push",value:function(e,t,r,i){var n=this;if(!this.observer)return Hs(r);var a=r.transmuxing;a.executeStart=Fs();var s=new Uint8Array(e),o=this.currentTransmuxState,l=this.transmuxConfig;i&&(this.currentTransmuxState=i);var u=i||o,c=u.contiguous,d=u.discontinuity,h=u.trackSwitch,f=u.accurateTimeOffset,v=u.timeOffset,g=u.initSegmentChange,p=l.audioCodec,m=l.videoCodec,y=l.defaultInitPts,k=l.duration,E=l.initSegmentData,S=function(e,t){var r=null;e.byteLength>0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(r=t);return r}(s,t);if(S&&Zi(S.method)){var T=this.getDecrypter(),A=en(S.method);return this.asyncResult=!0,this.decryptionPromise=T.decrypt(s,S.key.buffer,S.iv.buffer,A,r.decryptRange).then(function(e){var t=n.push(e,null,r);return n.decryptionPromise=null,t}),this.decryptionPromise}var b=this.needsProbing(d,h);if(b){var I=r.iframe&&E&&os.probe(E,this.logger)?E:s,R=this.configureTransmuxer(I);if(R)return this.logger.warn("[transmuxer] ".concat(R.message)),this.observer.emit(ne.ERROR,ne.ERROR,{type:re.MEDIA_ERROR,details:ie.FRAG_PARSING_ERROR,fatal:!1,error:R,reason:R.message}),a.executeEnd=Fs(),Hs(r)}(d||h||g||b)&&this.resetInitSegment(E,p,m,k,t,r),(d||g||b)&&this.resetInitialTimestamp(y),c||this.resetContiguity();var L=this.transmux(s,S,v,f,r);this.asyncResult=Ks(L);var P=this.currentTransmuxState;return P.contiguous=!0,P.discontinuity=!1,P.trackSwitch=!1,a.executeEnd=Fs(),L}},{key:"flush",value:function(e){var t=this,r=e.transmuxing;r.executeStart=Fs();var i=this.decrypter,n=this.currentTransmuxState,a=this.decryptionPromise;if(a)return this.asyncResult=!0,a.then(function(){return t.flush(e)});var s=[],o=n.timeOffset;if(i){var l=i.flush();l&&s.push(this.push(l.buffer,null,e))}var u=this.demuxer,c=this.remuxer;if(!u||!c){r.executeEnd=Fs();var d=[Hs(e)];return this.asyncResult?Promise.resolve(d):d}var h=u.flush(o,e);return Ks(h)?(this.asyncResult=!0,h.then(function(r){return t.flushRemux(s,r,e),s})):(this.flushRemux(s,h,e),this.asyncResult?Promise.resolve(s):s)}},{key:"flushRemux",value:function(e,t,r){if(this.remuxer){var i=t.audioTrack,n=t.videoTrack,a=t.id3Track,s=t.textTrack,o=this.currentTransmuxState,l=o.accurateTimeOffset,u=o.timeOffset;this.logger.log("[transmuxer.ts]: Flushed ".concat(this.id," sn: ").concat(r.sn).concat(r.part>-1?" part: "+r.part:""," of ").concat(this.id," playlist ").concat(r.level));var c=this.remuxer.remux(i,n,a,s,u,l,!0,this.id,r,t.initData,t.sampleData);e.push({remuxResult:c,chunkMeta:r}),r.transmuxing.executeEnd=Fs()}}},{key:"resetInitialTimestamp",value:function(e){var t=this.demuxer,r=this.remuxer;t&&r&&(t.resetTimeStamp(e),r.resetTimeStamp(e))}},{key:"resetContiguity",value:function(){var e=this.demuxer,t=this.remuxer;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())}},{key:"resetInitSegment",value:function(e,t,r,i,n,a){var s=this.demuxer,o=this.remuxer;s&&o&&(s.resetInitSegment(e,t,r,i,n,a),o.resetInitSegment(e,t,r,n))}},{key:"destroy",value:function(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0),this.observer&&this.observer.removeAllListeners(),this.decryptionPromise=null,this.decrypter=this.observer=void 0,this.logger=this.config=this.probe=void 0}},{key:"transmux",value:function(e,t,r,i,n){return"SAMPLE-AES"===(null==t?void 0:t.method)?this.transmuxSampleAes(e,t,r,i,n):this.transmuxUnencrypted(e,r,i,n)}},{key:"transmuxUnencrypted",value:function(e,t,r,i){var n=this.demuxer,a=this.remuxer;if(!n||!a)return Hs(i);var s=n.demux(e,t,i,!1,!this.config.progressive),o=s.audioTrack,l=s.videoTrack,u=s.id3Track,c=s.textTrack;return{remuxResult:a.remux(o,l,u,c,t,r,!1,this.id,i,s.initData,s.sampleData),chunkMeta:i}}},{key:"transmuxSampleAes",value:function(e,t,r,i,n){var a=this;return this.demuxer?this.demuxer.demuxSampleAes(e,t,r,n).then(function(e){return{remuxResult:a.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,r,i,!1,a.id,n,e.initData,e.sampleData),chunkMeta:n}}):Promise.reject(new Error("no demuxer"))}},{key:"configureTransmuxer",value:function(e){var t=this.config,r=this.observer,i=this.typeSupported;if(r){var n;try{for(var a=0,s=Vs.length;a<s;a++){var o;if(null!=(o=Vs[a].demux)&&o.probe(e,this.logger)){n=Vs[a];break}}}catch(e){return e}if(!n)return new Error("Failed to find demuxer by probing fragment data");var l=this.demuxer,u=this.remuxer,c=n.demux,d=n.remux;l&&l instanceof c||(this.logger.log("Using ".concat(c.name)),this.demuxer=new c(r,t,i,this.logger),this.probe=c.probe),u&&u instanceof d||(this.logger.log("Using ".concat(d.name)),this.remuxer=new d(r,t,i,this.logger))}}},{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 Pi(this.config)),e}}])}();var Hs=function(e){return{remuxResult:{},chunkMeta:e}};function Ks(e){return"then"in e&&e.then instanceof Function}var js=l(function e(t,r,i,n,a){s(this,e),this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=t,this.videoCodec=r,this.initSegmentData=i,this.duration=n,this.defaultInitPts=a||null}),qs=l(function e(t,r,i,n,a,o){s(this,e),this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=t,this.contiguous=r,this.accurateTimeOffset=i,this.trackSwitch=n,this.timeOffset=a,this.initSegmentChange=o}),Ws=0,Ys=function(){return l(function e(t,r,i,n){var a=this;s(this,e),this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Ws++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=function(e){var t=e.data,r=a.hls;if(r&&null!=t&&t.event&&t.instanceNo===a.instanceNo)switch(t.event){case"init":var i,n=null==(i=a.workerContext)?void 0:i.objectURL;n&&self.URL.revokeObjectURL(n);break;case"transmuxComplete":a.handleTransmuxComplete(t.data);break;case"flush":a.onFlush(t.data);break;case"workerLog":r.logger[t.data.logType]&&r.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=a.frag,t.data.part=a.part,t.data.id=a.id,r.trigger(t.event,t.data)}},this.onWorkerError=function(e){if(a.hls){var t=new Error("".concat(e.message," (").concat(e.filename,":").concat(e.lineno,")"));a.hls.config.enableWorker=!1,a.hls.logger.warn('Error in "'.concat(a.id,'" Web Worker, fallback to inline')),a.hls.trigger(ne.ERROR,{type:re.OTHER_ERROR,details:ie.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:t})}};var o=t.config;this.hls=t,this.id=r,this.useWorker=!!o.enableWorker,this.onTransmuxComplete=i,this.onFlush=n;var l=function(e,t){(t=t||{}).frag=a.frag||void 0,e===ne.ERROR&&(t.parent=a.id,t.part=a.part,a.error=t.error),a.hls.trigger(e,t)};this.observer=new Aa,this.observer.on(ne.FRAG_DECRYPTED,l),this.observer.on(ne.ERROR,l);var u=yr(o.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){var c=this.hls.logger;if(o.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{o.workerPath?(c.log("loading Web Worker ".concat(o.workerPath,' for "').concat(r,'"')),this.workerContext=function(e){var t=Ia[e];if(t)return t.clientCount++,t;var r=new self.URL(e,self.location.href).href,i={worker:new self.Worker(r),scriptURL:r,clientCount:1};return Ia[e]=i,i}(o.workerPath)):(c.log('injecting Web Worker for "'.concat(r,'"')),this.workerContext=function(){var e=Ia[ba];if(e)return e.clientCount++,e;var t=new self.Blob(["var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(".concat(__HLS_WORKER_BUNDLE__.toString(),")(true);")],{type:"text/javascript"}),r=self.URL.createObjectURL(t),i={worker:new self.Worker(r),objectURL:r,clientCount:1};return Ia[ba]=i,i}());var d=this.workerContext.worker;d.addEventListener("message",this.onWorkerMessage),d.addEventListener("error",this.onWorkerError),d.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:u,id:r,config:Nr(o)})}catch(e){c.warn('Error setting up "'.concat(r,'" Web Worker, fallback to inline'),e),this.terminateWorker(),this.error=null,this.transmuxer=new Gs(this.observer,u,o,"",r,t.logger)}return}}this.transmuxer=new Gs(this.observer,u,o,"",r,t.logger)},[{key:"reset",value:function(){if(this.frag=null,this.part=null,this.workerContext){var e=this.instanceNo;this.instanceNo=Ws++;var t=this.hls.config,r=yr(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:r,id:this.id,config:Nr(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=Ia[e||ba];if(t&&1===t.clientCount--){var r=t.worker,i=t.objectURL;delete Ia[e||ba],i&&self.URL.revokeObjectURL(i),r.terminate()}}(this.hls.config.workerPath)}}},{key:"destroy",value:function(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{var e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}var t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}},{key:"push",value:function(e,t,r,i,n,a,s,o,l,u){var c,d,h=this;l.transmuxing.start=self.performance.now();var f=this.instanceNo,v=this.transmuxer,g=a?a.start:n.start,p=n.decryptdata,m=this.frag,y=!m||n.cc!==m.cc,k=!m||l.level!==m.level,E=m?l.sn-m.sn:-1,S=this.part?l.part-this.part.index:-1,T=0===E&&l.id>1&&l.id===(null==m?void 0:m.stats.chunkCount),A=!k&&(1===E||0===E&&(1===S||T&&S<=0)),b=self.performance.now();(k||E||0===n.stats.parsing.start)&&(n.stats.parsing.start=b),!a||!S&&A||(a.stats.parsing.start=b);var I=!(m&&(null==(c=n.initSegment)?void 0:c.url)===(null==(d=m.initSegment)?void 0:d.url)),R=new qs(y,A,o,k,g,I);if(!A||y||I){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," playlist: ").concat(l.level," id: ").concat(l.id,"\n discontinuity: ").concat(y,"\n trackSwitch: ").concat(k,"\n contiguous: ").concat(A,"\n accurateTimeOffset: ").concat(o,"\n timeOffset: ").concat(g,"\n initSegmentChange: ").concat(I));var L=new js(r,i,t,s,u);this.configureTransmuxer(L)}if(this.frag=n,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:p,chunkMeta:l,state:R},e instanceof ArrayBuffer?[e]:[]);else if(v){var P=v.push(e,p,l,R);Ks(P)?P.then(function(e){h.handleTransmuxComplete(e)}).catch(function(e){h.transmuxerError(e,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(P)}}},{key:"flush",value:function(e){var t=this;e.transmuxing.start=self.performance.now();var r=this.instanceNo,i=this.transmuxer;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:r,cmd:"flush",chunkMeta:e});else if(i){var n=i.flush(e);Ks(n)?n.then(function(r){t.handleFlushResult(r,e)}).catch(function(r){t.transmuxerError(r,e,"transmuxer-interface flush error")}):this.handleFlushResult(n,e)}}},{key:"transmuxerError",value:function(e,t,r){this.hls&&(this.error=e,this.hls.trigger(ne.ERROR,{type:re.MEDIA_ERROR,details:ie.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:r}))}},{key:"handleFlushResult",value:function(e,t){var r=this;e.forEach(function(e){r.handleTransmuxComplete(e)}),this.onFlush(t)}},{key:"configureTransmuxer",value:function(e){var t=this.instanceNo,r=this.transmuxer;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):r&&r.configure(e)}},{key:"handleTransmuxComplete",value:function(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}])}(),zs=function(e){function t(e,r,i){var n;return s(this,t),(n=a(this,t,[e,r,i,"audio-stream-controller",de.AUDIO])).mainAnchor=null,n.mainFragLoading=null,n.audioOnly=!1,n.bufferedTrack=null,n.switchingTrack=null,n.trackId=-1,n.nextTrackId=-1,n.waitingData=null,n.mainDetails=null,n.flushing=!1,n.bufferFlushed=!1,n.cachedTrackLoadedData=null,n.registerListeners(),n}return f(t,e),l(t,[{key:"onHandlerDestroying",value:function(){this.unregisterListeners(),A(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(){A(t,"registerListeners",this,3)([]);var e=this.hls;e.on(ne.LEVEL_LOADED,this.onLevelLoaded,this),e.on(ne.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(ne.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(ne.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(ne.BUFFER_RESET,this.onBufferReset,this),e.on(ne.BUFFER_CREATED,this.onBufferCreated,this),e.on(ne.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(ne.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(ne.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(ne.FRAG_LOADING,this.onFragLoading,this),e.on(ne.FRAG_BUFFERED,this.onFragBuffered,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(A(t,"unregisterListeners",this,3)([]),e.off(ne.LEVEL_LOADED,this.onLevelLoaded,this),e.off(ne.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(ne.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(ne.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(ne.BUFFER_RESET,this.onBufferReset,this),e.off(ne.BUFFER_CREATED,this.onBufferCreated,this),e.off(ne.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(ne.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(ne.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(ne.FRAG_LOADING,this.onFragLoading,this),e.off(ne.FRAG_BUFFERED,this.onFragBuffered,this))}},{key:"onInitPtsFound",value:function(e,t){var r=t.frag,i=t.id,n=t.initPTS,a=t.timescale,s=t.trackId,o=t.timestampOffsets;if(i===de.MAIN){var l=r.cc,u=this.fragCurrent;if(this.initPTS=o,this.log("InitPTS for cc: ".concat(l," found from main: ").concat(n/a," (").concat(n,"/").concat(a,") trackId: ").concat(s)),this.mainAnchor=r,this.state===va){var c=this.waitingData;(!c&&!this.loadingParts||c&&c.frag.cc!==l)&&this.syncWithAnchor(r,null==c?void 0:c.frag)}else!this.hls.hasEnoughToStart&&u&&u.cc!==l?(u.abortRequests(),this.syncWithAnchor(r,u)):this.state===aa&&this.tick()}}},{key:"getLoadPosition",value:function(){var e;return!this.startFragRequested&&this.nextLoadPosition>=0&&!1!==(null==(e=this.switchingTrack)?void 0:e.flushImmediate)?this.nextLoadPosition:A(t,"getLoadPosition",this,3)([])}},{key:"syncWithAnchor",value:function(e,t){var r,i=(null==(r=this.mainFragLoading)?void 0:r.frag)||null;if(!t||(null==i?void 0:i.cc)!==t.cc){var n=(i||e).cc,a=Zr(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===aa&&this.doTickIdle())}}},{key:"startLoad",value:function(e,t){if(!this.levels)return this.startPosition=e,void(this.state=na);var r=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),r>0&&-1===e&&!t&&this.initPTS.length&&(this.log("Override startPosition with lastCurrentTime @".concat(r.toFixed(3))),e=r),this.state=aa,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,t||this.fragmentTracker.hasFragments(this.playlistType)||(this.startFragRequested=!1),this.tick()}},{key:"doTick",value:function(){switch(this.state){case aa:this.doTickIdle();break;case ua:var e=this.levels,r=this.trackId,i=null==e?void 0:e[r],n=null==i?void 0:i.details;if(n&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(n))break;this.state=va}break;case la:this.checkRetryDate();break;case va: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=oa;var d={frag:s,part:o,payload:l.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(d),u&&A(t,"_handleFragmentLoadComplete",this,3)([d])}else c&&c.cc!==a.frag.cc&&this.syncWithAnchor(c,a.frag)}else this.state=aa}this.onTickEnd()}},{key:"resetLoadingState",value:function(){var e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),A(t,"resetLoadingState",this,3)([])}},{key:"onTickEnd",value:function(){var e=this.media;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime,this.checkFragmentChanged())}},{key:"doTickIdle",value:function(){var e,t=this.hls,r=this.levels,i=this.media,n=this.trackId,a=t.config;if(this.buffering&&(i||this.primaryPrefetch||!this.startFragRequested&&a.startFragPrefetch)&&null!=r&&r[n]){var s=r[n],o=s.details;if(!o||this.waitForLive(s)||this.waitForCdnTuneIn(o))return this.state=ua,void(this.startFragRequested=!1);var l=this.getBufferOutput();this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,he));var u=this.getFwdBufferInfo();if(null!==u){if(!this.switchingTrack&&this._streamEnded(u,o))return t.trigger(ne.BUFFER_EOS,{type:"audio"}),void(this.state=ha);var c=u.len,d=t.maxBufferLength,h=o.fragments,f=h[0].start,v=this.getLoadPosition(),g=this.flushing||this.switchingTrack&&!this.switchingTrack.flushImmediate?v:u.end;if(this.switchingTrack&&i){var p=v;o.PTSKnown&&p<f&&p>=this.timelineOffset&&(u.end>f||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track ".concat(p," -> ").concat(f," + 0.05")),i.currentTime=f+.05)}if(!(c>=d&&!this.switchingTrack&&g<h[h.length-1].start)){var m=this.getNextFragment(g,o);if(m&&this.isLoopLoading(m,g)&&(m=this.getNextFragmentLoopLoading(m,o,u,de.MAIN,d)),m){if(!this.exceedsMaxBuffer(u,d,m)){var y=(null==(e=this.mainFragLoading)?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&y&&pe(m)&&!m.endList&&(!o.live||!this.loadingParts&&g<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(y)===yi&&(this.mainFragLoading=y=null),y&&pe(y))){if(m.start>y.end){var k=this.fragmentTracker.getFragAtPos(g,de.MAIN);k&&k.end>y.end&&(y=k,this.mainFragLoading={frag:k,targetBufferTime:null})}if(m.start>y.end)return}this.loadFragment(m,s,g)}}else this.bufferFlushed=!0}}}}},{key:"onMediaDetaching",value:function(e,r){this.bufferFlushed=this.flushing=!1,A(t,"onMediaDetaching",this,3)([e,r])}},{key:"onAudioTracksUpdated",value:function(e,t){var r=t.audioTracks;this.resetTransmuxer(),this.levels=r.map(function(e){return new xr(e)})}},{key:"onAudioTrackSwitching",value:function(e,t){var r=!!t.url;this.trackId=t.id;var i=this.fragCurrent;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),r?(this.switchingTrack=t,t.flushImmediate||(this.nextTrackId=t.id,this.nextLevelSwitch()),this.flushAudioIfNeeded(t),this.state!==na&&(this.setInterval(100),this.state=aa,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}},{key:"onManifestLoading",value:function(){A(t,"onManifestLoading",this,3)([]),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}},{key:"onLevelLoaded",value:function(e,t){this.mainDetails=t.details;var r=this.cachedTrackLoadedData;r&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(ne.AUDIO_TRACK_LOADED,r))}},{key:"onAudioTrackLoaded",value:function(e,t){var r,i=this.levels,n=t.details,a=t.id,s=t.groupId,o=t.track;if(i){var l=this.mainDetails;if(!l||n.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=t,void(this.state!==na&&(this.state=ua));this.cachedTrackLoadedData=null,this.log("Audio track ".concat(a,' "').concat(o.name,'" of "').concat(s,'" loaded [').concat(n.startSN,",").concat(n.endSN,"]").concat(n.lastPartSn?"[part-".concat(n.lastPartSn,"-").concat(n.lastPartIndex,"]"):"",",duration:").concat(n.totalduration));var u=i[a],c=0;if(n.live||null!=(r=u.details)&&r.live){if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;var d;if(u.details)c=this.alignPlaylists(n,u.details,null==(d=this.levelLastLoaded)?void 0:d.details);n.alignedSliding||(ea(l,n,this),c=n.fragmentStart)}u.details=n,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(l,c),this.hls.trigger(ne.AUDIO_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.state!==ua||this.waitForCdnTuneIn(n)||(this.state=aa),this.tick()}else this.warn("Audio tracks reset while loading track ".concat(a,' "').concat(o.name,'" of "').concat(s,'"'))}},{key:"_handleFragmentLoadProgress",value:function(e){var t,r=e.frag,i=e.part,n=e.payload,a=this.config,s=this.trackId,o=this.levels;if(o){var l=o[s];if(l){var u=l.details;if(!u)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(r.start);var c=a.defaultAudioCodec||l.audioCodec||"mp4a.40.2",d=this.transmuxer;d||(d=this.transmuxer=new Ys(this.hls,de.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));var h=this.initPTS[r.cc],f=null==(t=r.initSegment)?void 0:t.data;if(void 0!==h){var v=i?i.index:-1,g=-1!==v,p=new Fi(r.level,r.sn,r.stats.chunkCount,n.byteLength,v,g,r.duration);d.push(n,f,c,"",r,i,u.totalduration,!1,p,h)}else{this.log("Unknown video PTS for cc ".concat(r.cc,", waiting for video PTS before demuxing audio frag ").concat(r.sn," of [").concat(u.startSN," ,").concat(u.endSN,"],track ").concat(s)),(this.waitingData=this.waitingData||{frag:r,part:i,cache:new ka,complete:!1}).cache.push(new Uint8Array(n)),this.state!==na&&(this.state=va)}}else this.warn("Audio track is undefined on fragment load progress")}else this.warn("Audio tracks were reset while fragment load was in progress. Fragment ".concat(r.sn," of level ").concat(r.level," will not be buffered"))}},{key:"_handleFragmentLoadComplete",value:function(e){this.waitingData?this.waitingData.complete=!0:A(t,"_handleFragmentLoadComplete",this,3)([e])}},{key:"onBufferReset",value:function(){this.mediaBuffer=null}},{key:"onBufferCreated",value:function(e,t){this.bufferFlushed=this.flushing=!1;var r=t.tracks.audio;r&&(this.mediaBuffer=r.buffer||null)}},{key:"onFragLoading",value:function(e,t){!this.audioOnly&&t.frag.type===de.MAIN&&pe(t.frag)&&(this.mainFragLoading=t,this.state===aa&&this.tick())}},{key:"onFragBuffered",value:function(e,t){var r=t.frag,i=t.part;if(r.type===de.AUDIO)if(this.fragContextChanged(r))this.warn("Fragment ".concat(r.sn).concat(i?" p: "+i.index:""," of level ").concat(r.level," finished buffering, but was aborted. state: ").concat(this.state,", audioSwitch: ").concat(this.switchingTrack?this.switchingTrack.name:"false"));else{if(pe(r)){var n=this.switchingTrack;n&&(this.bufferedTrack=n)}this.fragBufferedComplete(r,i),this.media&&this.tick()}else this.audioOnly||r.type!==de.MAIN||r.elementaryStreams.video||r.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}},{key:"getFwdBufferInfo",value:function(){var e=this.getBufferOutput();return A(t,"getFwdBufferInfo",this,3)([e,de.AUDIO])}},{key:"getBufferOutput",value:function(){return this.mediaBuffer?this.mediaBuffer:this.media}},{key:"checkFragmentChanged",value:function(){var e=this.fragPlaying;if(!this.checkFragPlaying())return!1;var t=this.fragPlaying,r=null==e?void 0:e.level;return t&&t.level===r||(e&&this.cleanupBackBuffer(),this.switchingTrack&&this.completeAudioSwitch(this.switchingTrack)),!0}},{key:"onError",value:function(e,r){var i;if(r.fatal)this.state=fa;else switch(r.details){case ie.FRAG_GAP:case ie.FRAG_PARSING_ERROR:case ie.FRAG_DECRYPT_ERROR:case ie.FRAG_LOAD_ERROR:case ie.FRAG_LOAD_TIMEOUT:case ie.KEY_LOAD_ERROR:case ie.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(de.AUDIO,r);break;case ie.AUDIO_TRACK_LOAD_ERROR:case ie.AUDIO_TRACK_LOAD_TIMEOUT:case ie.LEVEL_PARSING_ERROR:r.levelRetry||this.state!==ua||(null==(i=r.context)?void 0:i.type)!==ce.AUDIO_TRACK||(this.state=aa);break;case ie.BUFFER_APPEND_NO_PROGRESS:if("audio"!==r.parent)return;r.frag&&(r.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn("Marking fragment ".concat(r.frag.sn," of track ").concat(r.frag.level," as a gap after ").concat(r.appendsWithoutProgress," appends without buffered range growth, to prevent loop loading")),this.fragmentTracker.addAsGap(r.frag));break;case ie.BUFFER_ADD_CODEC_ERROR:case ie.BUFFER_APPEND_ERROR:if("audio"!==r.parent)return;this.reduceLengthAndFlushBuffer(r)||this.resetLoadingState();break;case ie.BUFFER_FULL_ERROR:if("audio"!==r.parent)return;this.reduceLengthAndFlushBuffer(r)&&(this.bufferedTrack=null,A(t,"flushMainBuffer",this,3)([0,Number.POSITIVE_INFINITY,"audio"]));break;case ie.INTERNAL_EXCEPTION:this.recoverWorkerError(r)}}},{key:"onBufferFlushing",value:function(e,t){t.type!==fe&&(this.flushing=!0)}},{key:"onBufferFlushed",value:function(e,t){var r=t.type;if(r!==fe){this.flushing=!1,this.bufferFlushed=!0,this.state===ha&&(this.state=aa);var i=this.getBufferOutput();i&&(this.afterBufferFlushed(i,r),this.tick())}}},{key:"_handleTransmuxComplete",value:function(e){var r,i="audio",n=this.hls,a=e.remuxResult,s=e.chunkMeta,o=this.getCurrentContext(s);if(o){var l=o.frag,u=o.part,c=o.level,d=c.details,h=a.audio,f=a.text,v=a.id3,g=a.initSegment;if(this.fragContextChanged(l)||!d)return this.fragmentTracker.removeFragment(l),void(null!=g&&g.tracks&&this.resetTransmuxer());if(this.state=ca,h&&this.switchingTrack&&!this.switchingTrack.flushImmediate){var p=this.config.nextAudioTrackBufferFlushForwardOffset,m=Math.max(this.getLoadPosition()+p,l.start);A(t,"flushMainBuffer",this,3)([m,Number.POSITIVE_INFINITY,de.AUDIO])}if(null!=g&&g.tracks){var y=l.initSegment||l;if(this.unhandledEncryptionError(g,l))return;this._bufferInitSegment(c,g.tracks,y,s),n.trigger(ne.FRAG_PARSING_INIT_SEGMENT,{frag:y,id:i,tracks:g.tracks})}if(h){var k=h.startPTS,E=h.endPTS,S=h.startDTS,T=h.endDTS;u&&(u.elementaryStreams[he]={startPTS:k,endPTS:E,startDTS:S,endDTS:T}),l.setElementaryStreamInfo(he,k,E,S,T),this.bufferFragmentData(h,l,u,s)}if(null!=v&&null!=(r=v.samples)&&r.length){var b=Ae({id:i,frag:l,details:d},v);n.trigger(ne.FRAG_PARSING_METADATA,b)}if(f){var I=Ae({id:i,frag:l,details:d},f);n.trigger(ne.FRAG_PARSING_USERDATA,I)}}else this.resetWhenMissingContext(s)}},{key:"_bufferInitSegment",value:function(e,t,r,i){if(this.state===ca&&(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,t.audio)){var n=t.audio;n.id=de.AUDIO;var a=e.audioCodec;this.log("Init audio buffer, container:".concat(n.container,", codecs[level/parsed]=[").concat(a,"/").concat(n.codec,"]")),1===(null==a?void 0:a.split(",").length)&&(n.levelCodec=a),this.hls.trigger(ne.BUFFER_CODECS,t);var s=n.initSegment;if(null!=s&&s.byteLength){var o={type:"audio",frag:r,part:null,chunkMeta:i,parent:r.type,data:s};this.hls.trigger(ne.BUFFER_APPENDING,o)}this.tickImmediate()}}},{key:"loadFragment",value:function(e,r,i){var n,a=this.fragmentTracker.getState(e);if(this.switchingTrack||a===gi||a===mi)if(null!=(n=r.details)&&n.live&&!this.initPTS[e.cc]){this.log("Waiting for video PTS in continuity counter ".concat(e.cc," of live stream before loading audio fragment ").concat(e.sn," of level ").concat(this.trackId)),this.state=va;var s=this.mainDetails;s&&s.fragmentStart!==r.details.fragmentStart&&ea(s,r.details,this)}else A(t,"loadFragment",this,3)([e,r,i]);else this.clearTrackerIfNeeded(e)}},{key:"flushAudioIfNeeded",value:function(e){if(this.media&&this.bufferedTrack&&e.flushImmediate){var r=this.bufferedTrack;Hr({name:r.name,lang:r.lang,assocLang:r.assocLang,characteristics:r.characteristics,audioCodec:r.audioCodec,channels:r.channels},e,Kr)||(qr(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),A(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.bufferedTrack=e,this.switchingTrack=null,t.trigger(ne.AUDIO_TRACK_SWITCHED,Ie({},e))}},{key:"nextAudioTrack",get:function(){return this.nextTrackId}}])}(pa),Xs=function(e){function t(e,r){var i;return s(this,t),(i=a(this,t,[r,e.logger])).hls=void 0,i.canLoad=!1,i.timer=-1,i.loadingSync=!1,i.hls=e,i}return f(t,e),l(t,[{key:"destroy",value:function(){this.clearTimer(),this.hls=null}},{key:"clearTimer",value:function(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}},{key:"startLoad",value:function(){this.canLoad=!0,this.loadPlaylist()}},{key:"stopLoad",value:function(){this.canLoad=!1,this.clearTimer()}},{key:"switchParams",value:function(e,t,r){var i=null==t?void 0:t.renditionReports;if(i){for(var n=-1,a=0;a<i.length;a++){var s=i[a],o=void 0;try{o=new self.URL(s.URI,t.url).href}catch(e){this.warn("Could not construct new URL for Rendition Report: ".concat(e)),o=s.URI||""}if(o===e){n=a;break}o===e.substring(0,o.length)&&(n=a)}if(-1!==n){var l=i[n],u=parseInt(l["LAST-MSN"])||t.lastPartSn,c=parseInt(l["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){var d=Math.min(t.age-t.partTarget,t.targetduration);c>=0&&d>t.partTarget&&(c+=1)}var h=r&&_r(r);return new Mr(u,c>=0?c:void 0,h)}}}},{key:"loadPlaylist",value:function(e){this.clearTimer()}},{key:"loadingPlaylist",value:function(e,t){this.clearTimer()}},{key:"shouldLoadPlaylist",value:function(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}},{key:"getUrlWithDirectives",value:function(e,t){if(t)try{return t.addDirectives(e)}catch(e){this.warn("Could not construct new URL with HLS Delivery Directives: ".concat(e))}return e}},{key:"playlistLoaded",value:function(e,t,r){var i=t.details,n=t.stats,a=i.fragments,s=self.performance.now(),o=n.loading.first?Math.max(0,Math.floor(s-n.loading.first)):0;i.advancedDateTime=Date.now()-o;var l=this.hls.config.timelineOffset;if(l!==i.appliedTimelineOffset){var u=Math.max(l||0,0);i.appliedTimelineOffset=u,a.forEach(function(e){null==e||e.setStart(e.playlistOffset+u)})}if(i.live||null!=r&&r.live){var c,d="levelInfo"in t?t.levelInfo:t.track;i.reloaded(r);var h=null==(c=a[a.length-1])?void 0:c.type;if(i.misses>=this.hls.config.liveMaxUnchangedPlaylistRefresh){var f=new Error("".concat(h," playlist ").concat(d.id," hit max allowed unchanged reloads."));this.warn(f);var v=t.networkDetails,g=t.context;return void this.hls.trigger(ne.ERROR,{type:re.NETWORK_ERROR,details:ie.PLAYLIST_UNCHANGED_ERROR,fatal:!1,url:i.url,error:f,reason:f.message,level:t.level,parent:h,context:g,networkDetails:v,stats:n})}if(r){Gn(r,i,this);var p=i.playlistParsingError;if(p){this.warn(p);var m=this.hls;if(!m.config.ignorePlaylistParsingErrors){var y=t.networkDetails;return void m.trigger(ne.ERROR,{type:re.NETWORK_ERROR,details:ie.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:p,reason:p.message,level:t.level,parent:h,networkDetails:y,stats:n})}i.playlistParsingError=null}}-1===i.requestScheduled&&(i.requestScheduled=n.loading.start);var k=this.hls.mainForwardBufferInfo,E=k?k.end-k.len:0,S=jn(i,1e3*(i.edge-E));i.requestScheduled+S<s?i.requestScheduled=s:i.requestScheduled<=s&&(i.requestScheduled+=S);var T,A=t.deliveryDirectives;if(this.log("live playlist ".concat(e," ").concat(i.advanced?"REFRESHED ".concat(i.lastPartSn," - ").concat(i.lastPartIndex):i.updated?"UPDATED":"MISSED (received ".concat(i.lastPartSn," - ").concat(i.lastPartIndex).concat(A?" | requested ".concat(A.msn," - ").concat(A.part):"",")"))),!this.canLoad||!i.live)return;var b=void 0,I=void 0;if(i.canBlockReload&&i.advanced){var R=this.hls.config.lowLatencyMode,L=i.lastPartSn,P=i.endSN,w=i.lastPartIndex,C=L===P;-1!==w?C?(b=P+1,I=R?0:w):(b=L,I=R?w+1:i.maxPartIndex):b=P+1;var D=i.age,_=D+i.ageHeader,M=Math.min(_-i.partTarget,1.5*i.targetduration);if(M>0){if(_>3*i.targetduration)this.log("Playlist last advanced ".concat(D.toFixed(2),"s ago. Omitting segment and part directives.")),b=void 0,I=void 0;else if(null!=r&&r.tuneInGoal&&_-i.partTarget>r.tuneInGoal)this.warn("CDN Tune-in goal increased from: ".concat(r.tuneInGoal," to: ").concat(M," with playlist age: ").concat(i.age)),M=0;else{var x=Math.floor(M/i.targetduration);if(b+=x,void 0!==I)I+=Math.round(M%i.targetduration/i.partTarget);this.log("CDN Tune-in age: ".concat(i.ageHeader,"s last advanced ").concat(D.toFixed(2),"s goal: ").concat(M," skip sn ").concat(x," to part ").concat(I))}i.tuneInGoal=M}if(T=this.getDeliveryDirectives(i,t.deliveryDirectives,b,I),R||!C)return i.requestScheduled=s,void this.loadingPlaylist(d,T)}else(i.canBlockReload||i.canSkipUntil)&&(T=this.getDeliveryDirectives(i,t.deliveryDirectives,b,I));T&&void 0!==b&&i.canBlockReload&&(i.requestScheduled=n.loading.first+Math.max(S-2*o,S/2)),this.scheduleLoading(d,T,i)}else this.clearTimer()}},{key:"scheduleLoading",value:function(e,t,r){var i=this,n=r||e.details;if(n){var a=self.performance.now(),s=n.requestScheduled;if(a>=s&&!this.loadingSync)return this.loadingSync=!0,this.loadingPlaylist(e,t),void(this.loadingSync=!1);var o=Math.max(s-a,0);this.log("reload live playlist ".concat(e.name||e.bitrate+"bps"," in ").concat(Math.round(o)," ms")),this.clearTimer(),this.timer=self.setTimeout(function(){return i.loadingPlaylist(e,t)},o)}else this.loadingPlaylist(e,t)}},{key:"getDeliveryDirectives",value:function(e,t,r,i){var n=_r(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(r=t.msn,i=t.part,n=wr),new Mr(r,i,n)}},{key:"checkRetry",value:function(e){var t=this,r=e.details,i=Le(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===ni||!n.resolved&&s===ri);if(c){var d;if(l>=u.maxNumRetry)return!1;if(i&&null!=(d=e.context)&&d.deliveryDirectives)this.warn("Retrying playlist loading ".concat(l+1,"/").concat(u.maxNumRetry,' after "').concat(r,'" without delivery-directives')),this.loadPlaylist();else{var h,f=xe(null==(h=e.response)?void 0:h.code);if(this.clearTimer(),f)this.log("Waiting for connection (offline)"),e.reason="offline",this.timer=self.setTimeout(function(){return t.checkOfflineStatus()},1e3);else{var v=De(u,l);this.warn("Retrying playlist loading ".concat(l+1,"/").concat(u.maxNumRetry,' after "').concat(r,'" in ').concat(v,"ms")),this.timer=self.setTimeout(function(){return t.loadPlaylist()},v)}}e.levelRetry=!0,n.resolved=!0}return c}},{key:"checkOfflineStatus",value:function(){var e=this;this.clearTimer(),xe(0)?this.timer=self.setTimeout(function(){return e.checkOfflineStatus()},1e3):(this.log("Connection restored (online)"),this.loadPlaylist())}}])}(Be);function Qs(e,t){if(e.length!==t.length)return!1;for(var r=0;r<e.length;r++)if(!$s(e[r].attrs,t[r].attrs))return!1;return!0}function $s(e,t,r){var i=e["STABLE-RENDITION-ID"];return i&&!r?i===t["STABLE-RENDITION-ID"]:!(r||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(function(r){return e[r]!==t[r]})}var Js=function(e){function t(e){var r;return s(this,t),(r=a(this,t,[e,"audio-track-controller"])).tracks=[],r.groupIds=null,r.tracksInGroup=[],r.trackId=-1,r.currentTrack=null,r.selectDefaultTrack=!0,r.registerListeners(),r}return f(t,e),l(t,[{key:"registerListeners",value:function(){var e=this.hls;e.on(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ne.MANIFEST_PARSED,this.onManifestParsed,this),e.on(ne.LEVEL_LOADING,this.onLevelLoading,this),e.on(ne.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(ne.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(ne.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ne.MANIFEST_PARSED,this.onManifestParsed,this),e.off(ne.LEVEL_LOADING,this.onLevelLoading,this),e.off(ne.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(ne.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(ne.ERROR,this.onError,this)}},{key:"destroy",value:function(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,A(t,"destroy",this,3)([])}},{key:"onManifestLoading",value:function(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}},{key:"onManifestParsed",value:function(e,t){this.tracks=t.audioTracks||[]}},{key:"onAudioTrackLoaded",value:function(e,t){var r=t.id,i=t.groupId,n=t.details,a=this.tracksInGroup[r];if(a&&a.groupId===i){var s=a.details;a.details=t.details,this.log("Audio track ".concat(r,' "').concat(a.name,'" lang:').concat(a.lang," group:").concat(i," loaded [").concat(n.startSN,"-").concat(n.endSN,"]")),r===this.trackId&&this.playlistLoaded(r,t,s)}else this.warn("Audio track with id:".concat(r," and group:").concat(i," not found in active group ").concat(null==a?void 0:a.groupId))}},{key:"onLevelLoading",value:function(e,t){this.switchLevel(t.level)}},{key:"onLevelSwitching",value:function(e,t){this.switchLevel(t.level)}},{key:"switchLevel",value:function(e){var t=this.hls.levels[e];if(t){var r=t.audioGroups||null,i=this.groupIds,n=this.currentTrack;if(!r||(null==i?void 0:i.length)!==(null==r?void 0:r.length)||null!=r&&r.some(function(e){return-1===(null==i?void 0:i.indexOf(e))})){this.groupIds=r,this.trackId=-1,this.currentTrack=null;var a=this.tracks.filter(function(e){return Wr(e.groupId,r)});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=Gr(s,a,Kr);if(o>-1)n=a[o];else{var l=Gr(s,this.tracks);n=this.tracks[l]}}var u=this.findTrackId(n);-1===u&&n&&(u=this.findTrackId(null));var c={audioTracks:a};this.log("Updating audio tracks, ".concat(a.length," track(s) found in group(s): ").concat(null==r?void 0:r.join(","))),this.hls.trigger(ne.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(ne.ERROR,{type:re.MEDIA_ERROR,details:ie.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:f})}}}}},{key:"onError",value:function(e,t){!t.fatal&&t.context&&t.context.type===ce.AUDIO_TRACK&&t.context.id===this.trackId&&Wr(t.context.groupId,this.groupIds)&&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:"nextAudioTrack",get:function(){return this.trackId},set:function(e){this.selectDefaultTrack=!1,this.setAudioTrack(e,!1)}},{key:"setAudioOption",value:function(e){var t=this.hls;if(t.config.audioPreference=e,e){var r=this.allAudioTracks;if(this.selectDefaultTrack=!1,r.length){var i=this.currentTrack;if(i&&Hr(e,i,Kr))return i;var n=Gr(e,this.tracksInGroup,Kr);if(n>-1){var a=this.tracksInGroup[n];return this.setAudioTrack(n,"flushImmediate"in e&&e.flushImmediate),a}if(i){var s=t.loadLevel;-1===s&&(s=t.firstAutoLevel);var o=function(e,t,r,i,n){var a=t[i],s=t.reduce(function(e,t,r){var i=t.uri;return(e[i]||(e[i]=[])).push(r),e},{})[a.uri];s.length>1&&(i=Math.max.apply(Math,s));var o=a.videoRange,l=a.frameRate,u=a.codecSet.substring(0,4),c=jr(t,i,function(t){if(t.videoRange!==o||t.frameRate!==l||t.codecSet.substring(0,4)!==u)return!1;var i=t.audioGroups,a=r.filter(function(e){return Wr(e.groupId,i)});return Gr(e,a,n)>-1});return c>-1?c:jr(t,i,function(t){var i=t.audioGroups,a=r.filter(function(e){return Wr(e.groupId,i)});return Gr(e,a,n)>-1})}(e,t.levels,r,s,Kr);if(-1===o)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){var l=Gr(e,r);if(l>-1)return r[l]}}}return null}},{key:"setAudioTrack",value:function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],r=this.tracksInGroup;if(e<0||e>=r.length)this.warn("Invalid audio track id: ".concat(e));else{this.selectDefaultTrack=!1;var i=this.currentTrack,n=r[e],a=n.details&&!n.details.live;if(!(e===this.trackId&&n===i&&a||(this.log("Switching to audio-track ".concat(e,' "').concat(n.name,'" lang:').concat(n.lang," group:").concat(n.groupId," channels:").concat(n.channels)),this.trackId=e,this.currentTrack=n,this.hls.trigger(ne.AUDIO_TRACK_SWITCHING,Ie(Ie({},n),{},{flushImmediate:t})),a))){var s=this.switchParams(n.url,null==i?void 0:i.details,n.details);this.loadPlaylist(s)}}}},{key:"findTrackId",value:function(e){for(var t=this.tracksInGroup,r=0;r<t.length;r++){var i=t[r];if((!this.selectDefaultTrack||i.default)&&(!e||Hr(e,i,Kr)))return r}if(e){for(var n=e.name,a=e.lang,s=e.assocLang,o=e.characteristics,l=e.audioCodec,u=e.channels,c=0;c<t.length;c++){if(Hr({name:n,lang:a,assocLang:s,characteristics:o,audioCodec:l,channels:u},t[c],Kr))return c}for(var d=0;d<t.length;d++){var h=t[d];if($s(e.attrs,h.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return d}for(var f=0;f<t.length;f++){var v=t[f];if($s(e.attrs,v.attrs,["LANGUAGE"]))return f}}return-1}},{key:"loadPlaylist",value:function(e){A(t,"loadPlaylist",this,3)([]);var r=this.currentTrack;this.shouldLoadPlaylist(r)&&qr(r.url,this.hls)&&this.scheduleLoading(r,e)}},{key:"loadingPlaylist",value:function(e,r){A(t,"loadingPlaylist",this,3)([e,r]);var i=e.id,n=e.groupId,a=this.getUrlWithDirectives(e.url,r),s=e.details,o=null==s?void 0:s.age;this.log("Loading audio-track ".concat(i,' "').concat(e.name,'" lang:').concat(e.lang," group:").concat(n).concat(void 0!==(null==r?void 0:r.msn)?" at sn "+r.msn+" part "+r.part:"").concat(o&&s.live?" age "+o.toFixed(1)+(s.type&&" "+s.type||""):""," ").concat(a)),this.hls.trigger(ne.AUDIO_TRACK_LOADING,{url:a,id:i,groupId:n,deliveryDirectives:r||null,track:e})}}])}(Xs),Zs=function(){return l(function e(t){s(this,e),this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=t},[{key:"destroy",value:function(){this.tracks=this.queues=null}},{key:"append",value:function(e,t,r){if(null!==this.queues&&null!==this.tracks){var i=this.queues[t];i.push(e),1!==i.length||r||this.executeNext(t)}}},{key:"appendBlocker",value:function(e){var t=this;return new Promise(function(r){var i={label:"async-blocker",execute:r,onStart:function(){},onComplete:function(){},onError:function(){}};t.append(i,e)})}},{key:"prependBlocker",value:function(e){var t=this;return new Promise(function(r){if(t.queues){var i={label:"async-blocker-prepend",execute:r,onStart:function(){},onComplete:function(){},onError:function(){}};t.queues[e].unshift(i)}})}},{key:"removeBlockers",value:function(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(function(e){var t,r=null==(t=e[0])?void 0:t.label;"async-blocker"===r||"async-blocker-prepend"===r?(e[0].execute(),e.splice(0,1)):"block-audio"===r&&e.splice(0,1)})}},{key:"insertNext",value:function(e,t){var r;null!==this.queues&&(r=this.queues[t]).splice.apply(r,[1,0].concat(b(e)))}},{key:"unblockAudio",value:function(){var e;null!==this.queues&&"block-audio"===(null==(e=this.current("audio"))?void 0:e.label)&&this.shiftAndExecuteNext("audio")}},{key:"audioBlocking",value:function(){return null!==this.queues&&this.queues.audio.some(function(e){return"block-audio"===e.label})}},{key:"executeNext",value:function(e){if(null!==this.queues&&null!==this.tracks){var t=this.queues[e];if(t.length){var r=t[0];try{r.execute()}catch(t){var i;if(r.onError(t),null===this.queues||null===this.tracks)return;var n=null==(i=this.tracks[e])?void 0:i.buffer;null!=n&&n.updating||this.shiftAndExecuteNext(e)}}}}},{key:"shiftAndExecuteNext",value:function(e){null!==this.queues&&(this.queues[e].shift(),this.executeNext(e))}},{key:"current",value:function(e){var t;return(null==(t=this.queues)?void 0:t[e][0])||null}},{key:"toString",value:function(){var e=this.queues,t=this.tracks;return null===e||null===t?"<destroyed>":"\n".concat(this.list("video"),"\n").concat(this.list("audio"),"\n").concat(this.list("audiovideo"),"}")}},{key:"list",value:function(e){var t,r;return null!=(t=this.queues)&&t[e]||null!=(r=this.tracks)&&r[e]?"".concat(e,": (").concat(this.listSbInfo(e),") ").concat(this.listOps(e)):""}},{key:"listSbInfo",value:function(e){var t,r=null==(t=this.tracks)?void 0:t[e],i=null==r?void 0:r.buffer;return i?"SourceBuffer".concat(i.updating?" updating":"").concat(r.ended?" ended":"").concat(r.ending?" ending":""):"none"}},{key:"listOps",value:function(e){var t;return(null==(t=this.queues)?void 0:t[e].map(function(e){return e.label}).join(", "))||""}}])}(),eo=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,to="HlsJsTrackRemovedError",ro=function(e){function t(e){var r;return s(this,t),(r=a(this,t,[e])).name=to,r}return f(t,e),l(t)}(w(Error)),io=function(e){function t(e,r){var i,n;return s(this,t),(i=a(this,t,["buffer-controller",e.logger])).hls=void 0,i.fragmentTracker=void 0,i.fragmentAppendProgress=Object.create(null),i.appendsWithoutProgress=Object.create(null),i.details=null,i._objectUrl=null,i.operationQueue=null,i.bufferCodecEventsTotal=0,i.media=null,i.mediaSource=null,i.lastMpegAudioChunk=null,i.lastVideoAppendEnd=0,i.appendSource=void 0,i.transferData=void 0,i.overrides=void 0,i.appendErrors={audio:0,video:0,audiovideo:0},i.appendError=void 0,i._quotaEvictionPending={},i.tracks={},i.sourceBuffers=[[null,null],[null,null]],i._onEndStreaming=function(e){var t;i.hls&&"open"===(null==(t=i.mediaSource)?void 0:t.readyState)&&i.media&&!i.media.seeking&&i.hls.pauseBuffering()},i._onStartStreaming=function(e){i.hls&&i.hls.resumeBuffering()},i._onMediaSourceOpen=function(e){var t=i,r=t.media,n=t.mediaSource;e&&i.log("Media source opened"),r&&n&&(ra(n,"sourceopen",i._onMediaSourceOpen),ra(r,"emptied",i._onMediaEmptied),i.updateDuration(),i.hls.trigger(ne.MEDIA_ATTACHED,{media:r,mediaSource:n}),null!==i.mediaSource&&i.checkPendingTracks())},i._onMediaSourceClose=function(){if(i.log("Media source closed"),i.media){var e=i.media.error,t=i,r=t.appendError,n=t.appendErrors,a=!1;if(!r&&e)a=Math.max(++n.audio,++n.video,++n.audiovideo)>=i.hls.config.appendErrorMaxRetry;var s=new Error("MediaSource closed while media attached".concat(so(a,e)));i.warn(s),i.hls.trigger(ne.ERROR,Ae({fatal:a},r,{type:re.MEDIA_ERROR,details:ie.MEDIA_SOURCE_REQUIRES_RESET,error:s}))}},i._onMediaSourceEnded=function(){i.log("Media source ended")},i._onMediaEmptied=function(){var e=i,t=e.mediaSrc,r=e._objectUrl;t!==r&&i.error("Media element src was set while attaching MediaSource (".concat(r," > ").concat(t,")"))},i._onMediaError=function(){var e,t,r=i.media;r&&i.log("Media error (code: ".concat(null==(e=r.error)?void 0:e.code,"): ").concat(null==(t=r.error)?void 0:t.message))},i.hls=e,i.fragmentTracker=r,i.appendSource=(n=qe(e.config.preferManagedMediaSource),"undefined"!=typeof self&&n===self.ManagedMediaSource),i.initTracks(),i.registerListeners(),i}return f(t,e),l(t,[{key:"hasSourceTypes",value:function(){return Object.keys(this.tracks).length>0}},{key:"destroy",value:function(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=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,this._onMediaEmptied=this._onMediaError=null}},{key:"registerListeners",value:function(){var e=this.hls;e.on(ne.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(ne.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ne.MANIFEST_PARSED,this.onManifestParsed,this),e.on(ne.BUFFER_RESET,this.onBufferReset,this),e.on(ne.BUFFER_APPENDING,this.onBufferAppending,this),e.on(ne.BUFFER_CODECS,this.onBufferCodecs,this),e.on(ne.BUFFER_EOS,this.onBufferEos,this),e.on(ne.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(ne.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(ne.FRAG_PARSED,this.onFragParsed,this),e.on(ne.FRAG_CHANGED,this.onFragChanged,this),e.on(ne.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(ne.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(ne.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ne.MANIFEST_PARSED,this.onManifestParsed,this),e.off(ne.BUFFER_RESET,this.onBufferReset,this),e.off(ne.BUFFER_APPENDING,this.onBufferAppending,this),e.off(ne.BUFFER_CODECS,this.onBufferCodecs,this),e.off(ne.BUFFER_EOS,this.onBufferEos,this),e.off(ne.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(ne.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(ne.FRAG_PARSED,this.onFragParsed,this),e.off(ne.FRAG_CHANGED,this.onFragChanged,this),e.off(ne.ERROR,this.onError,this)}},{key:"transferMedia",value:function(){var e=this,t=this.media,r=this.mediaSource;if(!t)return null;var i={};if(this.operationQueue){var n=this.isUpdating();n||this.operationQueue.removeBlockers();var a=this.isQueued();(n||a)&&this.warn("Transfering MediaSource with".concat(a?" operations in queue":"").concat(n?" updating SourceBuffer(s)":""," ").concat(this.operationQueue)),this.operationQueue.destroy()}var s=this.transferData;return s&&!this.sourceBufferCount&&s.mediaSource===r?Ae(i,s.tracks):this.sourceBuffers.forEach(function(t){var r=S(t,1)[0];r&&(i[r]=Ae({},e.tracks[r]),e.removeBuffer(r)),t[0]=t[1]=null}),{media:t,mediaSource:r,tracks:i}}},{key:"initTracks",value:function(){this.resetAppendProgress(),this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0}},{key:"onManifestLoading",value:function(){this.bufferCodecEventsTotal=0,this.details=null,this.resetAppendErrors(),this.resetAppendProgress()}},{key:"onManifestParsed",value:function(e,t){var r,i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log("".concat(i," bufferCodec event(s) expected.")),null!=(r=this.transferData)&&r.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}},{key:"onMediaAttaching",value:function(e,t){var r=this.media=t.media;this.transferData=this.overrides=void 0;var i=qe(this.appendSource);if(i){var n=!!t.mediaSource;(n||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);var a=this.mediaSource=t.mediaSource||new i;if(this.assignMediaSource(a),n)this._objectUrl=r.src,this.attachTransferred();else{var s=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{r.removeAttribute("src");var o=self.ManagedMediaSource;r.disableRemotePlayback=r.disableRemotePlayback||o&&a instanceof o,no(r),function(e,t){var r=self.document.createElement("source");r.type="video/mp4",r.src=t,e.appendChild(r)}(r,s),r.load()}catch(e){r.src=s}else r.src=s}ta(r,"emptied",this._onMediaEmptied),ta(r,"error",this._onMediaError),this.appendSource&&ta(r,"seeking",this._onStartStreaming)}}},{key:"assignMediaSource",value:function(e){var t,r;this.log("".concat((null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created"," media source: ").concat(null==(r=e.constructor)?void 0:r.name)),ta(e,"sourceopen",this._onMediaSourceOpen),ta(e,"sourceended",this._onMediaSourceEnded),ta(e,"sourceclose",this._onMediaSourceClose),this.appendSource&&(ta(e,"startstreaming",this._onStartStreaming),ta(e,"endstreaming",this._onEndStreaming))}},{key:"attachTransferred",value:function(){var e=this,t=this.media,r=this.transferData;if(r&&t){var i=this.tracks,n=r.tracks,a=n?Object.keys(n):null,s=a?a.length:0,o=function(){Promise.resolve().then(function(){e.media&&e.mediaSourceOpenOrEnded&&e._onMediaSourceOpen()})};if(n&&a&&s){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log("attachTransferred: (bufferCodecEventsTotal ".concat(this.bufferCodecEventsTotal,")\nrequired tracks: ").concat(Nr(i,function(e,t){return"initSegment"===e?void 0:t}),";\ntransfer tracks: ").concat(Nr(n,function(e,t){return"initSegment"===e?void 0:t}),"}")),!We(n,i)){r.mediaSource=null,r.tracks=void 0;var l=t.currentTime,u=this.details,c=Math.max(l,(null==u?void 0:u.fragments[0].start)||0);return c-l>1?void this.log("attachTransferred: waiting for playback to reach new tracks start time ".concat(l," -> ").concat(c)):(this.warn('attachTransferred: resetting MediaSource for incompatible tracks ("'.concat(Object.keys(n),'"->"').concat(Object.keys(i),'") start time: ').concat(c," currentTime: ").concat(l)),this.onMediaDetaching(ne.MEDIA_DETACHING,{}),this.onMediaAttaching(ne.MEDIA_ATTACHING,r),void(t.currentTime=c))}this.transferData=void 0,a.forEach(function(t){var r=t,i=n[r];if(i){var a=i.buffer;if(a){var s=e.fragmentTracker,o=i.id;if(s.hasFragments(o)||s.hasParts(o)){var l=Bi.getBuffered(a);s.detectEvictedFragments(r,l,o,null,null,!0)}var u=ao(r),c=[r,a];e.sourceBuffers[u]=c,a.updating&&e.operationQueue&&e.operationQueue.prependBlocker(r),e.trackSourceBuffer(r,i)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}}},{key:"mediaSourceOpenOrEnded",get:function(){var e,t=null==(e=this.mediaSource)?void 0:e.readyState;return"open"===t||"ended"===t}},{key:"onMediaDetaching",value:function(e,t){var r=this,i=!!t.transferMedia;this.transferData=this.overrides=void 0;var n=this.media,a=this.mediaSource,s=this._objectUrl;if(a){if(this.log("media source ".concat(i?"transferring":"detaching")),i)this.sourceBuffers.forEach(function(e){var t=S(e,1)[0];t&&r.removeBuffer(t)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){var o="open"===a.readyState;try{for(var l=a.sourceBuffers,u=l.length;u--;)o&&l[u].abort(),a.removeSourceBuffer(l[u]);o&&a.endOfStream()}catch(e){this.warn("onMediaDetaching: ".concat(e.message," while calling endOfStream"))}}this.sourceBufferCount&&this.onBufferReset()}ra(a,"sourceopen",this._onMediaSourceOpen),ra(a,"sourceended",this._onMediaSourceEnded),ra(a,"sourceclose",this._onMediaSourceClose),this.appendSource&&(ra(a,"startstreaming",this._onStartStreaming),ra(a,"endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}n&&(ra(n,"emptied",this._onMediaEmptied),ra(n,"error",this._onMediaError),ra(n,"seeking",this._onStartStreaming),i||(s&&self.URL.revokeObjectURL(s),this.mediaSrc===s?(n.removeAttribute("src"),this.appendSource&&no(n),n.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null)}},{key:"onBufferReset",value:function(){var e=this;this.sourceBuffers.forEach(function(t){var r=S(t,1)[0];r&&e.resetBuffer(r)}),this.initTracks()}},{key:"resetBuffer",value:function(e){var t,r=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),r)try{var i;null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(r)}catch(t){this.warn("onBufferReset ".concat(e),t)}delete this.tracks[e]}},{key:"removeBuffer",value:function(e){this.removeBufferListeners(e),this.sourceBuffers[ao(e)]=[null,null];var t=this.tracks[e];t&&(this.clearBufferAppendTimeoutId(t),t.buffer=void 0)}},{key:"resetQueue",value:function(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Zs(this.tracks)}},{key:"onBufferCodecs",value:function(e,t){var r,i=this,n=this.tracks,a=Object.keys(t);this.log('BUFFER_CODECS: "'.concat(a,'" (current SB count ').concat(this.sourceBufferCount,")"));var s="audiovideo"in t&&(n.audio||n.video)||n.audiovideo&&("audio"in t||"video"in t),o=!s&&this.sourceBufferCount&&this.media&&a.some(function(e){return!n[e]});s||o?this.warn('Unsupported transition between "'.concat(Object.keys(n),'" and "').concat(a,'" SourceBuffers')):(a.forEach(function(e){var r,a,s=t[e],o=s.id,l=s.codec,u=s.levelCodec,c=s.container,d=s.metadata,h=s.supplemental,f=n[e],v=null==(r=i.transferData)||null==(r=r.tracks)?void 0:r[e],g=null!=v&&v.buffer?v:f,p=(null==g?void 0:g.pendingCodec)||(null==g?void 0:g.codec),m=null==g?void 0:g.levelCodec;f||(f=n[e]={buffer:void 0,listeners:[],codec:l,supplemental:h,container:c,levelCodec:u,metadata:d,id:o});var y=gr(p,m),k=null==y?void 0:y.replace(eo,"$1"),E=gr(l,u),S=null==(a=E)?void 0:a.replace(eo,"$1");E&&y&&k!==S&&("audio"===e.slice(0,5)&&(E=vr(E,i.appendSource)),i.log("switching codec ".concat(p," to ").concat(E)),E!==(f.pendingCodec||f.codec)&&(f.pendingCodec=E),f.container=c,i.appendChangeType(e,c,E))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&"main"===(null==(r=t.audio)?void 0:r.id)&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks()))}},{key:"sourceBufferTracks",get:function(){var e=this;return Object.keys(this.tracks).reduce(function(t,r){var i=e.tracks[r];return t[r]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},t},{})}},{key:"appendChangeType",value:function(e,t,r){var i=this,n="".concat(t,";codecs=").concat(r),a={label:"change-type=".concat(n),execute:function(){var a=i.tracks[e];if(a){var s=a.buffer;null!=s&&s.changeType&&(i.log("changing ".concat(e," sourceBuffer type to ").concat(n)),s.changeType(n),a.codec=r,a.container=t)}i.shiftAndExecuteNext(e)},onStart:function(){},onComplete:function(){},onError:function(t){i.warn("Failed to change ".concat(e," SourceBuffer type"),t)}};this.append(a,e,this.isPending(this.tracks[e]))}},{key:"blockAudio",value:function(e){var t,r=this,i=e.start,n=i+.05*e.duration;if(!(!0===(null==(t=this.fragmentTracker.getAppendedFrag(i,de.MAIN))?void 0:t.gap))){var a={label:"block-audio",execute:function(){var e,t;(r.lastVideoAppendEnd>n||Bi.isBuffered(null==(e=r.tracks.video)?void 0:e.buffer,n)||!0===(null==(t=r.fragmentTracker.getAppendedFrag(n,de.MAIN))?void 0:t.gap))&&r.unblockAudio()},onStart:function(){},onComplete:function(){},onError:function(e){r.warn("Error executing block-audio operation",e)}};this.append(a,"audio",!0)}}},{key:"unblockAudio",value:function(){this.operationQueue&&this.operationQueue.unblockAudio()}},{key:"onBufferAppending",value:function(e,t){var r=this,i=this.tracks,n=t.data,a=t.type,s=t.parent,o=t.frag,l=t.part,u=t.chunkMeta,c=t.offset,d=u.buffering[a],h=pe(o)&&!l&&!o.gap&&!u.partial&&!u.iframe,f=null,v=!1,g=o.sn,p=o.cc,m=self.performance.now();d.start=m;var y=o.stats.buffering,k=l?l.stats.buffering:null;0===y.start&&(y.start=m),0===(null==k?void 0:k.start)&&(k.start=m);var E=i.audio,T=!1;"audio"===a&&"audio/mpeg"===(null==E?void 0:E.container)&&(T=!this.lastMpegAudioChunk||1===u.id||this.lastMpegAudioChunk.sn!==u.sn,this.lastMpegAudioChunk=u);var A=i.video,b=null==A?void 0:A.buffer;if(b&&"initSegment"!==g&&void 0!==c){var I=null==E?void 0:E.buffer,R=l||o;if("audio"===a&&"main"!==s&&!A.ending&&!A.ended&&I&&Bi.getBuffered(I).length){var L=R.start+.05*R.duration,P=Bi.getBuffered(b),w=this.currentOp("video");P.length||w?!Bi.isBuffered(b,L)&&this.lastVideoAppendEnd<L&&this.blockAudio(R):this.blockAudio(R)}else if("video"===a){var C=R.end,D=this.lastVideoAppendEnd-C;this.lastVideoAppendEnd=C,D<0||D>R.duration?this.unblockAudio():this.isAudioBlocked()&&this.executeNext("audio")}}var _=(l||o).start,M={label:"append-".concat(a),execute:function(){var e;d.executeStart=self.performance.now();var t=null==(e=r.tracks[a])?void 0:e.buffer;t&&(h&&(f=Bi.timeRangesToArray(Bi.getBuffered(t)),v=uo(lo(f,o),o)),T?r.updateTimestampOffset(t,_,.1,a,g,p):void 0!==c&&Z(c)&&r.updateTimestampOffset(t,c,1e-6,a,g,p)),r.appendExecutor(n,a)},onStart:function(){},onComplete:function(){r.clearBufferAppendTimeoutId(r.tracks[a]);var e=self.performance.now();d.executeEnd=d.end=e,0===y.first&&(y.first=e),0===(null==k?void 0:k.first)&&(k.first=e);var t={};if(r.sourceBuffers.forEach(function(e){var r=S(e,2),i=r[0],n=r[1];i&&(t[i]=Bi.getBuffered(n))}),h){var i=r.getFragmentAppendProgress(o),n=t[a];if(n&&f){var c=lo(Bi.timeRangesToArray(n),o);i.progressed||(i.progressed=c-lo(f,o)>.001);var g=v&&uo(c,o);i.fullyBuffered[a]=(void 0===i.fullyBuffered[a]||i.fullyBuffered[a])&&g}}r.hls.trigger(ne.BUFFER_APPENDED,{type:a,frag:o,part:l,chunkMeta:u,parent:s,timeRanges:t})},onError:function(e){var t;r.clearBufferAppendTimeoutId(r.tracks[a]);var i=e.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==e.name||"quota"in e;if(i&&!r._quotaEvictionPending[a]){var c=r.getBackBufferEvictionTarget(a,n.byteLength,o.type);if(c>0){r._quotaEvictionPending[a]=!0,r.log('QuotaExceededError on "'.concat(a,'" append sn: ').concat(g," - evicting back buffer to ").concat(c.toFixed(3),"s and retrying"));var d=r.getFlushOp(a,0,c),f=r.getClearEvictionPendingOp(a);return void r.insertNext([d,M,f],a)}r.warn('QuotaExceededError on "'.concat(a,'" sn: ').concat(g," - no back buffer available to evict"))}h&&(r.getFragmentAppendProgress(o).errored=!0);var v={type:re.MEDIA_ERROR,parent:s,details:ie.BUFFER_APPEND_ERROR,sourceBufferName:a,frag:o,part:l,chunkMeta:u,error:e,err:e,fatal:!1},p=null==(t=r.media)?void 0:t.error;if(e.name!==to||0!==r.sourceBufferCount||r.media&&0!==r.pendingTrackCount){var m;i&&(v.details=ie.BUFFER_FULL_ERROR);var y=++r.appendErrors[a],k=r.hls.config.appendErrorMaxRetry;r.warn("Failed ".concat(y,"/").concat(k+1,' times to append segment in "').concat(a,'" sourceBuffer with error: ').concat(e.message)),y>=k&&(v.fatal=!i);var E=null==(m=r.mediaSource)?void 0:m.readyState;("ended"===E||"closed"===E||p)&&(r.warn('MediaSource readyState "'.concat(E,'" during SourceBuffer').concat(so(v.fatal,p))),v.details=ie.MEDIA_SOURCE_REQUIRES_RESET)}else v.errorAction=vi(!0);r.appendError=v,r.hls.trigger(ne.ERROR,v),i&&r.hls&&r.trimBuffers(o.start,1)}};this.log('queuing "'.concat(a,'" append sn: ').concat(g).concat(l?" p: "+l.index:""," of ").concat(s," playlist ").concat(o.level," cc: ").concat(p," offset: ").concat(c," bytes: ").concat(n.byteLength)),this.append(M,a,this.isPending(this.tracks[a]))}},{key:"getClearEvictionPendingOp",value:function(e){var t=this;return{label:"clear",execute:function(){t._quotaEvictionPending[e]=!1,t.shiftAndExecuteNext(e)},onStart:function(){},onComplete:function(){},onError:function(){}}}},{key:"getFlushOp",value:function(e,t,r){var i=this;return this.log('queuing "'.concat(e,'" remove ').concat(t,"-").concat(r)),{label:"remove",execute:function(){i.removeExecutor(e,t,r)},onStart:function(){},onComplete:function(){var n,a=null==(n=i.tracks[e])?void 0:n.buffer;i.log("Remove request ".concat(t,"-").concat(r," from ").concat(e," Source Buffer complete > buffer: ").concat(a?ia(Bi.getBuffered(a)):"(detached)")),i.hls.trigger(ne.BUFFER_FLUSHED,{type:e,start:t,end:r})},onError:function(n){i.warn("Failed to remove ".concat(t,"-").concat(r,' from "').concat(e,'" SourceBuffer'),n),i.hls.trigger(ne.BUFFER_FLUSHED,{type:e,start:0,end:0,error:n})}}}},{key:"onBufferFlushing",value:function(e,t){var r=this,i=t.type,n=t.startOffset,a=t.endOffset;i&&"audio"!==i||this.unblockAudio(),i?this.append(this.getFlushOp(i,n,a),i):this.sourceBuffers.forEach(function(e){var t=S(e,1)[0];t&&r.append(r.getFlushOp(t,n,a),t)})}},{key:"onFragParsed",value:function(e,t){var r=this,i=t.frag,n=t.part,a=t.chunkMeta,s=[],o=n?n.elementaryStreams:i.elementaryStreams;o[ve]?s.push("audiovideo"):(o[he]&&s.push("audio"),o[fe]&&s.push("video"));0===s.length&&this.log("Fragments must have at least one ElementaryStreamType set. ".concat(i.type," ").concat(i.level," ").concat(n?"part: ".concat(n.index," of "):"","sn: ").concat(i.sn)),this.blockBuffers(function(){var e=self.performance.now();i.stats.buffering.end=e,n&&(n.stats.buffering.end=e);var t=n?n.stats:i.stats;r.checkAppendProgress(i,n,a,s),r.hls&&(r.hls.trigger(ne.FRAG_BUFFERED,{frag:i,part:n,stats:t,id:i.type,chunkMeta:a}),!n&&i.gap&&t.retry&&r.log("Nothing buffered for ".concat(i.type," level: ").concat(i.level," sn: ").concat(i.sn," retries ").concat(t.retry)))},s).catch(function(e){r.warn("Fragment buffered callback ".concat(e.message)),r.stepOperationQueue(r.sourceBufferTypes)})}},{key:"onFragChanged",value:function(e,t){var r,i,n=this,a=null==(r=this.hls)?void 0:r.config;if(a){var s=a.backBufferLength,o=a.frontBufferFlushThreshold;this.trimBuffers(o,s,t.frag,t.previousFrag);var l=t.frag.elementaryStreams,u=this.appendErrors,c=null==(i=this.appendError)?void 0:i.sourceBufferName;Object.keys(l).forEach(function(e){l[e]&&(u[e]=0,e===c&&(n.appendError=void 0),"audio"===e||"video"===e?(u.audiovideo=0,"audiovideo"===c&&(n.appendError=void 0)):(u.audio=0,u.video=0,"audiovideo"!==c&&(n.appendError=void 0)))})}}},{key:"bufferedToEnd",get:function(){var e=this;return this.sourceBufferCount>0&&!this.sourceBuffers.some(function(t){var r=S(t,1)[0];if(r){var i=e.tracks[r];if(i)return!i.ended||i.ending}return!1})}},{key:"onBufferEos",value:function(e,t){var r,i=this;this.sourceBuffers.forEach(function(e){var r=S(e,1)[0];if(r){var n=i.tracks[r];t.type&&t.type!==r||(n.ending=!0,n.ended||(n.ended=!0,i.log("".concat(r," buffer reached EOS"))))}});var n=!1!==(null==(r=this.overrides)?void 0:r.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some(function(e){var t,r=S(e,1)[0];return r&&!(null!=(t=i.tracks[r])&&t.ended)})?(this.unblockAudio(),n?(this.log("Queueing EOS"),this.blockUntilOpen(function(){i.tracksEnded();var e=i.mediaSource;"open"===(null==e?void 0:e.readyState)?(i.log("Calling mediaSource.endOfStream()"),e.endOfStream(),i.hls.trigger(ne.BUFFERED_TO_END,void 0)):e&&i.log("Could not call mediaSource.endOfStream(). mediaSource.readyState: ".concat(e.readyState))})):(this.tracksEnded(),this.hls.trigger(ne.BUFFERED_TO_END,void 0))):"video"===t.type&&this.unblockAudio()}},{key:"tracksEnded",value:function(){var e=this;this.sourceBuffers.forEach(function(t){var r=S(t,1)[0];if(null!==r){var i=e.tracks[r];i&&(i.ending=!1)}})}},{key:"onLevelUpdated",value:function(e,t){var r=t.details;r.fragments.length&&(this.details=r,this.updateDuration())}},{key:"updateDuration",value:function(){var e=this;this.blockUntilOpen(function(){var t=e.getDurationAndRange();t&&e.updateMediaSource(t)})}},{key:"onError",value:function(e,t){if(t.details===ie.BUFFER_APPEND_ERROR&&t.frag){var r,i=null==(r=t.errorAction)?void 0:r.nextAutoLevel;Z(i)&&i!==t.frag.level&&this.resetAppendErrors()}}},{key:"getBackBufferEvictionTarget",value:function(e,t,r){var i=this.media;return i?this.fragmentTracker.getBackBufferEvictionEnd(i.currentTime,r,t):0}},{key:"getFragmentAppendProgress",value:function(e){var t,r=oo(e),i=this.fragmentAppendProgress[r];return(null==(t=i)?void 0:t.stats)!==e.stats&&(i={stats:e.stats,progressed:!1,errored:!1,fullyBuffered:Object.create(null)},this.fragmentAppendProgress[r]=i),i}},{key:"checkAppendProgress",value:function(e,t,r,i){if(!(t||!pe(e)||e.gap||r.iframe||r.partial)){var n=oo(e),a=this.fragmentAppendProgress[n];delete this.fragmentAppendProgress[n];var s=e.stats.buffering;if(!s.start||s.first){var o=(null==a?void 0:a.stats)===e.stats?a:void 0;if(null==o||!o.errored){var l=i.length>0&&i.every(function(e){return!0===(null==o?void 0:o.fullyBuffered[e])});if(null!=o&&o.progressed||l)delete this.appendsWithoutProgress[n];else if(o||0!==i.length){var u=(this.appendsWithoutProgress[n]||0)+1,c=this.hls;u>=c.config.appendErrorMaxRetry?delete this.appendsWithoutProgress[n]:this.appendsWithoutProgress[n]=u,this.warn("Fragment ".concat(e.sn," of ").concat(e.type," playlist ").concat(e.level," appended ").concat(u," time").concat(u>1?"s":""," without buffered range growth")),c.trigger(ne.ERROR,{type:re.MEDIA_ERROR,details:ie.BUFFER_APPEND_NO_PROGRESS,fatal:!1,frag:e,chunkMeta:r,parent:e.type,appendsWithoutProgress:u,error:new Error("Fragment append did not increase buffered coverage (".concat(u,")"))})}}}}}},{key:"resetAppendProgress",value:function(){this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null)}},{key:"resetAppendErrors",value:function(){this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0}},{key:"trimBuffers",value:function(e,t,r,i){var n=this.hls,a=this.details,s=this.media;if(s&&null!==a&&this.sourceBufferCount){var o=n.config,l=s.currentTime,u=a.levelTargetDuration;t=a.live&&null!==o.liveBackBufferLength?o.liveBackBufferLength:t;var c=-1/0;if(Z(t)&&t>=0){var d=Math.max(t,u);c=Math.floor(l/u)*u-d}if(r){var h=this.getLoopBackBufferFlushEnd(r,null!=i?i:null);h>0&&(c=Math.max(c,h))}if(c>0&&this.flushBackBuffer(l,u,c),Z(e)&&e>0){var f=Math.max(o.maxBufferLength,e),v=Math.max(f,u),g=Math.floor(l/u)*u+v;this.flushFrontBuffer(l,u,g)}}}},{key:"getLoopBackBufferFlushEnd",value:function(e,t){var r,i=this.media;if(!1===(null==(r=this.hls)?void 0:r.config.loopBackBufferFlush)||null==i||!i.loop||!t||e.level<=t.level)return 0;var n=e.elementaryStreams,a=n.video,s=n.audiovideo;if(null!=a&&a.partial||null!=s&&s.partial)return 0;var o=this.getEarliestElementaryStreamStart(e)-.25;return o<=0?0:(this.log("Flushing lower quality back buffer for loop: level ".concat(e.level,", range [0-").concat(o.toFixed(3),"]")),o)}},{key:"getEarliestElementaryStreamStart",value:function(e){var t=e.elementaryStreams,r=t.audio,i=t.video,n=t.audiovideo,a=e.start;return n?a=Math.min(a,n.startDTS):(r&&(a=Math.min(a,r.startDTS)),i&&(a=Math.min(a,i.startDTS))),a}},{key:"flushBackBuffer",value:function(e,t,r){var i=this;this.sourceBuffers.forEach(function(e){var t=S(e,2),n=t[0],a=t[1];if(a){var s=Bi.getBuffered(a);if(s.length>0&&r>s.start(0)){var o,l,u;i.hls.trigger(ne.BACK_BUFFER_REACHED,{bufferEnd:r});var c=i.tracks[n];if(null!=(o=i.details)&&o.live)i.hls.trigger(ne.LIVE_BACK_BUFFER_REACHED,{bufferEnd:r});else if(null!=c&&c.ended&&(null==(l=i.media)||!l.loop||!1===(null==(u=i.hls)?void 0:u.config.loopBackBufferFlush)))return void i.log("Cannot flush ".concat(n," back buffer while SourceBuffer is in ended state"));i.hls.trigger(ne.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:n})}}})}},{key:"flushFrontBuffer",value:function(e,t,r){var i=this;this.sourceBuffers.forEach(function(t){var n=S(t,2),a=n[0],s=n[1];if(s){var o=Bi.getBuffered(s),l=o.length;if(l<2)return;var u=o.start(l-1),c=o.end(l-1);if(r>u||e>=u&&e<=c)return;i.hls.trigger(ne.BUFFER_FLUSHING,{startOffset:u,endOffset:1/0,type:a})}})}},{key:"getDurationAndRange",value:function(){var e,t=this.details,r=this.mediaSource;if(!t||!this.media||"open"!==(null==r?void 0:r.readyState))return null;var i=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&r.setLiveSeekableRange){var n=Math.max(0,t.fragmentStart);return{duration:1/0,start:n,end:Math.max(n,i)}}return{duration:1/0}}var a=null==(e=this.overrides)?void 0:e.duration;if(a)return Z(a)?{duration:a}:null;var s=this.media.duration;return i>(Z(r.duration)?r.duration:0)&&i>s||!Z(s)?{duration:i}:null}},{key:"updateMediaSource",value:function(e){var t=e.duration,r=e.start,i=e.end,n=this.mediaSource;n&&this.media&&"open"===n.readyState&&(n.duration!==t&&(Z(t)&&this.log("Updating MediaSource duration to ".concat(t.toFixed(3))),n.duration=t),void 0!==r&&void 0!==i&&(this.log("MediaSource duration is set to ".concat(n.duration,". Setting seekable range to ").concat(r,"-").concat(i,".")),n.setLiveSeekableRange(r,i)))}},{key:"tracksReady",get:function(){var e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}},{key:"checkPendingTracks",value:function(){var e=this.bufferCodecEventsTotal,t=this.pendingTrackCount,r=this.tracks;if(this.log("checkPendingTracks (pending: ".concat(t," codec events expected: ").concat(e,") ").concat(Nr(r))),this.tracksReady){var i,n=null==(i=this.transferData)?void 0:i.tracks;n&&Object.keys(n).length?this.attachTransferred():this.createSourceBuffers()}}},{key:"bufferCreated",value:function(){var e=this;if(this.sourceBufferCount){var t={};this.sourceBuffers.forEach(function(r){var i=S(r,2),n=i[0],a=i[1];if(n){var s=e.tracks[n];t[n]={buffer:a,container:s.container,codec:s.codec,supplemental:s.supplemental,levelCodec:s.levelCodec,id:s.id,metadata:s.metadata}}}),this.hls.trigger(ne.BUFFER_CREATED,{tracks:t}),this.log("SourceBuffers created. Running queue: ".concat(this.operationQueue)),this.sourceBuffers.forEach(function(t){var r=S(t,1)[0];e.executeNext(r)})}else{var r=new Error("could not create source buffer for media codec(s)");this.hls.trigger(ne.ERROR,{type:re.MEDIA_ERROR,details:ie.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:r,reason:r.message})}}},{key:"createSourceBuffers",value:function(){var e=this.tracks,t=this.sourceBuffers,r=this.mediaSource;if(!r)throw new Error("createSourceBuffers called when mediaSource was null");for(var i in e){var n=i,a=e[n];if(this.isPending(a)){var s=this.getTrackCodec(a,n),o="".concat(a.container,";codecs=").concat(s);a.codec=s,this.log("creating sourceBuffer(".concat(o,")").concat(this.currentOp(n)?" Queued":""," ").concat(Nr(a)));try{var l=r.addSourceBuffer(o),u=ao(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(ne.ERROR,{type:re.MEDIA_ERROR,details:ie.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:n,mimeType:o,parent:a.id})}this.trackSourceBuffer(n,a)}}this.bufferCreated()}},{key:"clearBufferAppendTimeoutId",value:function(e){e&&(self.clearTimeout(e.bufferAppendTimeoutId),e.bufferAppendTimeoutId=void 0)}},{key:"getTrackCodec",value:function(e,t){var r=e.supplemental,i=e.codec;r&&("video"===t||"audiovideo"===t)&&or(r,"video")&&(i=function(e,t){var r=[];if(e)for(var i=e.split(","),n=0;n<i.length;n++)sr(i[n],"video")||r.push(i[n]);return t&&r.push(t),r.join(",")}(i,r));var n=gr(i,e.levelCodec);return n?"audio"===t.slice(0,5)?vr(n,this.appendSource):n:""}},{key:"trackSourceBuffer",value:function(e,t){var r=this,i=t.buffer;if(i){var n=this.getTrackCodec(t,e);this.tracks[e]={buffer:i,codec:n,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",function(e,t){var i=t.removedRanges;null!=i&&i.length&&(r.log("".concat(e," buffer removed ").concat(ia(i))),r.hls.trigger(ne.BUFFER_FLUSHED,{type:e,start:i.start(0),end:i.end(i.length-1)}))})}}},{key:"mediaSrc",get:function(){var e,t,r=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==r?void 0:r.src}},{key:"onSBUpdateStart",value:function(e){var t=this.currentOp(e);t&&t.onStart()}},{key:"onSBUpdateEnd",value:function(e){var t,r,i=this;if("closed"!==(null==(t=this.mediaSource)?void 0:t.readyState)){var n=this.currentOp(e);if(n){if(n.onComplete(),null==(r=this.tracks[e])||null==(r=r.buffer)?void 0:r.updating)return this.log("".concat(e,' SourceBuffer updating on "updateend"')),void this.blockUntilOpen(function(){i.shiftAndExecuteNext(e)});this.shiftAndExecuteNext(e)}}else this.resetBuffer(e)}},{key:"onSBUpdateError",value:function(e,t){var r,i=null==(r=this.mediaSource)?void 0:r.readyState,n=new Error("".concat(e," SourceBuffer error. MediaSource readyState: ").concat(i));this.error("".concat(n.message),t),this.hls.trigger(ne.ERROR,{type:re.MEDIA_ERROR,details:ie.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:n,fatal:!1});var a=this.currentOp(e);a&&a.onError(n)}},{key:"updateTimestampOffset",value:function(e,t,r,i,n,a){var s=t-e.timestampOffset;Math.abs(s)>=r&&(this.log("Updating ".concat(i," SourceBuffer timestampOffset to ").concat(t," (sn: ").concat(n," cc: ").concat(a,")")),e.timestampOffset=t)}},{key:"removeExecutor",value:function(e,t,r){var i=this.media,n=this.mediaSource,a=this.tracks[e],s=null==a?void 0:a.buffer;if(!i||!n||!s)throw new Error("Attempting to remove from the ".concat(e," SourceBuffer, but it does not exist"));var o,l=Z(i.duration)?i.duration:1/0,u=Z(n.duration)?n.duration:1/0,c=Math.max(0,t);if(c>=u)return null==(o=this.currentOp(e))||o.onComplete(),void this.shiftAndExecuteNext(e);var d=Math.min(r,l,u);if(!(d>c)||a.ending&&!a.ended)throw new Error("Cannot remove ".concat(d<=c?"invalid range (".concat(c," >= ").concat(d,") "):"","from the ").concat(e," SourceBuffer").concat(a.ending?" while track ending":""));a.ended=!1,this.log("Removing [".concat(c,",").concat(d,"] from the ").concat(e," SourceBuffer")),s.remove(c,d)}},{key:"appendExecutor",value:function(e,t){var r=this,i=this.tracks[t],n=null==i?void 0:i.buffer;if(!n)throw new ro("Attempting to append to the ".concat(t," SourceBuffer, but it does not exist"));if(i.ending=!1,i.ended=!1,this.hls.config.appendTimeout!==1/0){var a=this.calculateAppendTimeoutTime(n);i.bufferAppendTimeoutId=self.setTimeout(function(){return r.appendTimeoutHandler(t,n,a)},a)}n.appendBuffer(e)}},{key:"appendTimeoutHandler",value:function(e,t,r){this.log("Received timeout after ".concat(r,"ms for append on ").concat(e," source buffer. Aborting and triggering error."));try{t.abort()}catch(t){this.log("Failed to abort append on ".concat(e," source buffer after timeout."))}var i=this.currentOp(e);i&&i.onError(new Error("".concat(e,"-append-timeout")))}},{key:"calculateAppendTimeoutTime",value:function(e){var t=10;this.details&&(t=this.details.levelTargetDuration);var r=2*t*1e3;if(null===this.media)return r;var i=Bi.bufferInfo(e,this.media.currentTime,0);return i.len?(r=Math.max(1e3*i.len,r),Math.max(this.hls.config.appendTimeout,r)):r}},{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=S(e,2),r=t[0],i=t[1];return r&&i.updating})}},{key:"isQueued",value:function(){var e=this;return this.sourceBuffers.some(function(t){var r=S(t,1)[0];return r&&!!e.currentOp(r)})}},{key:"isPending",value:function(e){return!!e&&!e.buffer}},{key:"isAudioBlocked",value:function(){var e;return"block-audio"===(null==(e=this.currentOp("audio"))?void 0:e.label)}},{key:"isAudioBlocking",value:function(){return!!this.operationQueue&&this.operationQueue.audioBlocking()}},{key:"blockBuffers",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.sourceBufferTypes;if(!r.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);var i=this.operationQueue,n=2===r.length&&this.isAudioBlocking()?[this.appendBlocker("video")]:r.map(function(e){return t.appendBlocker(e)});return Promise.all(n).then(function(r){i===t.operationQueue&&(e(),t.stepOperationQueue(t.sourceBufferTypes))})}},{key:"stepOperationQueue",value:function(e){var t=this;e.forEach(function(e){var r,i=null==(r=t.tracks[e])?void 0:r.buffer;!i||i.updating||"audio"===e&&t.isAudioBlocked()||t.shiftAndExecuteNext(e)})}},{key:"append",value:function(e,t,r){this.operationQueue&&this.operationQueue.append(e,t,r)}},{key:"insertNext",value:function(e,t){this.operationQueue&&this.operationQueue.insertNext(e,t)}},{key:"appendBlocker",value:function(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}},{key:"currentOp",value:function(e){return this.operationQueue?this.operationQueue.current(e):null}},{key:"executeNext",value:function(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}},{key:"shiftAndExecuteNext",value:function(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}},{key:"pendingTrackCount",get:function(){var e=this;return Object.keys(this.tracks).reduce(function(t,r){return t+(e.isPending(e.tracks[r])?1:0)},0)}},{key:"sourceBufferCount",get:function(){return this.sourceBuffers.reduce(function(e,t){return e+(S(t,1)[0]?1:0)},0)}},{key:"sourceBufferTypes",get:function(){return this.sourceBuffers.map(function(e){return S(e,1)[0]}).filter(function(e){return!!e})}},{key:"addBufferListener",value:function(e,t,r){var i=this.tracks[e];if(i){var n=i.buffer;if(n){var a=r.bind(this,e);i.listeners.push({event:t,listener:a}),ta(n,t,a)}}}},{key:"removeBufferListeners",value:function(e){var t=this.tracks[e];if(t){var r=t.buffer;r&&(t.listeners.forEach(function(e){ra(r,e.event,e.listener)}),t.listeners.length=0)}}}])}(Be);function no(e){var t=e.querySelectorAll("source");[].slice.call(t).forEach(function(t){e.removeChild(t)})}function ao(e){return"audio"===e?1:0}function so(e,t){return"".concat(e?"":" - triggering recovery").concat(t?" with HTMLMediaElement Error: "+t.message:"")}function oo(e){return"".concat(e.type,"_").concat(e.sn,"_").concat(e.level)}function lo(e,t){for(var r=t.start,i=t.end,n=0,a=0;a<e.length;a++){var s=e[a];if(s.start>=i)break;var o=Math.max(r,s.start),l=Math.min(i,s.end);l>o&&(n+=l-o)}return n}function uo(e,t){return t.duration-e<=.05}var co=function(){function e(t){s(this,e),this.hls=null,this.autoLevelCapping=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.observer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.media=null,this.restrictedLevels=[],this.clientRect=null,this.registerListeners()}return l(e,[{key:"setStreamController",value:function(e){this.streamController=e}},{key:"destroy",value:function(){this.hls&&this.unregisterListener(),(this.timer||this.observer)&&this.stopCapping(),this.media=this.clientRect=this.hls=null,this.streamController=void 0}},{key:"registerListeners",value:function(){var e=this.hls;e&&(e.on(ne.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(ne.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(ne.MANIFEST_PARSED,this.onManifestParsed,this),e.on(ne.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(ne.BUFFER_CODECS,this.onBufferCodecs,this),e.on(ne.MEDIA_DETACHING,this.onMediaDetaching,this))}},{key:"unregisterListener",value:function(){var e=this.hls;e&&(e.off(ne.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(ne.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(ne.MANIFEST_PARSED,this.onManifestParsed,this),e.off(ne.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(ne.BUFFER_CODECS,this.onBufferCodecs,this),e.off(ne.MEDIA_DETACHING,this.onMediaDetaching,this))}},{key:"onFpsDropLevelCapping",value:function(e,t){if(this.hls){var r=this.hls.levels[t.droppedLevel];this.isLevelAllowed(r)&&this.restrictedLevels.push({bitrate:r.bitrate,height:r.height,width:r.width})}}},{key:"onMediaAttaching",value:function(e,t){var r=t.media;this.clientRect=null,this.hls&&(r instanceof HTMLVideoElement?(this.media=r,this.hls.config.capLevelToPlayerSize&&this.observe()):this.media=null,(this.timer||this.observer)&&this.hls.levels.length>1&&this.detectPlayerSize())}},{key:"onManifestParsed",value:function(e,t){this.restrictedLevels=[],t.video&&this.startCapping(),this.onLevelsUpdated()}},{key:"onLevelsUpdated",value:function(){if(this.hls)if((this.timer||this.observer)&&(Z(this.autoLevelCapping)||this.clientRect))this.detectPlayerSize();else if(void 0===this.observer&&void 0===this.timer){var e=this.hls.levels;e.length>1&&e.some(function(e){return!!e.videoCodec})&&this.startCapping()}}},{key:"onBufferCodecs",value:function(e,t){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||!this.hls)return void(this.clientRect=null);var e=this.hls.levels;if(e.length>1){var t=this.hls,r=this.getMaxLevel(e.length-1);r!==this.autoLevelCapping&&t.logger.log("Setting autoLevelCapping to ".concat(r,": ").concat(e[r].height,"p@").concat(e[r].bitrate," for media ").concat(this.mediaWidth,"x").concat(this.mediaHeight)),t.autoLevelCapping=r,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}else 1===e.length&&this.stopCapping()}}},{key:"getMaxLevel",value:function(t){var r=this;if(!this.hls)return-1;var i=this.hls.levels;if(!i.length)return-1;var n=i.filter(function(e,i){return r.isLevelAllowed(e)&&i<=t});return this.observer||(this.clientRect=null),e.getMaxLevelByMediaSize(n,this.mediaWidth,this.mediaHeight)}},{key:"observe",value:function(){var e=this,t=self.ResizeObserver;t&&(this.observer=new t(function(t){var r,i=null==(r=t[0])?void 0:r.contentRect;i&&(e.clientRect=i,e.detectPlayerSize())})),this.observer&&this.media&&this.observer.observe(this.media)}},{key:"startCapping",value:function(){var e;this.timer||this.observer||null==(e=this.hls)||!e.config.capLevelToPlayerSize||(self.clearInterval(this.timer),this.timer=void 0,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.observe(),this.observer||(this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3)),this.detectPlayerSize())}},{key:"stopCapping",value:function(){this.restrictedLevels=[],this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0),this.observer&&(this.observer.disconnect(),this.observer=void 0)}},{key:"getDimensions",value:function(){if(this.clientRect)return this.clientRect;var e=this.media,t={width:0,height:0};if(e){var r=e.getBoundingClientRect();t.width=r.width,t.height=r.height,t.width||t.height||(t.width=r.right-r.left||e.width||0,t.height=r.bottom-r.top||e.height||0)}return this.clientRect=t,t}},{key:"mediaWidth",get:function(){return this.getDimensions().width*this.contentScaleFactor}},{key:"mediaHeight",get:function(){return this.getDimensions().height*this.contentScaleFactor}},{key:"contentScaleFactor",get:function(){var e=1;if(!this.hls)return e;var t=this.hls.config,r=t.ignoreDevicePixelRatio,i=t.maxDevicePixelRatio;if(!r)try{e=self.devicePixelRatio}catch(e){}return Math.min(e,i)}},{key:"isLevelAllowed",value:function(e){return!this.restrictedLevels.some(function(t){return e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height})}}],[{key:"getMaxLevelByMediaSize",value:function(e,t,r){if(null==e||!e.length)return-1;for(var i=function(e,t){return!t||(e.width!==t.width||e.height!==t.height)},n=e.length-1,a=Math.max(t,r),s=0;s<e.length;s+=1){var o=e[s];if((o.width>=a||o.height>=a)&&i(o,e[s+1])){n=s;break}}return n}}])}(),ho=l(function e(t,r){s(this,e),Array.isArray(t)&&(t=t.map(function(t){return t instanceof e?t:new e(t)})),this.value=t,this.params=r});function fo(e,t,r,i){return new Error("failed to ".concat(e,' "').concat((n=t,Array.isArray(n)?JSON.stringify(n):n instanceof Map?"Map{}":n instanceof Set?"Set{}":"object"===R(n)?JSON.stringify(n):String(n)),'" as ').concat(r),{cause:i});var n}var vo="Bare Item";var go=/[\x00-\x1f\x7f]+/,po=l(function e(t){s(this,e),this.description=t});function mo(e,t,r){return fo("serialize",e,t,r)}function yo(e){if(!1===ArrayBuffer.isView(e))throw mo(e,"Byte Sequence");return":".concat((t=e,btoa(String.fromCharCode.apply(String,b(t)))),":");var t}function ko(e){if(function(e){return e<-999999999999999||999999999999999<e}(e))throw mo(e,"Integer");return e.toString()}function Eo(e){var t=$e(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw mo(e,"Decimal");var r=t.toString();return r.includes(".")?r:"".concat(r,".0")}function So(e){var t,r=(t=e).description||t.toString().slice(7,-1);if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(r))throw mo(r,"Token");return r}function To(e){switch(R(e)){case"number":if(!Z(e))throw mo(e,vo);return Number.isInteger(e)?ko(e):Eo(e);case"string":return function(e){if(go.test(e))throw mo(e,"String");return'"'.concat(e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),'"')}(e);case"symbol":return So(e);case"boolean":return function(e){if("boolean"!=typeof e)throw mo(e,"Boolean");return e?"?1":"?0"}(e);case"object":if(e instanceof Date)return function(e){return"@".concat(ko(e.getTime()/1e3))}(e);if(e instanceof Uint8Array)return yo(e);if(e instanceof po)return So(e);default:throw mo(e,vo)}}function Ao(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw mo(e,"Key");return e}function bo(e){return null==e?"":Object.entries(e).map(function(e){var t=S(e,2),r=t[0],i=t[1];return!0===i?";".concat(Ao(r)):";".concat(Ao(r),"=").concat(To(i))}).join("")}function Io(e){return e instanceof ho?"".concat(To(e.value)).concat(bo(e.params)):To(e)}function Ro(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{whitespace:!0};if("object"!==R(e)||null==e)throw mo(e,"Dict");var r=e instanceof Map?e.entries():Object.entries(e),i=null!=t&&t.whitespace?" ":"";return Array.from(r).map(function(e){var t=S(e,2),r=t[0],i=t[1];i instanceof ho==!1&&(i=new ho(i));var n,a=Ao(r);return!0===i.value?a+=bo(i.params):(a+="=",Array.isArray(i.value)?a+="(".concat((n=i).value.map(Io).join(" "),")").concat(bo(n.params)):a+=Io(i)),a}).join(",".concat(i))}function Lo(e,t){return Ro(e,t)}var Po=["url"],wo=["version","eventTargets","sid","transmissionMode"],Co=["customData","headers"],Do=function(e){return e instanceof ho?new ho(Math.round(e.value),e.params):Math.round(e)},_o=function(e){return Array.isArray(e)?e.map(Do):Do(e)},Mo=function(e,t){return Array.isArray(e)?e.map(function(e){return Mo(e,t)}):e instanceof ho&&"string"==typeof e.value?new ho(Mo(e.value,t),e.params):(t.baseUrl&&(e=function(e,t){var r;try{r=new URL(e)}catch(t){return e}var i=new URL(t);if(r.origin!==i.origin)return e;for(var n=r.pathname.split("/").slice(1),a=i.pathname.split("/").slice(1,-1),s=Math.min(n.length,a.length),o=0;o<s&&n[o]===a[o];o++)n.shift(),a.shift();for(;a.length;)a.shift(),n.unshift("..");return n.join("/")+r.search+r.hash}(e,(r=t.baseUrl,(i="string"==typeof r?new URL(r):r).origin+i.pathname.substring(0,i.pathname.lastIndexOf("/")+1)))),1===t.version?encodeURIComponent(e):e);var r,i},xo=function(e){return e instanceof ho?new ho(100*Math.round(e.value/100),e.params):100*Math.round(e/100)},Oo=function(e){return Array.isArray(e)?e.map(xo):xo(e)},Fo={br:_o,d:_o,bl:Oo,dl:Oo,mtp:Oo,nor:function(e,t){var r=e;return t.version>=2&&(e instanceof ho&&"string"==typeof e.value?r=new ho([e]):"string"==typeof e&&(r=[e])),Mo(r,t)},rtp:Oo,tb:_o},No="rr",Bo="bc",Uo="e",Vo=No,Go="ce",Ho=new Map([["ps","sta"],["pr","pr"],["c","cid"],["b","bg"],["bc","br"]]),Ko="event",jo="request",qo=["cen","e","h","ts"],Wo=["ab","bg","bl","br","bs","bsa","bsd","bsda","cdn","cid","cs","d","dfa","dl","ec","lab","lb","ltc","msd","mtp","nor","nr","ot","pb","pr","pt","rtp","sf","sid","sn","st","sta","su","tab","tb","tbl","tpb","v"],Yo=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function zo(e){return Yo.test(e)}var Xo=new Set(Wo);function Qo(e){return Xo.has(e)||zo(e)}var $o=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],Jo=new Set($o);function Zo(e){return Jo.has(e)}var el=new Set(qo);var tl=new Set(["ab","bl","br","bsa","bsd","bsda","lab","lb","mtp","pb","tab","tb","tbl","tpb"]),rl=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"],il=new Set(rl);function nl(e){return il.has(e)||zo(e)}var al=new Set(["ot","sf","st","e","sta"]);function sl(e){return al.has(e)}function ol(e){return"number"==typeof e?Z(e):null!=e&&""!==e&&!1!==e}var ll=c(c({},Ko,function(e){return Qo(e)||Zo(e)||el.has(e)}),jo,Qo);function ul(e,t){var r;return Array.isArray(e)?(t&&(r=e.find(function(e){var r;return(null==(r=e.params)?void 0:r.ot)===t})),r||(r=e[0]),ul(r)):e instanceof ho?e.value:e}function cl(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r={};if(null==e||"object"!==R(e))return r;var i=t.version||e.v||2,n=t.reportingMode||jo,a=1===i?function(e){for(var t={},r=0,i=Object.entries(e);r<i.length;r++){var n=S(i[r],2),a=n[0],s=n[1];if(null!=s)if("nor"===a){var o,l=(Array.isArray(s)?s:[s])[0];l instanceof ho?(t.nor=l.value,null!=(o=l.params)&&o.r&&(t.nrr=l.params.r)):t.nor=l}else tl.has(a)?t[a]=ul(s,e.ot):t[a]=s;else t[a]=s}return t}(e):e,s=1===i?nl:ll[n],o=Object.keys(a).filter(s);a.e&&a.e!==No&&(o=o.filter(function(e){return!Zo(e)}));var l=t.filter;"function"==typeof l&&(o=o.filter(l));var c=n===Ko;if(c){var d=a.e;o.includes("e")||null==d||o.push("e"),o.includes("ts")||o.push("ts"),o.includes("cen")||null==a.cen||"ce"!==d||o.push("cen");var h=d?Ho.get(d):void 0;h&&null!=a[h]&&!o.includes(h)&&o.push(h)}if(0===o.length)return r;i>1&&!o.includes("v")&&o.push("v");var f={version:i,reportingMode:n,baseUrl:t.baseUrl};o.sort();var v,g=u(o);try{for(g.s();!(v=g.n()).done;){var p,m,y=v.value,k=a[y],E=null!=(p=null==(m=t.formatters)?void 0:m[y])?p:Fo[y];if("function"==typeof E&&(k=E(k,f)),"v"===y){if(1===i)continue;k=i}if("pr"!==y||1!==k||c&&"pr"===a.e){c&&"ts"===y&&!Z(k)&&(k=Date.now());var T=c&&!1===k&&"bg"===y&&"b"===a.e;(ol(k)||T)&&(sl(y)&&"string"==typeof k&&(k=new po(k)),r[y]=k)}}}catch(e){g.e(e)}finally{g.f()}return r}var dl="CMCD-Object",hl="CMCD-Request",fl="CMCD-Session",vl="CMCD-Status",gl=hl,pl={ab:dl,br:dl,d:dl,lab:dl,lb:dl,ot:dl,tab:dl,tb:dl,tpb:dl,bl:hl,cs:hl,dfa:hl,dl:hl,ltc:hl,mtp:hl,nor:hl,nrr:hl,pb:hl,sn:hl,sta:hl,su:hl,tbl:hl,cid:fl,msd:fl,sf:fl,sid:fl,st:fl,v:fl,bg:vl,bs:vl,bsa:vl,bsd:vl,bsda:vl,cdn:vl,ec:vl,nr:vl,pr:vl,pt:vl,rtp:vl};function ml(e,t){var r={};if(!e)return r;for(var i,n=Object.keys(e),a=t?(i=t,Object.keys(i).reduce(function(e,t){var r;return null==(r=i[t])||r.forEach(function(r){return e[r]=t}),e},{})):{},s=0,o=n;s<o.length;s++){var l,u=o[s],c=pl[u]||a[u]||gl;(null!=(l=r[c])?l:r[c]={})[u]=e[u]}return r}var yl="CMCD";function kl(e){return Lo(e,{whitespace:!1})}function El(e){return e?kl(cl(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})):""}var Sl=[].concat(rl,Wo,$o,qo).filter(function(e,t,r){return r.indexOf(e)===t}),Tl="m",Al="a",bl="v",Il="av",Rl="i",Ll="tt",Pl="s",wl="p",Cl="k",Dl="r",_l="a",Ml="e",xl="f",Ol="d",Fl="query",Nl="headers";function Bl(e,t,r){var i,n=new Set(null!=(i=t.enabledKeys)?i:[]);return{version:t.version||2,reportingMode:e,filter:function(e){return n.has(e)},baseUrl:r}}var Ul=Object.is,Vl=function(e){return e},Gl=Array.from(Ho,function(e){var t=S(e,2),r=t[0],i=t[1];return"br"===i?{event:r,field:i,equal:function(e,t){return void 0===e||void 0===t?e===t:function(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(var r=0;r<e.length;r++){var i=e[r],n=t[r];if(i!==n){if("number"==typeof i||"number"==typeof n)return!1;if(i.value!==n.value)return!1;var a=i.params,s=n.params,o=a&&Object.keys(a)[0],l=s&&Object.keys(s)[0];if(o!==l)return!1;if(void 0!==o&&void 0!==l&&a&&s&&a[o]!==s[l])return!1}}return!0}(e,t)},snapshot:function(e){return e.slice()}}:{event:r,field:i,equal:Ul,snapshot:Vl}}),Hl=new Map(Gl.map(function(e){return[e.event,e]}));function Kl(e){var t=e.url,r=Re(e,Po);return fetch(t,r)}var jl=function(){return l(function e(t){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Kl;s(this,e),this.timeOrigin=performance.timeOrigin||(null==(r=performance.timing)?void 0:r.fetchStart)||Date.now()-performance.now(),this.data={},this.msd=NaN,this.eventTargets=new Map,this.lastEmitted={},this.requestTarget={sn:0,msdSent:!1},this.config=function(e){var t=e.version,r=void 0===t?2:t,i=e.eventTargets,n=void 0===i?[]:i,a=e.sid,s=void 0===a?Je():a,o=e.transmissionMode,l=void 0===o?Fl:o;return Ie(Ie({},Re(e,wo)),{},{version:r,transmissionMode:l,sid:s,eventTargets:n.reduce(function(e,t){var r,i,n;return null!=t&&t.url&&null!=(r=t.events)&&r.length&&e.push({version:t.version||2,enabledKeys:(null==(i=t.enabledKeys)?void 0:i.slice())||[],url:t.url,events:t.events.slice(),interval:null!=(n=t.interval)?n:30,batchSize:t.batchSize||1}),e},[])})}(t),this.data={cid:this.config.cid,sid:this.config.sid,v:this.config.version},this.requester=i;var n,a=u(this.config.eventTargets);try{for(a.s();!(n=a.n()).done;){var o=n.value;this.eventTargets.set(o,{intervalId:void 0,sn:0,msdSent:!1,queue:[]})}}catch(e){a.e(e)}finally{a.f()}},[{key:"start",value:function(){var e=this;this.eventTargets.forEach(function(t,r){if(e.disarmInterval(t),0!==r.interval&&r.events.includes("t")){var i=function(){e.recordTargetEvent(t,r,"t"),e.processEventTargets()};t.intervalId=setInterval(i,1e3*r.interval),i()}})}},{key:"stop",value:function(){var e=this;arguments.length>0&&void 0!==arguments[0]&&arguments[0]&&this.flush(),this.eventTargets.forEach(function(t){e.disarmInterval(t)})}},{key:"flush",value:function(){this.processEventTargets(!0)}},{key:"update",value:function(e){e.sid&&e.sid!==this.data.sid&&this.resetSession(),e.msd&&!isNaN(e.msd)&&(this.msd=e.msd),this.data=Ie(Ie(Ie({},this.data),e),{},{msd:void 0});for(var t=0,r=Gl;t<r.length;t++){var i=r[t];i.field in e&&!i.equal(this.data[i.field],this.lastEmitted[i.field])&&this.recordEvent(i.event)}}},{key:"recordEvent",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=Hl.get(e);if(i){var n=i.field,a=r[n];void 0!==a&&Ae(this.data,c({},n,a));var s=this.data[n];if(void 0===s)return;if(i.equal(s,this.lastEmitted[n]))return;Ae(this.lastEmitted,c({},n,i.snapshot(s)))}this.eventTargets.forEach(function(i,n){t.recordTargetEvent(i,n,e,r)}),this.processEventTargets()}},{key:"recordTargetEvent",value:function(e,t,r){var i,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};if(t.events.includes(r)){var a=Ie(Ie(Ie({},this.data),n),{},{e:r,ts:null!=(i=n.ts)?i:Date.now(),sn:e.sn++});isNaN(this.msd)||e.msdSent||(a.msd=this.msd,e.msdSent=!0),e.queue.push(a)}}},{key:"recordResponseReceived",value:function(e){var t,r,i,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=e.request,s=null!=(t=n.url)?t:null==a?void 0:a.url;if(s){var o=new URL(s);o.searchParams.delete(yl);var l={url:o.toString(),rc:e.status},u=e.resourceTiming;u&&(null!=u.startTime&&(l.ts=Math.round(this.timeOrigin+u.startTime),null!=u.responseStart&&(l.ttfb=Math.round(u.responseStart-u.startTime))),null!=u.duration&&(l.ttlb=Math.round(u.duration)));var c=null!=(r=null==(i=a.customData)?void 0:i.cmcd)?r:{};this.recordEvent(No,Ie(Ie(Ie({},c),l),n))}}},{key:"applyRequestReport",value:function(e){var t;return null!=(t=this.createRequestReport(e))?t:e}},{key:"isRequestReportingEnabled",value:function(){var e;return!(null==(e=this.config.enabledKeys)||!e.length)}},{key:"createRequestReport",value:function(e,t){var r,i=e.customData,n=void 0===i?{}:i,a=e.headers,s=void 0===a?{}:a,o=Ie(Ie({},Re(e,Co)),{},{headers:Ie({},s),customData:Ie(Ie({},n),{},{cmcd:{}})});if(null==(r=this.config.enabledKeys)||!r.length||!o.url)return o;var l=new URL(o.url),u=Ie(Ie(Ie({},this.data),t),{},{sn:this.requestTarget.sn++}),c=Bl(jo,this.config,o.url);isNaN(this.msd)||this.requestTarget.msdSent||(u.msd=this.msd,this.requestTarget.msdSent=!0);var d=o.customData.cmcd=cl(u,c);switch(this.config.transmissionMode){case Fl:var h=kl(d);h&&(l.searchParams.set(yl,h),o.url=l.toString());break;case Nl:Ae(o.headers,function(e,t){for(var r={},i=ml(e,t),n=0,a=Object.entries(i);n<a.length;n++){var s=S(a[n],2),o=s[0],l=Lo(s[1],{whitespace:!1});l&&(r[o]=l)}return r}(d,c.customHeaderMap))}return o}},{key:"processEventTargets",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],r=!1;this.eventTargets.forEach(function(i,n){var a=i.queue;if(a.length&&(!(a.length<n.batchSize)||t)){var s=t?a.length:n.batchSize,o=a.splice(0,s);e.sendEventReport(n,o).catch(function(){var e;(e=i.queue).unshift.apply(e,b(o))}),r||(r=a.length>0)}}),r&&this.processEventTargets()}},{key:"sendEventReport",value:(e=y().m(function e(t,r){var i,n,a;return y().w(function(e){for(;;)switch(e.n){case 0:return i=Bl(Ko,t),e.n=1,this.requester({url:t.url,method:"POST",headers:{"Content-Type":"application/cmcd"},body:r.map(function(e){return El(e,i)}).join("\n")+"\n"});case 1:if(n=e.v,410!==(a=n.status)){e.n=2;break}this.disposeEventTarget(t),e.n=3;break;case 2:if(!(429===a||a>499&&a<600)){e.n=3;break}throw new Error("Event report failed with status ".concat(a));case 3:return e.a(2)}},e,this)}),t=function(){var t=this,r=arguments;return new Promise(function(i,a){var s=e.apply(t,r);function o(e){n(s,i,a,o,l,"next",e)}function l(e){n(s,i,a,o,l,"throw",e)}o(void 0)})},function(e,r){return t.apply(this,arguments)})},{key:"disarmInterval",value:function(e){clearInterval(e.intervalId),e.intervalId=void 0}},{key:"disposeEventTarget",value:function(e){var t=this.eventTargets.get(e);t&&(this.disarmInterval(t),this.eventTargets.delete(e))}},{key:"resetSession",value:function(){this.eventTargets.forEach(function(e){return e.sn=0}),this.requestTarget.sn=0,this.lastEmitted={}}}]);var e,t}(),ql="h",Wl="v",Yl="l",zl="ll";new Set(rl),new Set(Sl);var Xl=["includeKeys"];function Ql(e){return Object.keys(e).every(zo)}var $l=function(){return l(function e(t){var r=this;s(this,e),this.hls=void 0,this.config=void 0,this.media=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.playerState=void 0,this.reporter=void 0,this.playheadLevel=void 0,this.onWaiting=function(){r.initialized&&(r.starved=!0,r.setPlayerState(Dl)),r.buffering=!0},this.onPlay=function(){r.initialized||r.setPlayerState(Pl)},this.onPlaying=function(){r.initialized||(r.initialized=!0),r.buffering=!1,r.setPlayerState(wl)},this.onPause=function(){r.media&&!r.media.ended&&r.setPlayerState(_l)},this.onSeeking=function(){r.initialized&&r.setPlayerState(Cl)},this.onSeeked=function(){var e;r.initialized&&null!=(e=r.media)&&e.paused&&r.setPlayerState(_l)},this.onRateChange=function(){r.reporter&&r.media&&r.reporter.update({pr:r.media.playbackRate})},this.applyPlaylistData=function(e){try{r.apply(e,{ot:Tl,su:!r.initialized})}catch(e){r.hls.logger.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=function(e){try{var t=e.frag,i=e.part,n=r.hls.levels[t.level],a=r.getObjectType(t,n),s={d:1e3*(i||t).duration,ot:a};if(a===bl||a===Al||a===Il||null==a&&("main"===t.type||"audio"===t.type)){var o,l=n.bitrate/1e3;s.br=[l];var u=r.config.cmcd,c=null!=(o=null==u?void 0:u.rtpSafetyFactor)?o:5;if(s.rtp=100*Math.round(l*c/100),a===Il||null==a&&"main"===t.type){var d=r.getTopBandwidth()/1e3;Z(d)&&(s.tb=[d]);var h=r.getLowestBandwidth()/1e3;Z(h)&&(s.lb=[h])}var f=r.getBufferLength(t);if(Z(f)){var v;s.bl=[f];var g=(null==(v=r.media)?void 0:v.playbackRate)||1;s.dl=100*Math.round(f/g/100)}r.playheadLevel&&(s.pb=[r.playheadLevel.bitrate/1e3]);var p=r.hls.maxAutoLevel;if(p>=0){var m=r.hls.levels[p];m&&(s.tpb=[m.bitrate/1e3])}}var y=i?r.getNextPart(i):r.getNextFrag(t);null!=y&&y.url&&y.url!==t.url&&(y.byteRange.length>0?s.nor=[(k=y.url,E={r:"".concat(y.byteRange[0],"-").concat(y.byteRange[1])},new ho(k,E))]:s.nor=[y.url]),r.apply(e,s)}catch(e){r.hls.logger.warn("Could not generate segment CMCD data.",e)}var k,E},this.recordFragmentResponse=function(e,t,i){var n,a=r.config.cmcd,s=null==a||null==(n=a.eventTargets)?void 0:n.some(function(e){var t;return null==(t=e.events)?void 0:t.includes(Vo)});if(r.reporter&&i.loading.first>0&&s)try{r.reporter.recordResponseReceived({request:{url:e},status:t.code,resourceTiming:{startTime:i.loading.start,responseStart:i.loading.first,duration:i.loading.end-i.loading.start,encodedBodySize:i.total}})}catch(e){r.hls.logger.warn("Could not record fragment response CMCD data.",e)}},this.hls=t;var i=this.config=t.config;null!=i.cmcd&&(i.pLoader=this.createPlaylistLoader(),i.fLoader=this.createFragmentLoader(),this.registerListeners())},[{key:"createReporter",value:function(){var e,t,r=this.config.cmcd;if(null!=r){var i=r.version||1;if(this.reporter=new jl({sid:r.sessionId||this.hls.sessionId,cid:r.contentId,version:i,transmissionMode:!0===r.useHeaders?Nl:Fl,enabledKeys:null!=(e=r.includeKeys)?e:b(i>=2?Sl:rl),eventTargets:(null!=(t=r.eventTargets)?t:[]).map(function(e){var t=e.includeKeys;return Ie(Ie({},Re(e,Xl)),{},{enabledKeys:null!=t?t:Sl})})},r.loader),this.reporter.update({sf:ql,sta:this.playerState}),r.reporterCallback){var n=this.reporter,a={updateCustomData:function(e){Ql(e)&&n.update(e)},recordCustomEvent:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};Ql(t)&&n.recordEvent(Go,Ie({cen:e},t))}};r.reporterCallback(a)}this.reporter.start()}}},{key:"registerListeners",value:function(){var e=this.hls;e.on(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ne.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(ne.MEDIA_DETACHED,this.onMediaDetached,this),e.on(ne.MEDIA_ENDED,this.onMediaEnded,this),e.on(ne.ERROR,this.onError,this),e.on(ne.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(ne.LEVEL_SWITCHED,this.onLevelSwitched,this),e.on(ne.BUFFER_APPENDED,this.onBufferInfoChange,this),e.on(ne.BUFFER_FLUSHED,this.onBufferInfoChange,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ne.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(ne.MEDIA_DETACHED,this.onMediaDetached,this),e.off(ne.MEDIA_ENDED,this.onMediaEnded,this),e.off(ne.ERROR,this.onError,this),e.off(ne.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(ne.LEVEL_SWITCHED,this.onLevelSwitched,this),e.off(ne.BUFFER_APPENDED,this.onBufferInfoChange,this),e.off(ne.BUFFER_FLUSHED,this.onBufferInfoChange,this)}},{key:"destroy",value:function(){this.unregisterListeners(),this.onMediaDetached(),this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.hls=this.config=null,this.onWaiting=this.onPlay=this.onPlaying=this.onPause=null,this.onSeeking=this.onSeeked=this.onRateChange=this.media=null}},{key:"onMediaAttaching",value:function(e,t){var r=this.media=t.media;this.setPlayerState(this.media.autoplay?Pl:Ol),ta(r,"waiting",this.onWaiting),ta(r,"play",this.onPlay),ta(r,"playing",this.onPlaying),ta(r,"pause",this.onPause),ta(r,"seeking",this.onSeeking),ta(r,"seeked",this.onSeeked),ta(r,"ratechange",this.onRateChange)}},{key:"onMediaDetached",value:function(){var e=this.media;e&&(ra(e,"waiting",this.onWaiting),ra(e,"play",this.onPlay),ra(e,"playing",this.onPlaying),ra(e,"pause",this.onPause),ra(e,"seeking",this.onSeeking),ra(e,"seeked",this.onSeeked),ra(e,"ratechange",this.onRateChange),this.media=null)}},{key:"onMediaEnded",value:function(e,t){this.setPlayerState(Ml)}},{key:"onManifestLoading",value:function(e,t){this.initialized=!1,this.starved=!1,this.buffering=!0,this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.createReporter(),this.media||this.setPlayerState(Ol)}},{key:"onError",value:function(e,t){t.fatal&&(this.setPlayerState(xl),this.reporter&&this.reporter.recordEvent(Uo,{ec:[t.details]}))}},{key:"onLevelSwitching",value:function(e,t){var r;if(this.reporter){var i={br:[t.bitrate/1e3]},n=null==(r=t.details)?void 0:r.fragments[0];n&&(i.ot=this.getObjectType(n,t)),this.reporter.recordEvent(Bo,i)}}},{key:"onLevelSwitched",value:function(e,t){var r=this.hls.levels[t.level];r&&(this.playheadLevel=r)}},{key:"setPlayerState",value:function(e){this.playerState=e,this.reporter&&this.reporter.update({sta:e})}},{key:"getStreamType",value:function(){var e=this.hls.latestLevelDetails;if(e)return e.live?e.partList&&e.canBlockReload?zl:Yl:Wl}},{key:"apply",value:function(e){var t,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.reporter){this.reporter.update({mtp:[this.hls.bandwidthEstimate/1e3],pr:null==(t=this.media)?void 0:t.playbackRate,st:this.getStreamType()});var i=r.ot===Rl||r.ot===bl||r.ot===Il;this.starved&&i&&(r.bs=!0,r.su=!0,this.starved=!1),null==r.su&&(r.su=this.buffering);var n=this.reporter.createRequestReport({url:e.url,headers:e.headers},r);e.url=n.url,e.headers=n.headers}}},{key:"getNextFrag",value:function(e){var t,r=null==(t=this.hls.levels[e.level])?void 0:t.details;if(r){var i=e.sn-r.startSN;return r.fragments[i+1]}}},{key:"getNextPart",value:function(e){var t,r=e.index,i=e.fragment,n=null==(t=this.hls.levels[i.level])||null==(t=t.details)?void 0:t.partList;if(n)for(var a=i.sn,s=n.length-1;s>=0;s--){var o=n[s];if(o.index===r&&o.fragment.sn===a)return n[s+1]}}},{key:"getObjectType",value:function(e,t){var r=e.type;if("subtitle"===r)return Ll;if("initSegment"===e.sn)return Rl;if("audio"===r)return Al;if("main"===r){if(e.hasStreams){var i=e.elementaryStreams;if(i.audiovideo)return Il;if(i.video)return bl;if(i.audio)return Al}if(t){var n=t.audioCodec,a=t.videoCodec;if(!this.hls.audioTracks.length){if(n&&a)return Il;if(n)return Al}if(a)return bl}}}},{key:"getTopBandwidth",value:function(){var e=0,t=this.hls,r=t.maxAutoLevel,i=r>-1?r+1:t.levels.length;return t.levels.slice(0,i).forEach(function(t){t.bitrate>e&&(e=t.bitrate)}),e>0?e:NaN}},{key:"getLowestBandwidth",value:function(){var e=1/0,t=this.hls,r=t.maxAutoLevel,i=r>-1?r+1:t.levels.length;return t.levels.slice(0,i).forEach(function(t){t.bitrate<e&&(e=t.bitrate)}),Z(e)?e:NaN}},{key:"getBufferLength",value:function(e){if(!this.media)return NaN;var t="audio"===e.type?this.hls.audioForwardBufferInfo:this.hls.mainForwardBufferInfo;return t?1e3*t.len:NaN}},{key:"getEventBufferLength",value:function(){if(!this.media)return NaN;var e=this.hls.mainForwardBufferInfo,t=this.hls.audioForwardBufferInfo;if(e&&t)return 1e3*Math.min(e.len,t.len);var r=e||t;return r?1e3*r.len:NaN}},{key:"onBufferInfoChange",value:function(e,t){if(this.reporter){var r=this.getEventBufferLength();Z(r)&&this.reporter.update({bl:[r]})}}},{key:"createPlaylistLoader",value:function(){var e=this.config.pLoader,t=this.applyPlaylistData,r=e||this.config.loader;return function(){return l(function e(t){s(this,e),this.loader=void 0,this.loader=new r(t)},[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}},{key:"destroy",value:function(){this.loader.destroy()}},{key:"abort",value:function(){this.loader.abort()}},{key:"load",value:function(e,r,i){t(e),this.loader.load(e,r,i)}}])}()}},{key:"createFragmentLoader",value:function(){var e=this.config.fLoader,t=this.applyFragmentData,r=this.recordFragmentResponse,i=e||this.config.loader;return function(){return l(function e(t){s(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,n){t(e);var a=n.onSuccess;this.loader.load(e,i,Ie(Ie({},n),{},{onSuccess:function(t,i,n,s){a(t,i,n,s),r(e.url,t,i)}}))}}])}()}}])}(),Jl=function(e){function t(e){var r;return s(this,t),(r=a(this,t,["content-steering",e.logger])).hls=void 0,r.loader=null,r.uri=null,r.pathwayId=".",r._pathwayPriority=null,r.timeToLoad=300,r.reloadTimer=-1,r.updated=0,r.started=!1,r.enabled=!0,r.levels=null,r.audioTracks=null,r.subtitleTracks=null,r.penalizedPathways={},r.hls=e,r.registerListeners(),r}return f(t,e),l(t,[{key:"registerListeners",value:function(){var e=this.hls;e.on(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ne.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(ne.MANIFEST_PARSED,this.onManifestParsed,this),e.on(ne.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ne.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(ne.MANIFEST_PARSED,this.onManifestParsed,this),e.off(ne.ERROR,this.onError,this))}},{key:"pathways",value:function(){return(this.levels||[]).reduce(function(e,t){return-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e},[])}},{key:"pathwayPriority",get:function(){return this._pathwayPriority},set:function(e){this.updatePathwayPriority(e)}},{key:"startLoad",value:function(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){var e=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}}},{key:"stopLoad",value:function(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}},{key:"clearTimeout",value:function(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}},{key:"destroy",value:function(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}},{key:"removeLevel",value:function(e){var t=this.levels;t&&(this.levels=t.filter(function(t){return t!==e}))}},{key:"onManifestLoading",value:function(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}},{key:"onManifestLoaded",value:function(e,t){var r=t.contentSteering;null!==r&&(this.pathwayId=r.pathwayId,this.uri=r.uri,this.started&&this.startLoad())}},{key:"onManifestParsed",value:function(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}},{key:"onError",value:function(e,t){var r=t.errorAction;if((null==r?void 0:r.action)===ri&&r.flags&si){var i=this.levels,n=this._pathwayPriority,a=this.pathwayId;if(t.context){var s=t.context,o=s.groupId,l=s.pathwayId,u=s.type;o&&i?a=this.getPathwayForGroupId(o,u,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!n&&i&&(n=this.pathways()),n&&n.length>1&&(this.updatePathwayPriority(n),r.resolved=this.pathwayId!==a,r.resolved||t.details===ie.BUFFER_APPEND_ERROR&&!t.fatal||this.warn("Could not resolve ".concat(t.details,' ("').concat(t.error.message,'") with content-steering for Pathway: ').concat(a," levels: ").concat(i?i.length:i," priorities: ").concat(Nr(n)," penalized: ").concat(Nr(this.penalizedPathways))))}}},{key:"filterParsedLevels",value:function(e){this.levels=e;var t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){var r=e[0].pathwayId;this.log("No levels found in Pathway ".concat(this.pathwayId,'. Setting initial Pathway to "').concat(r,'"')),t=this.getLevelsForPathway(r),this.pathwayId=r}return t.length!==e.length&&this.log("Found ".concat(t.length,"/").concat(e.length,' levels in Pathway "').concat(this.pathwayId,'"')),t}},{key:"getLevelsForPathway",value:function(e){return null===this.levels?[]:this.levels.filter(function(t){return e===t.pathwayId})}},{key:"updatePathwayPriority",value:function(e){var t;this._pathwayPriority=e;var r=this.penalizedPathways,i=performance.now();Object.keys(r).forEach(function(e){i-r[e]>3e5&&delete r[e]});for(var n=0;n<e.length;n++){var a=e[n];if(!(a in r)){if(a===this.pathwayId)return;var s=this.hls.nextLoadLevel,o=this.hls.levels[s];if((t=this.getLevelsForPathway(a)).length>0){this.log('Setting Pathway to "'.concat(a,'"')),this.pathwayId=a,zn(t),this.hls.trigger(ne.LEVELS_UPDATED,{levels:t});var l=this.hls.levels[s];o&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==o.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==o.bitrate&&this.log("Unstable Pathways change from bitrate ".concat(o.bitrate," to ").concat(l.bitrate)),this.hls.nextLoadLevel=s);break}}}}},{key:"getPathwayForGroupId",value:function(e,t,r){for(var i=this.getLevelsForPathway(r).concat(this.levels||[]),n=0;n<i.length;n++)if(t===ce.AUDIO_TRACK&&i[n].hasAudioGroup(e)||t===ce.SUBTITLE_TRACK&&i[n].hasSubtitleGroup(e))return i[n].pathwayId;return r}},{key:"clonePathways",value:function(e){var t=this,r=this.levels;if(r){var i={},n={};e.forEach(function(e){var a=e.ID,s=e["BASE-ID"],o=e["URI-REPLACEMENT"];if(!r.some(function(e){return e.pathwayId===a})){var l=t.getLevelsForPathway(s).map(function(e){var t=new Wi(e.attrs);t["PATHWAY-ID"]=a;var r=t.AUDIO&&"".concat(t.AUDIO,"_clone_").concat(a),s=t.SUBTITLES&&"".concat(t.SUBTITLES,"_clone_").concat(a);r&&(i[t.AUDIO]=r,t.AUDIO=r),s&&(n[t.SUBTITLES]=s,t.SUBTITLES=s);var l=eu(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",o),u=new xr({attrs:t,audioCodec:e.audioCodec,bitrate:e.bitrate,height:e.height,name:e.name,url:l,videoCodec:e.videoCodec,width:e.width});if(e.audioGroups)for(var c=1;c<e.audioGroups.length;c++)u.addGroupId("audio","".concat(e.audioGroups[c],"_clone_").concat(a));if(e.subtitleGroups)for(var d=1;d<e.subtitleGroups.length;d++)u.addGroupId("text","".concat(e.subtitleGroups[d],"_clone_").concat(a));return u});r.push.apply(r,b(l)),Zl(t.audioTracks,i,o,a),Zl(t.subtitleTracks,n,o,a)}})}}},{key:"loadSteeringManifest",value:function(e){var t,r=this,i=this.hls.config,n=i.loader;this.loader&&this.loader.destroy(),this.loader=new n(i);try{t=new self.URL(e)}catch(t){return this.enabled=!1,void this.log("Failed to parse Steering Manifest URI: ".concat(e))}if("data:"!==t.protocol){var a=0|(this.hls.bandwidthEstimate||i.abrEwmaDefaultEstimate);Rr(t,"_HLS_pathway",this.pathwayId),Rr(t,"_HLS_throughput",""+a)}var s={type:ce.STEERING_MANIFEST,responseType:"json",url:t.href},o=i.steeringManifestLoadPolicy.default,l=o.errorRetry||o.timeoutRetry||{},u={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:l.maxNumRetry||0,retryDelay:l.retryDelayMs||0,maxRetryDelay:l.maxRetryDelayMs||0},c={onSuccess:function(e,i,n,a){r.log('Loaded steering manifest: "'.concat(t,'"'));var s=e.data;if(1===(null==s?void 0:s.VERSION)){r.updated=performance.now(),r.timeToLoad=s.TTL;var o=s["RELOAD-URI"],l=s["PATHWAY-CLONES"],u=s["PATHWAY-PRIORITY"];if(o)try{r.uri=new self.URL(o,t).href}catch(e){return r.enabled=!1,void r.log("Failed to parse Steering Manifest RELOAD-URI: ".concat(o))}r.scheduleRefresh(r.uri||n.url),l&&r.clonePathways(l);var c={steeringManifest:s,url:t.toString()};r.hls.trigger(ne.STEERING_MANIFEST_LOADED,c),u&&r.updatePathwayPriority(u)}else r.log("Steering VERSION ".concat(s.VERSION," not supported!"))},onError:function(e,t,i,n){if(r.log("Error loading steering manifest: ".concat(e.code," ").concat(e.text," (").concat(t.url,")")),r.stopLoad(),410===e.code)return r.enabled=!1,void r.log("Steering manifest ".concat(t.url," no longer available"));var a=1e3*r.timeToLoad;if(429!==e.code)r.scheduleRefresh(r.uri||t.url,a);else{var s=r.loader;if("function"==typeof(null==s?void 0:s.getResponseHeader)){var o=s.getResponseHeader("Retry-After");o&&(a=1e3*parseFloat(o))}r.log("Steering manifest ".concat(t.url," rate limited"))}},onTimeout:function(e,t,i){r.log("Timeout loading steering manifest (".concat(t.url,")")),r.scheduleRefresh(r.uri||t.url)}};this.log("Requesting steering manifest: ".concat(t)),this.loader.load(s,u,c)}},{key:"scheduleRefresh",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1e3*this.timeToLoad;this.clearTimeout(),this.reloadTimer=self.setTimeout(function(){var r,i=null==(r=t.hls)?void 0:r.media;!i||i.ended?t.scheduleRefresh(e,1e3*t.timeToLoad):t.loadSteeringManifest(e)},r)}}])}(Be);function Zl(e,t,r,i){e&&Object.keys(t).forEach(function(n){var a=e.filter(function(e){return e.groupId===n}).map(function(e){var a=Ae({},e);return a.details=void 0,a.attrs=new Wi(a.attrs),a.url=a.attrs.URI=eu(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",r),a.groupId=a.attrs["GROUP-ID"]=t[n],a.attrs["PATHWAY-ID"]=i,a});e.push.apply(e,b(a))})}function eu(e,t,r,i){if(t){var n=i[r];if(n){var a=n[t];if(a)return a}}var s=i.HOST,o=i.PARAMS,l=new self.URL(e);return s&&(l.hostname=s),o&&Object.keys(o).sort().forEach(function(e){e&&Rr(l,e,o[e])}),l.href}var tu=function(){return l(function e(){s(this,e),this.status="initialized",this.requestErrors=[],this.licenseXhr=void 0,this.onmessage=void 0,this.onkeystatuseschange=void 0,this.emitter=new Aa,this.error=void 0,this.ok=void 0},[{key:"errored",get:function(){return this.error},set:function(e){this.error=e,this.emitter.eventNames().length&&this.emitter.emit("error",e)}},{key:"hasListeners",get:function(){return this.emitter.eventNames().length>0}},{key:"resolved",get:function(){return this.ok}},{key:"resolve",value:function(){this.ok=!0,this.emitter.emit("resolved")}},{key:"useable",get:function(){var e=this;return this.ok?Promise.resolve():this.error?Promise.reject(this.error):new Promise(function(t,r){e.emitter.on("error",r),e.emitter.on("resolved",t)})}},{key:"reset",value:function(){this.emitter.removeAllListeners();var e=this.licenseXhr;e&&(e.readyState!==XMLHttpRequest.DONE&&e.abort(),this.licenseXhr=void 0),this.onmessage=this.onkeystatuseschange=void 0}}])}(),ru=function(e){function t(e,r){var i;return s(this,t),(i=a(this,t,[r])).data=void 0,e.error||(e.error=new Error(r)),i.data=e,e.err=e.error,i}return f(t,e),l(t)}(w(Error)),iu=function(e){function t(e){var r;return s(this,t),(r=a(this,t,["eme",e.logger])).hls=void 0,r.config=void 0,r.media=null,r.mediaResolved=void 0,r.keyFormatPromise=null,r.keySystemAccessPromises={},r.sessionSetupByUri={},r.mediaKeySessions=[],r.activeKeys={},r.mediaKeys=null,r.setMediaKeysQueue=t.CDMCleanupPromise?[t.CDMCleanupPromise]:[],r.onMediaEncrypted=function(e){var t=e.initDataType,i=e.initData,n='"'.concat(e.type,'" event: init data type: "').concat(t,'"');if(r.log(n),null!==i){if(!r.keyFormatPromise){var a=Object.keys(r.keySystemAccessPromises);a.length||(a=vn(r.config));var s=a.map(fn).filter(function(e){return!!e});r.keyFormatPromise=r.getKeyFormatPromise(s)}r.keyFormatPromise.then(function(a){var s,o,l=dn(a),u=r.activeLevelKeys();if(l===sn.FAIRPLAY&&"sinf"===t)try{var c=pt(new Uint8Array(i)),d=Vt(gt(JSON.parse(c).sinf));if(!d)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");s=new Uint8Array(d.subarray(8,24))}catch(e){return void r.warn("".concat(n," Failed to parse sinf: ").concat(e))}else if(l===sn.PLAYREADY)s=mn(new Uint8Array(i));else if(l===sn.WIDEVINE){var h=Xt(i).filter(function(e){return e.systemId===hn});if(h.length){var f,v=h[0];s=null!=(f=v.kids)&&f.length?v.kids[0]:null}}if(s)for(var g=ft(s),p=0;p<u.length;p++){var m=u[p];if(m.keyId&&($i(s,m.keyId)||-1!==m.uri.replace(/-/g,"").indexOf(g))){m.pssh||(m.scheme=t,m.pssh=new Uint8Array(i),m.keyId=s,kn.setKeyIdForUri(m.uri,s)),o=r.getSessionForKey(m,"encrypted-event-key-match");break}}if(!o){var y,k;if(u.length)return(y=u[0]).scheme||(y.scheme=t),(k=u[0]).pssh||(k.pssh=new Uint8Array(i)),r.getSessionForKey(u[0],"encrypted-event-no-match");if(s)throw new Error("Key ID ".concat(ft(s)," not encountered in playlist"));r.log('Ignoring "'.concat(e.type,'" event - could not determine keyId'))}return o}).catch(function(e){return r.handleError(e)})}},r.onWaitingForKey=function(e){r.log('"'.concat(e.type,'" event'))},r.hls=e,r.config=e.config,r.registerListeners(),r}return f(t,e),l(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=null,this.onMediaEncrypted=this.onWaitingForKey=null}},{key:"registerListeners",value:function(){var e=this.hls;e&&(e.on(ne.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ne.MEDIA_DETACHED,this.onMediaDetached,this),e.on(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ne.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(ne.DESTROYING,this.onDestroying,this))}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ne.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ne.MEDIA_DETACHED,this.onMediaDetached,this),e.off(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ne.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(ne.DESTROYING,this.onDestroying,this))}},{key:"attemptKeySystemAccess",value:function(e){var t=this;if(!this.hls)return Promise.reject(new Error("destroyed"));var r=this.hls.levels,i=function(e,t,r){return!!e&&r.indexOf(e)===t},n=r.map(function(e){return e.audioCodec}).filter(i),a=r.map(function(e){return e.videoCodec}).filter(i);return n.length+a.length===0&&a.push("avc1.42e01e"),new Promise(function(r,i){var s=function(e){var o=e.shift();t.getMediaKeysPromise(o,n,a).then(function(e){return r({keySystem:o,mediaKeys:e})}).catch(function(t){e.length?s(e):i(t instanceof ru?t:new ru({type:re.KEY_SYSTEM_ERROR,details:ie.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))})};s(e)})}},{key:"requestMediaKeySystemAccess",value:function(e,t){var r=this.config.requestMediaKeySystemAccessFunc;if("function"!=typeof r){var i="Configured requestMediaKeySystemAccess is not a function ".concat(r);return null===pn&&"http:"===self.location.protocol&&(i="navigator.requestMediaKeySystemAccess is not available over insecure protocol ".concat(location.protocol)),Promise.reject(new Error(i))}return r(e,t)}},{key:"getMediaKeysPromise",value:function(e,t,r){var i,n=this,a=function(e,t,r,i){var n;switch(e){case sn.FAIRPLAY:n=["cenc","sinf"];break;case sn.WIDEVINE:case sn.PLAYREADY:n=["cenc"];break;case sn.CLEARKEY:n=["cenc","keyids"];break;default:throw new Error("Unknown key-system: ".concat(e))}return function(e,t,r,i){return[{initDataTypes:e,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:t.map(function(e){return{contentType:"audio/mp4; codecs=".concat(e),robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null}}),videoCapabilities:r.map(function(e){return{contentType:"video/mp4; codecs=".concat(e),robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}})}]}(n,t,r,i)}(e,t,r,this.config.drmSystemOptions||{}),s=this.keySystemAccessPromises[e],o=null==(i=s)?void 0:i.keySystemAccess;if(!o){this.log('Requesting encrypted media "'.concat(e,'" key-system access with config: ').concat(Nr(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.throwIfDestroyed(),n.log('Access for key-system "'.concat(t.keySystem,'" obtained'));var r=n.fetchServerCertificate(e);n.log('Create media-keys for "'.concat(e,'"'));var i=l.mediaKeys=t.createMediaKeys().then(function(t){return n.log('Media-keys created for "'.concat(e,'"')),l.hasMediaKeys=!0,r.then(function(r){return r?n.setMediaKeysServerCertificate(t,e,r):t})});return i.catch(function(t){n.error('Failed to create media-keys for "'.concat(e,'"}: ').concat(t))}),i})}return o.then(function(){return s.mediaKeys})}},{key:"getMediaKeySessionContext",value:function(e,t,r,i){for(var n=this.mediaKeySessions,a=' key-session "'.concat(e,'" keyId: ').concat(ft(r.keyId||[])," keyUri: ").concat(r.uri,' for "').concat(i,'"'),s=0;s<n.length;s++){var o=n[s];if(!o.initialized&&o.createdFor.levelKey.uri===r.uri)return this.log("Reusing".concat(a)),o}this.log("Creating".concat(a));var l=t.createSession(),u={keySystem:e,mediaKeys:t,mediaKeysSession:l,keyRequests:{},keyStatuses:{},createdFor:{levelKey:r,reason:i},initialized:!1};return n.push(u),u}},{key:"resetMediaKeys",value:function(){var e,t=null==(e=this.mediaKeySessions[0])?void 0:e.keySystem,r=this.keySystemAccessPromises[t];r&&(this.log("reset mediaKeys"),this.mediaKeys=null,r.hasMediaKeys=!1,delete r.mediaKeys,delete this.keySystemAccessPromises[t])}},{key:"updateKeySession",value:function(e,t,r){var i=e.mediaKeysSession;return this.log('Updating key-session "'.concat(i.sessionId,'" for keyId ').concat(ft(t.keyId||[]),"\n } (data length: ").concat(r.byteLength,")")),i.update(r)}},{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 fn(e.keySystem)}).filter(function(e){return!!e})}},{key:"getKeySystemAccess",value:function(e){var t=this;return this.getKeySystemSelectionPromise(e).then(function(e){var r=e.keySystem,i=e.mediaKeys;return t.attemptSetMediaKeys(r,i)})}},{key:"selectKeySystem",value:function(e){return this.getKeySystemSelectionPromise(e).then(function(e){var t=e.keySystem,r=fn(t);if(!r)throw new Error('Unable to find format for key-system "'.concat(t,'"'));return 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=vn(this.config),r=e.map(dn).filter(function(e){return!!e&&-1!==t.indexOf(e)});return this.selectKeySystem(r)}},{key:"loadClear",value:function(e,t,r){var i=this;if(this.config.emeEnabled&&!this.getSelectedKeySystemFormats().length){if(t.length)for(var n,a=function(){var n=t[s];if(e.cc<=n.cc&&(!pe(e)||!pe(n)||e.sn<n.sn)||!r&&s==o-1)return{v:i.selectKeySystemFormat(n).then(function(e){if(i.hls){n.setKeyFormat(e);var t=dn(e);return t?i.getKeySystemAccess([t]):void 0}})}},s=0,o=t.length;s<o;s++)if(n=a())return n.v;if(this.config.requireKeySystemAccessOnStart){var l=vn(this.config);if(l.length)return this.getKeySystemAccess(l)}}return null}},{key:"getKeyStatus",value:function(e){for(var t=this.mediaKeySessions,r=0;r<t.length;r++){var i=nu(e,t[r]);if(i)return i}}},{key:"loadKey",value:function(e){var t=e.decryptdata,r=this.getKeyStatus(t);if("internal-error"===r){var i=au(r,t);return i.data.frag=e,this.error("".concat(i.message," (").concat(ft(t.keyId||[]),")")),Promise.reject(i)}var n=e.type,a=this.activeKeys,s=a[n];s&&!t.matches(s.decryptdata)&&(a.previous||(a.previous=[]),a.previous.push(s),delete a[n]),a[n]||(a[n]=e);for(var o=this.mediaKeySessions.length;o--;){var l=this.mediaKeySessions[o];if(t.keyId&&"expired"===l.keyStatuses[ft(t.keyId)])return this.renewKeySession(t,l)}return this.updateUsablePromise(t,"playlist-key",e)}},{key:"renewKeySession",value:function(e,t){var r=this;return this.resetMediaKeys(),this.removeSession(t).then(function(){return r.throwIfDestroyed(),r.updateUsablePromise(e,"expired")})}},{key:"updateUsablePromise",value:function(e,t,r){var i=this,n=this.getSessionForKey(e,t);return n.catch(function(e){return i.handleError(e,r)}),n.then(function(t){return e})}},{key:"getSessionForKey",value:function(e,t){var r=this,i=this.findContextForKey(e);if(void 0!==i)return Promise.resolve(i);var n,a=e.uri,s=this.sessionSetupByUri[a];n=void 0===s?this.resolveSessionForKey(e,t):s.catch(function(){}).then(function(){return r.throwIfDestroyed(),r.resolveSessionForKey(e,t)}),this.sessionSetupByUri[a]=n;var o=function(){r.sessionSetupByUri[a]===n&&delete r.sessionSetupByUri[a]};return n.then(o,o),n}},{key:"findContextForKey",value:function(e){for(var t=this.mediaKeySessions,r=t.length;r--;){var i=t[r];if(nu(e,i))return i}}},{key:"resolveSessionForKey",value:function(e,t){var r=this;return this.getKeySystemForKeyPromise(e).then(function(i){var n=i.keySystem,a=i.mediaKeys;r.throwIfDestroyed();for(var s=r.mediaKeySessions.length;s--;){var o=r.mediaKeySessions[s];if(nu(e,o))return o;var l=r.getUsableKeyPromise(o,e,t);if(l)return l}return r.attemptSetMediaKeys(n,a).then(function(){return r.throwIfDestroyed(),r.getMediaKeySessionContext(n,a,e,t)}).then(function(i){r.throwIfDestroyed();var n=e.scheme||"cenc",a=e.pssh?e.pssh.buffer:null;return r.generateRequestWithPreferredKeySession(i,e,n,a,t)})})}},{key:"getUsableKeyPromise",value:function(e,t,r){var i=e.keyRequests[t.uri];if(i)return this.log("Waiting for usable key (".concat(r," keyId: ").concat(function(e){if(e.keyFormat===ln)return e.uri;if(null===e.keyId)throw new Error("keyId is null");return ft(e.keyId)}(t),' format: "').concat(t.keyFormat,'" URI: ').concat(t.uri,")")),i.useable.then(function(){return e})}},{key:"throwIfDestroyed",value:function(){if(!this.hls)throw new Error("invalid state")}},{key:"handleError",value:function(e,t){if(this.hls)if(e instanceof ru){t&&(e.data.frag=t);var r=e.data.decryptdata;this.error("".concat(e.message).concat(r?" (".concat(ft(r.keyId||[]),")"):"")),this.hls.trigger(ne.ERROR,e.data)}else this.error(e.message),this.hls.trigger(ne.ERROR,{type:re.KEY_SYSTEM_ERROR,details:ie.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}},{key:"getKeySystemForKeyPromise",value:function(e){var t=dn(e.keyFormat),r=t?[t]:vn(this.config);return this.attemptKeySystemAccess(r)}},{key:"getKeySystemSelectionPromise",value:function(e){if(e.length||(e=vn(this.config)),0===e.length)throw new ru({type:re.KEY_SYSTEM_ERROR,details:ie.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},"Missing key-system license configuration options ".concat(Nr({drmSystems:this.config.drmSystems})));return this.attemptKeySystemAccess(e)}},{key:"activeLevelKeys",value:function(){var e=this.activeKeys,t=(e.previous||[]).map(function(e){return e.decryptdata});return e.audio&&t.unshift(e.audio.decryptdata),e.main&&t.unshift(e.main.decryptdata),t}},{key:"attemptSetMediaKeys",value:function(e,t){var r=this;if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();var i=this.setMediaKeysQueue.slice();this.log('Setting media-keys for "'.concat(e,'"'));var n=Promise.all(i).then(function(){return r.media?r.media.setMediaKeys(t):new Promise(function(e,i){r.mediaResolved=function(){if(r.mediaResolved=void 0,!r.media)return i(new Error("Attempted to set mediaKeys without media element attached"));r.mediaKeys=t,r.media.setMediaKeys(t).then(e).catch(i)}})});return this.mediaKeys=t,this.setMediaKeysQueue.push(n),n.then(function(){r.log('Media-keys set for "'.concat(e,'"')),i.push(n),r.setMediaKeysQueue=r.setMediaKeysQueue.filter(function(e){return-1===i.indexOf(e)})})}},{key:"filterInitData",value:function(e,t,r,i,n){var a,s=null==(a=this.config.drmSystems)||null==(a=a[e.keySystem])?void 0:a.generateRequest;if(s)try{var o=s.call(this.hls,r,i,Ae({},e,{decryptdata:t,reason:n}),n);if(!o)throw new Error("Invalid response from configured generateRequest filter");t.scheme=o.initDataType?o.initDataType:"cenc";var l=o.initData?o.initData:null;return t.pssh=l?new Uint8Array(l):null,o}catch(e){var u;if(this.warn(e.message),null!=(u=this.hls)&&u.config.debug)throw e}return{initDataType:r,initData:i}}},{key:"generateRequestWithPreferredKeySession",value:function(e,t,r,i,n){var a=this,s=this.getUsableKeyPromise(e,t,n);if(s)return s;var o=this.filterInitData(e,t,r,i,n);if(o&&(i=o.initData?o.initData:null,r=o.initDataType),null===i)return n.startsWith("encrypted-event")?Promise.reject(new Error('missing initialization data for "'.concat(n,'"'))):(this.log('Skipping key-session request for "'.concat(n,'" (no initData)')),Promise.resolve(e));var l=t.uri,u=new tu;e.keyRequests[l]=u;var c=function(r){var i=e.mediaKeysSession;if(i){var n=r.messageType,s=r.message;u.status=n,a.log('"'.concat(n,'" message event for session "').concat(i.sessionId,'" message size: ').concat(s.byteLength)),"license-request"===n||"license-renewal"===n?a.renewLicense(e,t,s).catch(function(t){u.errored=t,u.hasListeners||a.handleError(t),a.removeSession(e)}):"license-release"===n?e.keySystem===sn.FAIRPLAY&&a.updateKeySession(e,t,tn("acknowledged")).then(function(){return a.removeSession(e)}).catch(function(e){return a.handleError(e)}):a.warn('unhandled media key message type "'.concat(n,'"'))}else{var o=new Error("invalid state");u.errored=o}};u.onmessage=c,ta(e.mediaKeysSession,"message",c);return this.generateRequest(e,t,r,i,n,!1)}},{key:"generateRequest",value:function(e,t,r,i,n,a){var s=this;if(a){var o=this.filterInitData(e,t,r,i,n);o&&(i=o.initData?o.initData:i,r=o.initDataType)}var l=t.uri,u=e.keyRequests[l],c=ft(t.keyId||[]),d=function(e){var r;e.startsWith("usable")?u.resolve():"internal-error"===e||"output-restricted"===e||"output-downscaled"===e?r=au(e,t):"expired"===e?r=new Error("key expired (keyId: ".concat(c,")")):"released"===e?r=new Error("key released"):"status-pending"===e||s.warn('unhandled key status change "'.concat(e,'" (keyId: ').concat(c,")")),r&&(u.errored=r,u.hasListeners||s.handleError(r))},h=function(r){if(e.mediaKeysSession){var i=e.keyStatuses=s.getKeyStatuses(e);if(Object.keys(i).some(function(e){return"status-pending"!==i[e]})){for(var n=s.activeLevelKeys(),a=0;a<n.length;a++){var o=ft(n[a].keyId||[]);if("expired"===i[o]){var l;s.log("Expired key ".concat(Nr(i),' in key-session "').concat(null==(l=e.mediaKeysSession)?void 0:l.sessionId,'"')),s.renewKeySession(t,e).catch(function(e){return s.handleError(e)});break}}var h=i[c];if(h)d(h);else{var f;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(f=e.keyStatusTimeouts)[c]||(f[c]=self.setTimeout(function(){var r;if(e.mediaKeysSession){var i,n=s.getKeyStatus(t);if(n&&"status-pending"!==n)return s.log("No status for keyId ".concat(c,' in key-session "').concat(null==(i=e.mediaKeysSession)?void 0:i.sessionId,'". Using session key-status ').concat(n," from other session.")),d(n);s.log("key status for ".concat(c,' in key-session "').concat(null==(r=e.mediaKeysSession)?void 0:r.sessionId,'" timed out after ').concat(1e3,"ms")),d(h="internal-error")}},1e3)),s.log("No status for keyId ".concat(c," (").concat(Nr(i),")."))}}}else{var v=new Error("invalid state");u.errored=v}};u.onkeystatuseschange=h,ta(e.mediaKeysSession,"keystatuseschange",h);var f=u.useable;return this.log('Generating key-session request for "'.concat(n,'" keyId: ').concat(c," URI: ").concat(l," (init data type: ").concat(r," length: ").concat(i.byteLength,")")),u.status="started",e.initialized=!0,e.mediaKeysSession.generateRequest(r,i).then(function(){var t;u.status="generated",s.log('Request generated for key-session "'.concat(null==(t=e.mediaKeysSession)?void 0:t.sessionId,'" keyId: ').concat(c," URI: ").concat(l))}).catch(function(e){throw s.log("mediaKeysSession.generateRequest failed: ".concat(e)),new ru({type:re.KEY_SYSTEM_ERROR,details:ie.KEY_SYSTEM_NO_SESSION,error:e,decryptdata:t,fatal:!1},"Error generating key-session request: ".concat(e))}).then(function(){return f}).catch(function(t){var r;s.log("mediaKeysSession.generateRequest failed: ".concat(t));var i=null==(r=t.data)?void 0:r.details;return i!==ie.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED&&i!==ie.KEY_SYSTEM_STATUS_INTERNAL_ERROR||!Object.keys(e.keyStatuses).some(function(t){return"usable"===e.keyStatuses[t]})?s.removeSession(e).then(function(){throw t}):(s.handleError(t),e)}).then(function(){return e})}},{key:"getKeyStatuses",value:function(e){var t=this,r={},i=e.mediaKeysSession.sessionId;return e.mediaKeysSession.keyStatuses.forEach(function(n,a){if("string"==typeof a&&"object"===R(n)){var s=a;a=n,n=s}var o="buffer"in a?new Uint8Array(a.buffer,a.byteOffset,a.byteLength):new Uint8Array(a);if(e.keySystem===sn.PLAYREADY&&16===o.length){var l=ft(o);r[l]=n,rn(o)}var u=ft(o);t.log('key status change "'.concat(n,'" for keyStatuses keyId: ').concat(u,' key-session "').concat(i,'"')),r[u]=n}),r}},{key:"fetchServerCertificate",value:function(e){var t=this.config,r=new(0,t.loader)(t),i=function(e,t){var r=t.drmSystems,i=null==r?void 0:r[e];if(i)return i.serverCertificateUrl}(e,t);return i?(this.log('Fetching server certificate for "'.concat(e,'"')),new Promise(function(n,a){var s={type:ce.SERVER_CERTIFICATE,responseType:"arraybuffer",url:i},o=t.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:function(e,t,r,i){n(e.data)},onError:function(t,r,n,o){a(new ru({type:re.KEY_SYSTEM_ERROR,details:ie.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:n,response:Ie({url:s.url,data:void 0},t)},'"'.concat(e,'" certificate request failed (').concat(i,"). Status: ").concat(t.code," (").concat(t.text,")")))},onTimeout:function(t,r,n){a(new ru({type:re.KEY_SYSTEM_ERROR,details:ie.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:n,response:{url:s.url,data:void 0}},'"'.concat(e,'" certificate request timed out (').concat(i,")")))},onAbort:function(e,t,r){a(new Error("aborted"))}};r.load(s,l,u)})):(this.log('No Server Certificate in config.drmSystems["'.concat(e,'"]')),Promise.resolve())}},{key:"setMediaKeysServerCertificate",value:function(e,t,r){var i=this;return new Promise(function(n,a){e.setServerCertificate(r).then(function(a){i.log("setServerCertificate ".concat(a?"success":"not supported by CDM"," (").concat(r.byteLength,') on "').concat(t,'"')),n(e)}).catch(function(e){a(new ru({type:re.KEY_SYSTEM_ERROR,details:ie.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))})})}},{key:"renewLicense",value:function(e,t,r){var i=this;return this.requestLicense(e,t,new Uint8Array(r)).then(function(r){return i.updateKeySession(e,t,new Uint8Array(r)).catch(function(e){throw new ru({type:re.KEY_SYSTEM_ERROR,details:ie.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t,error:e,fatal:!1},e.message)})})}},{key:"unpackPlayReadyKeyMessage",value:function(e,t){var r=pt(new Uint16Array(t.buffer));if(!r.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;var i=(new DOMParser).parseFromString(r,"application/xml"),n=i.querySelectorAll("HttpHeader");if(n.length>0)for(var a,s=0,o=n.length;s<o;s++){var l,u,c=null==(l=(a=n[s]).querySelector("name"))?void 0:l.textContent,d=null==(u=a.querySelector("value"))?void 0:u.textContent;c&&d&&e.setRequestHeader(c,d)}var h=i.querySelector("Challenge"),f=null==h?void 0:h.textContent;if(!f)throw new Error("Cannot find <Challenge> in key message");return tn(atob(f))}},{key:"setupLicenseXHR",value:function(e,t,r,i,n){var a=this,s=this.config.licenseXhrSetup;return s?Promise.resolve().then(function(){return a.throwIfDestroyed(),s.call(a.hls,e,t,Ie(Ie({},r),{},{decryptdata:i}),n)}).catch(function(o){if(!r.mediaKeysSession)throw o;return e.open("POST",t,!0),s.call(a.hls,e,t,Ie(Ie({},r),{},{decryptdata:i}),n)}).then(function(r){return e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:r||n}}):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:n}))}},{key:"requestLicense",value:function(e,t,r){var i=this;return new Promise(function(n,a){var s=function(e,t){var r=t.drmSystems,i=t.widevineLicenseUrl,n=null==r?void 0:r[e];if(n)return n.licenseUrl;if(e===sn.WIDEVINE&&i)return i}(e.keySystem,i.config);if(!s)return a(new Error('no license server URL configured for key-system "'.concat(e.keySystem,'"')));var o=e.keyRequests[t.uri];if(!o)return a(new Error("License emitter removed"));i.log("Sending license request to URL: ".concat(s));var l=i.config.keyLoadPolicy.default,u=new XMLHttpRequest;u.responseType="arraybuffer",u.onreadystatechange=function(){if(!i.hls||!e.mediaKeysSession)return a(new Error("invalid state"));if(4===u.readyState)if(200===u.status){o.requestErrors=[];var c=u.response;i.log("License received ".concat(c instanceof ArrayBuffer?c.byteLength:c));var d=i.config.licenseResponseCallback;if(d)try{c=d.call(i.hls,u,s,Ie(Ie({},e),{},{decryptdata:t}))}catch(e){i.error(e)}n(c)}else{var h=l.errorRetry,f=h?h.maxNumRetry:0;if(o.requestErrors.push({status:u.status,message:u.statusText}),o.requestErrors.length>f||u.status>=400&&u.status<500)a(new ru({type:re.KEY_SYSTEM_ERROR,details:ie.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:t,fatal:!0,networkDetails:u,response:{url:s,data:void 0,code:u.status,text:u.statusText}},"License Request XHR failed (".concat(s,"). Status: ").concat(u.status," (").concat(u.statusText,")")));else{var v=f-o.requestErrors.length;i.warn("Retrying license request, ".concat(v," attempts left")),i.requestLicense(e,t,r).then(n,a)}}},o.licenseXhr&&o.licenseXhr.readyState!==XMLHttpRequest.DONE&&o.licenseXhr.abort(),o.licenseXhr=u,i.setupLicenseXHR(u,s,e,t,r).then(function(t){var r=t.xhr,n=t.licenseChallenge;e.keySystem==sn.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 r=t.media;this.media=r,ta(r,"encrypted",this.onMediaEncrypted),ta(r,"waitingforkey",this.onWaitingForKey);var i=this.mediaResolved;i?i():this.mediaKeys=r.mediaKeys}}},{key:"onMediaDetached",value:function(){var e=this.media;e&&(ra(e,"encrypted",this.onMediaEncrypted),ra(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}},{key:"_clear",value:function(){var e,r=this;this.keyFormatPromise=null,this.keySystemAccessPromises={},this.activeKeys={},this.sessionSetupByUri={};var i=this.mediaResolved;if(i&&i(),this.mediaKeys||this.mediaKeySessions.length){var n=this.media,a=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,kn.clearKeyUriToKeyIdMap();var s=a.length;t.CDMCleanupPromise=Promise.all(a.map(function(e){return r.removeSession(e)}).concat((null==n||null==(e=n.setMediaKeys(null))?void 0:e.catch(function(e){r.log("Could not clear media keys: ".concat(e)),r.hls&&r.hls.trigger(ne.ERROR,{type:re.OTHER_ERROR,details:ie.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error("Could not clear media keys: ".concat(e))})}))||Promise.resolve())).catch(function(e){r.log("Could not close sessions and clear media keys: ".concat(e)),r.hls&&r.hls.trigger(ne.ERROR,{type:re.OTHER_ERROR,details:ie.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error("Could not close sessions and clear media keys: ".concat(e))})}).then(function(){s&&r.log("finished closing key sessions and clearing media keys")})}}},{key:"onManifestLoading",value:function(){this._clear(),this.keyFormatPromise=null}},{key:"onManifestLoaded",value:function(e,t){var r=t.sessionKeys;if(r&&this.config.emeEnabled&&!this.keyFormatPromise){var i=r.reduce(function(e,t){return-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e},[]);this.log("Selecting key-system from session-keys ".concat(i.join(", "))),this.keyFormatPromise=this.getKeyFormatPromise(i),this.keyFormatPromise.catch(function(){})}}},{key:"removeSession",value:function(e){var t=this,r=e.mediaKeysSession;if(r){this.log('Remove licenses and keys and close session "'.concat(r.sessionId,'"')),Object.keys(e.keyRequests).forEach(function(t){var i=e.keyRequests[t];i.onmessage&&r.removeEventListener("message",i.onmessage),i.onkeystatuseschange&&r.removeEventListener("keystatuseschange",i.onkeystatuseschange),i.reset(),e.keyRequests[t]=void 0}),e.mediaKeysSession=void 0;var i=this.mediaKeySessions.indexOf(e);i>-1&&this.mediaKeySessions.splice(i,1);var n=e.keyStatusTimeouts;n&&Object.keys(n).forEach(function(e){return self.clearTimeout(n[e])});var a=function(e){var t;return!(!e||"persistent-license"!==e.sessionType&&(null==(t=e.sessionTypes)||!t.some(function(e){return"persistent-license"===e})))}(this.config.drmSystemOptions)?new Promise(function(e,t){self.setTimeout(function(){return t(new Error("MediaKeySession.remove() timeout"))},8e3),r.remove().then(e).catch(t)}):Promise.resolve();return a.catch(function(e){t.log("Could not remove session: ".concat(e)),t.hls&&t.hls.trigger(ne.ERROR,{type:re.OTHER_ERROR,details:ie.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error("Could not remove session: ".concat(e))})}).then(function(){return r.close()}).then(function(){return r.closed}).catch(function(e){t.log("Could not close session: ".concat(e)),t.hls&&t.hls.trigger(ne.ERROR,{type:re.OTHER_ERROR,details:ie.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error("Could not close session: ".concat(e))})})}return Promise.resolve()}}])}(Be);function nu(e,t){var r=e.keyId,i=t.mediaKeysSession;if(r&&i){var n=t.mediaKeysSession.keyStatuses;if(n.size)return n.has(r)?n.get(r):t.keyStatuses[ft(r)]}}function au(e,t){var r="output-restricted"===e,i=r?ie.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:ie.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new ru({type:re.KEY_SYSTEM_ERROR,details:i,fatal:!1,decryptdata:t},r?"HDCP level output restricted":'key status changed to "'.concat(e,'"'))}iu.CDMCleanupPromise=void 0;var su=function(){return l(function e(t){s(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(ne.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(ne.MEDIA_DETACHING,this.onMediaDetaching,this)}},{key:"unregisterListeners",value:function(){this.hls.off(ne.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(ne.MEDIA_DETACHING,this.onMediaDetaching,this)}},{key:"destroy",value:function(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}},{key:"onMediaAttaching",value:function(e,t){var r=this.hls.config;if(r.capLevelOnFPSDrop){var i=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=i,i&&"function"==typeof i.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}}},{key:"onMediaDetaching",value:function(){this.media=null}},{key:"checkFPS",value:function(e,t,r){var i=performance.now();if(t){if(this.lastTime){var n=i-this.lastTime,a=r-this.lastDroppedFrames,s=t-this.lastDecodedFrames,o=1e3*a/n,l=this.hls;if(l.trigger(ne.FPS_DROP,{currentDropped:a,currentDecoded:s,totalDroppedFrames:r}),o>0&&a>l.config.fpsDroppedMonitoringThreshold*s){var u=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(-1===l.autoLevelCapping||l.autoLevelCapping>=u)&&(u-=1,l.trigger(ne.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:l.currentLevel}),l.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=r,this.lastDecodedFrames=t}}},{key:"checkFPSInterval",value:function(){var e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){var t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}])}(),ou=function(){if(null!=an&&an.VTTCue)return self.VTTCue;var e=["","lr","rl"],t=["start","middle","end","left","right"];function r(e,t){if("string"!=typeof t)return!1;if(!Array.isArray(e))return!1;var r=t.toLowerCase();return!!~e.indexOf(r)&&r}function i(e){return r(t,e)}function n(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];for(var n=1;n<arguments.length;n++){var a=arguments[n];for(var s in a)e[s]=a[s]}return e}function a(t,a,s){var o=this,l={enumerable:!0};o.hasBeenReset=!1;var u="",c=!1,d=t,h=a,f=s,v=null,g="",p=!0,m="auto",y="start",k=50,E="middle",S=50,T="middle";Object.defineProperty(o,"id",n({},l,{get:function(){return u},set:function(e){u=""+e}})),Object.defineProperty(o,"pauseOnExit",n({},l,{get:function(){return c},set:function(e){c=!!e}})),Object.defineProperty(o,"startTime",n({},l,{get:function(){return d},set:function(e){if("number"!=typeof e)throw new TypeError("Start time must be set to a number.");d=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",n({},l,{get:function(){return h},set:function(e){if("number"!=typeof e)throw new TypeError("End time must be set to a number.");h=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",n({},l,{get:function(){return f},set:function(e){f=""+e,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",n({},l,{get:function(){return v},set:function(e){v=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",n({},l,{get:function(){return g},set:function(t){var i=function(t){return r(e,t)}(t);if(!1===i)throw new SyntaxError("An invalid or illegal string was specified.");g=i,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",n({},l,{get:function(){return p},set:function(e){p=!!e,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",n({},l,{get:function(){return m},set:function(e){if("number"!=typeof e&&"auto"!==e)throw new SyntaxError("An invalid number or illegal string was specified.");m=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",n({},l,{get:function(){return y},set:function(e){var t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");y=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",n({},l,{get:function(){return k},set:function(e){if(e<0||e>100)throw new Error("Position must be between 0 and 100.");k=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",n({},l,{get:function(){return E},set:function(e){var t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");E=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",n({},l,{get:function(){return S},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");S=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",n({},l,{get:function(){return T},set:function(e){var t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");T=t,this.hasBeenReset=!0}})),o.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}(),lu=function(){return l(function e(){s(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 uu(e){function t(e,t,r,i){return 3600*(0|e)+60*(0|t)+(0|r)+parseFloat(i||0)}var r=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return r?parseFloat(r[2])>59?t(r[2],r[3],0,r[4]):t(r[1],r[2],r[3],r[4]):null}var cu=function(){return l(function e(){s(this,e),this.values=Object.create(null)},[{key:"set",value:function(e,t){this.get(e)||""===t||(this.values[e]=t)}},{key:"get",value:function(e,t,r){return r?this.has(e)?this.values[e]:t[r]:this.has(e)?this.values[e]:t}},{key:"has",value:function(e){return e in this.values}},{key:"alt",value:function(e,t,r){for(var i=0;i<r.length;++i)if(t===r[i]){this.set(e,t);break}}},{key:"integer",value:function(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}},{key:"percent",value:function(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){var r=parseFloat(t);if(r>=0&&r<=100)return this.set(e,r),!0}return!1}}])}();function du(e,t,r,i){var n=i?e.split(i):[e];for(var a in n)if("string"==typeof n[a]){var s=n[a].split(r);if(2===s.length)t(s[0],s[1])}}var hu=new ou(0,0,""),fu="middle"===hu.align?"middle":"center";function vu(e,t,r){var i=e;function n(){var t=uu(e);if(null===t)throw new Error("Malformed timestamp: "+i);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function a(){e=e.replace(/^\s+/,"")}if(a(),t.startTime=n(),a(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+i);e=e.slice(3),a(),t.endTime=n(),a(),function(e,t){var i=new cu;du(e,function(e,t){var n;switch(e){case"region":for(var a=r.length-1;a>=0;a--)if(r[a].id===t){i.set(e,r[a].region);break}break;case"vertical":i.alt(e,t,["rl","lr"]);break;case"line":n=t.split(","),i.integer(e,n[0]),i.percent(e,n[0])&&i.set("snapToLines",!1),i.alt(e,n[0],["auto"]),2===n.length&&i.alt("lineAlign",n[1],["start",fu,"end"]);break;case"position":n=t.split(","),i.percent(e,n[0]),2===n.length&&i.alt("positionAlign",n[1],["start",fu,"end","line-left","line-right","auto"]);break;case"size":i.percent(e,t);break;case"align":i.alt(e,t,["start",fu,"end","left","right"])}},/:/,/\s/),t.region=i.get("region",null),t.vertical=i.get("vertical","");var n=i.get("line","auto");"auto"===n&&-1===hu.line&&(n=-1),t.line=n,t.lineAlign=i.get("lineAlign","start"),t.snapToLines=i.get("snapToLines",!0),t.size=i.get("size",100),t.align=i.get("align",fu);var a=i.get("position","auto");"auto"===a&&50===hu.position&&(a="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=a}(e,t)}function gu(e){return e.replace(/<br(?: \/)?>/gi,"\n")}var pu=function(){return l(function e(){s(this,e),this.state="INITIAL",this.buffer="",this.decoder=new lu,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0},[{key:"parse",value:function(e){var t=this;function r(){var e=t.buffer,r=0;for(e=gu(e);r<e.length&&"\r"!==e[r]&&"\n"!==e[r];)++r;var i=e.slice(0,r);return"\r"===e[r]&&++r,"\n"===e[r]&&++r,t.buffer=e.slice(r),i}function i(e){du(e,function(e,t){},/:/)}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{var n="";if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;var a=(n=r()).match(/^()?WEBVTT([ \t].*)?$/);if(null==a||!a[0])throw new Error("Malformed WebVTT signature.");t.state="HEADER"}for(var s=!1;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(s?s=!1:n=r(),t.state){case"HEADER":/:/.test(n)?i(n):n||(t.state="ID");continue;case"NOTE":n||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(n)){t.state="NOTE";break}if(!n)continue;if(t.cue=new ou(0,0,""),t.state="CUE",-1===n.indexOf("--\x3e")){t.cue.id=n;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{vu(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}}])}();function mu(e){for(var t=5381,r=e.length;r;)t=33*t^e.charCodeAt(--r);return(t>>>0).toString()}var yu=/\r\n|\n\r|\n|\r/g,ku="Missing initPTS for VTT ";function Eu(e,t,r){return mu(e.toString())+mu(t.toString())+mu(r)}function Su(e,t,r,i,n,a,s){var o,l=new pu,u=at(new Uint8Array(e)).trim().replace(yu,"\n").split("\n"),c=[],d=t?function(e){return Ls(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=!1,p=!0;l.oncue=function(e){var a=r[i],s=r.ccOffset,l=(f-d)/9e4;if(g){if(null!=a&&a.new&&(s=r.ccOffset=a.start),l){if(!t)return void(o=new Error(ku+"MPEGTS"));s=l-r.presentationOffset}}else{if(!t)return void(o=new Error(ku+"without X-TIMESTAMP-MAP"));s=-t.baseTime/t.timescale}var u=e.endTime-e.startTime,h=Ms(9e4*(e.startTime+s-v),9e4*n)/9e4;e.startTime=Math.max(h,0),e.endTime=Math.max(h+u,0);var p=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(p)),e.id?i&&(e.id="hlsjscc".concat(i,"_").concat(e.id)):e.id=Eu(e.startTime,e.endTime,p),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(p){if(e.startsWith("X-TIMESTAMP-MAP=")){p=!1,g=!0,e.slice(16).split(",").forEach(function(e){e.startsWith("LOCAL:")?h=e.slice(6):e.startsWith("MPEGTS:")&&(f=parseInt(e.slice(7)))});try{v=function(e){var t=parseInt(e.slice(-3)),r=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),n=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(Z(t)&&Z(r)&&Z(i)&&Z(n)))throw Error("Malformed X-TIMESTAMP-MAP: Local:".concat(e));return t+=1e3*r,t+=6e4*i,t+36e5*n}(h)/1e3}catch(e){o=e}return}""===e&&(p=!1)}l.parse(e+"\n")}),l.flush()}var Tu="stpp.ttml.im1t",Au=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,bu=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Iu={left:"start",center:"center",right:"end",start:"start",end:"end"};function Ru(e,t,r,i){var n=Ct(new Uint8Array(e),["mdat"]);if(0!==n.length){var a=n.map(function(e){return at(e)}),s=function(e,t){return Ls(e,t,1/(arguments.length>2&&void 0!==arguments[2]?arguments[2]:1),arguments.length>3&&void 0!==arguments[3]&&arguments[3])}(t.baseTime,1,t.timescale);try{a.forEach(function(e){return r(function(e,t){var r=(new DOMParser).parseFromString(e,"text/xml"),i=r.getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");var n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:1},a=Object.keys(n).reduce(function(e,t){return e[t]=i.getAttribute("ttp:".concat(t))||n[t],e},{});!i.getAttribute("ttp:tickRate")&&i.getAttribute("ttp:frameRate")&&(a.tickRate=Number(a.frameRate)*Number(a.subFrameRate));var s="preserve"!==i.getAttribute("xml:space"),o=Pu(Lu(i,"styling","style")),l=Pu(Lu(i,"layout","region")),u=Lu(i,"body","[begin]");return[].map.call(u,function(e){var r=wu(e,s);if(!r||!e.hasAttribute("begin"))return null;var i=_u(e.getAttribute("begin"),a),n=_u(e.getAttribute("dur"),a),u=_u(e.getAttribute("end"),a);if(null===i)throw Du(e);if(null===u){if(null===n)throw Du(e);u=i+n}var c=new ou(i-t,u-t,r);c.id=Eu(c.startTime,c.endTime,c.text);var d=function(e,t,r){var i="http://www.w3.org/ns/ttml#styling",n=null,a=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],s=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;s&&r.hasOwnProperty(s)&&(n=r[s]);return a.reduce(function(r,a){var s=Cu(t,i,a)||Cu(e,i,a)||Cu(n,i,a);return s&&(r[a]=s),r},{})}(l[e.getAttribute("region")],o[e.getAttribute("style")],o),h=d.textAlign;if(h){var f=Iu[h];f&&(c.lineAlign=f),c.align=h}return Ae(c,d),c}).filter(function(e){return null!==e})}(e,s))})}catch(e){i(e)}}else i(new Error("Could not parse IMSC1 mdat"))}function Lu(e,t,r){var i=e.getElementsByTagName(t)[0];return i?[].slice.call(i.querySelectorAll(r)):[]}function Pu(e){return e.reduce(function(e,t){var r=t.getAttribute("xml:id");return r&&(e[r]=t),e},{})}function wu(e,t){return[].slice.call(e.childNodes).reduce(function(e,r,i){var n;return"br"===r.nodeName&&i?e+"\n":null!=(n=r.childNodes)&&n.length?wu(r,t):t?e+r.textContent.trim().replace(/\s+/g," "):e+r.textContent},"")}function Cu(e,t,r){return e&&e.hasAttributeNS(t,r)?e.getAttributeNS(t,r):null}function Du(e){return new Error("Could not parse ttml timestamp ".concat(e))}function _u(e,t){if(!e)return null;var r=uu(e);return null===r&&(Au.test(e)?r=function(e,t){var r=Au.exec(e),i=(0|r[4])+(0|r[5])/t.subFrameRate;return 3600*(0|r[1])+60*(0|r[2])+(0|r[3])+i/t.frameRate}(e,t):bu.test(e)&&(r=function(e,t){var r=bu.exec(e),i=Number(r[1]);switch(r[2]){case"h":return 3600*i;case"m":return 60*i;case"ms":return i/1e3;case"f":return i/t.frameRate;case"t":return i/t.tickRate}return i}(e,t))),r}function Mu(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:"disabled",a=e.ownerDocument.createElement("track");return a.kind=t,a.label=r,i&&(a.srclang=i),a.src="data:,WEBVTT",a.track.mode=n,e.appendChild(a),a}function xu(e){return e.forced&&(tr.indexOf("Apple")>-1||/iPhone|iPad|iPod/.test(er))?"forced":e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function Ou(e,t){var r=e.mode;if("disabled"===r&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error("addCue is failed for: ".concat(t))}catch(r){je.debug("[texttrack-utils]: ".concat(r));try{var i=new self.TextTrackCue(t.startTime,t.endTime,t.text);i.id=t.id,e.addCue(i)}catch(e){je.debug("[texttrack-utils]: Legacy TextTrackCue fallback failed: ".concat(e))}}"disabled"===r&&(e.mode=r)}function Fu(e,t,r,i){var n=e.mode;if("disabled"===n&&(e.mode="hidden"),e.cues&&e.cues.length>0)for(var a=function(e,t,r){var i=[],n=function(e,t){if(t<=e[0].startTime)return 0;var r=e.length-1;if(t>e[r].endTime)return-1;var i,n=0,a=r;for(;n<=a;)if(t<e[i=Math.floor((a+n)/2)].startTime)a=i-1;else{if(!(t>e[i].startTime&&n<r))return i;n=i+1}return e[n].startTime-t<t-e[a].startTime?n:a}(e,t);if(n>-1)for(var a=n,s=e.length;a<s;a++){var o=e[a];if(o.startTime>=t&&o.endTime<=r)i.push(o);else if(o.startTime>r)return i}return i}(e.cues,t,r),s=0;s<a.length;s++)i&&!i(a[s])||e.removeCue(a[s]);"disabled"===n&&(e.mode=n)}var Nu=function(e){function t(e){var r;return s(this,t),(r=a(this,t,[e,"subtitle-track-controller"])).media=null,r.tracks=[],r.groupIds=null,r.tracksInGroup=[],r.trackId=-1,r.currentTrack=null,r.selectDefaultTrack=!0,r.queuedDefaultTrack=-1,r.useTextTrackPolling=!1,r.subtitlePollingInterval=-1,r._subtitleDisplay=!0,r.asyncPollTrackChange=function(){return r.pollTrackChange(0)},r.onTextTracksChanged=function(){if(r.useTextTrackPolling||self.clearInterval(r.subtitlePollingInterval),r.media&&r.hls.config.renderTextTracksNatively){var e,t=-1,i=!1;if(r.currentTrack){var n,a=null==(n=r.currentTrack.trackNode)?void 0:n.track.mode;"showing"===a?(t=r.trackId,i=!0):"hidden"===a&&(t=r.trackId)}if(!i)for(var s=0;s<r.tracksInGroup.length;s++){var o,l=null==(o=r.tracksInGroup[s].trackNode)?void 0:o.track.mode;if("showing"===l){t=s;break}t<0&&"hidden"===l&&(t=s)}if(t>-1)r._subtitleDisplay="showing"===(null==(e=r.tracksInGroup[t].trackNode)?void 0:e.track.mode);r.setSubtitleTrack(t,!0)}},r.registerListeners(),r}return f(t,e),l(t,[{key:"destroy",value:function(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,A(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(ne.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ne.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ne.MANIFEST_PARSED,this.onManifestParsed,this),e.on(ne.LEVEL_LOADING,this.onLevelLoading,this),e.on(ne.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(ne.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(ne.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(ne.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ne.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ne.MANIFEST_PARSED,this.onManifestParsed,this),e.off(ne.LEVEL_LOADING,this.onLevelLoading,this),e.off(ne.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(ne.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(ne.ERROR,this.onError,this)}},{key:"createTracksInGroup",value:function(){var e,t=this;if(this.media&&this.hls.config.renderTextTracksNatively){this.tracksInGroup.forEach(function(e){e.trackNode||(e.trackNode=Mu(t.media,xu(e),e.name,e.lang))});var r=null==(e=this.currentTrack)||null==(e=e.trackNode)?void 0:e.track;"disabled"===(null==r?void 0:r.mode)&&(r.mode=this._subtitleDisplay?"showing":"hidden")}}},{key:"onMediaAttached",value:function(e,t){var r=t.media;this.media=r;var i=this.trackId;this.queuedDefaultTrack>-1&&(i=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.setSubtitleTrack(i),this.createTracksInGroup(),this.useTextTrackPolling=!(r.textTracks&&"onchange"in r.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):r.textTracks.addEventListener("change",this.asyncPollTrackChange)}},{key:"pollTrackChange",value:function(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}},{key:"onMediaDetaching",value:function(e,t){var r=this.media;if(r){var i=!!t.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||r.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId,this.setSubtitleTrack(-1)),this.media=null,i||this.hls.config.renderTextTracksNatively&&this.tracksInGroup.forEach(function(e){var t=e.trackNode;t&&(t.track.mode="hidden",t.remove(),e.trackNode=void 0)})}}},{key:"onManifestLoading",value:function(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}},{key:"onManifestParsed",value:function(e,t){this.tracks=t.subtitleTracks}},{key:"onSubtitleTrackLoaded",value:function(e,t){var r=t.id,i=t.groupId,n=t.details,a=this.tracksInGroup[r];if(a&&a.groupId===i){var s=a.details;a.details=t.details,this.log("Subtitle track ".concat(r,' "').concat(a.name,'" lang:').concat(a.lang," group:").concat(i," loaded [").concat(n.startSN,"-").concat(n.endSN,"]")),r===this.trackId&&this.playlistLoaded(r,t,s)}else this.warn("Subtitle track with id:".concat(r," and group:").concat(i," not found in active group ").concat(null==a?void 0:a.groupId))}},{key:"onLevelLoading",value:function(e,t){this.switchLevel(t.level)}},{key:"onLevelSwitching",value:function(e,t){this.switchLevel(t.level)}},{key:"switchLevel",value:function(e){var t=this,r=this.hls.levels[e];if(r){var i=r.subtitleGroups||null,n=this.groupIds,a=this.currentTrack;if(!i||(null==n?void 0:n.length)!==(null==i?void 0:i.length)||null!=i&&i.some(function(e){return-1===(null==n?void 0:n.indexOf(e))})){this.groupIds=i;var s=[];if(this.tracks.forEach(function(e){(e.textCodec===Tu?t.hls.config.enableIMSC1:t.hls.config.enableWebVTT)&&(!i||i.indexOf(e.groupId)>-1?(e.id=s.length,s.push(e)):e.trackNode&&(e.trackNode.remove(),e.trackNode=void 0))}),s.length===this.tracksInGroup.length){for(var o=!1,l=0;l<s.length;l++)if(s[l]!==this.tracksInGroup[l]){o=!0;break}if(!o)return}s.length&&this.selectDefaultTrack&&!s.some(function(e){return e.default})&&(this.selectDefaultTrack=!1),this.tracksInGroup=s,this.trackId=-1,this.currentTrack=null;var u=this.hls.config.subtitlePreference;if(!a&&u){this.selectDefaultTrack=!1;var c=Gr(u,s);if(c>-1)a=s[c];else{var d=Gr(u,this.tracks);a=this.tracks[d]}}var h=this.findTrackId(a);-1===h&&a&&(h=this.findTrackId(null));var f={subtitleTracks:s};this.log("Updating subtitle tracks, ".concat(s.length,' track(s) found in "').concat(null==i?void 0:i.join(","),'" group-id')),this.hls.trigger(ne.SUBTITLE_TRACKS_UPDATED,f),this.setSubtitleTrack(h),this.createTracksInGroup()}}}},{key:"findTrackId",value:function(e){for(var t=this.tracksInGroup,r=this.selectDefaultTrack,i=0;i<t.length;i++){var n=t[i];if((!r||n.default)&&(r||e)&&(!e||Hr(n,e)))return i}if(e){for(var a=0;a<t.length;a++){var s=t[a];if($s(e.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return a}for(var o=0;o<t.length;o++){var l=t[o];if($s(e.attrs,l.attrs,["LANGUAGE"]))return o}}return-1}},{key:"onError",value:function(e,t){!t.fatal&&t.context&&t.context.type===ce.SUBTITLE_TRACK&&t.context.id===this.trackId&&Wr(t.context.groupId,this.groupIds)&&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,!0)}},{key:"setSubtitleOption",value:function(e){if(this.hls.config.subtitlePreference=e,e){if(-1===e.id)return this.setSubtitleTrack(-1,!0),null;var t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){var r=this.currentTrack;if(r&&Hr(e,r))return r;var i=Gr(e,this.tracksInGroup);if(i>-1){var n=this.tracksInGroup[i];return this.setSubtitleTrack(i,!0),n}if(r)return null;var a=Gr(e,t);if(a>-1)return t[a]}}return null}},{key:"loadPlaylist",value:function(e){A(t,"loadPlaylist",this,3)([]),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}},{key:"loadingPlaylist",value:function(e,r){A(t,"loadingPlaylist",this,3)([e,r]);var i=e.id,n=e.groupId,a=this.getUrlWithDirectives(e.url,r),s=e.details,o=null==s?void 0:s.age;this.log("Loading subtitle ".concat(i,' "').concat(e.name,'" lang:').concat(e.lang," group:").concat(n).concat(void 0!==(null==r?void 0:r.msn)?" at sn "+r.msn+" part "+r.part:"").concat(o&&s.live?" age "+o.toFixed(1)+(s.type&&" "+s.type||""):""," ").concat(a)),this.hls.trigger(ne.SUBTITLE_TRACK_LOADING,{url:a,id:i,groupId:n,deliveryDirectives:r||null,track:e})}},{key:"toggleTrackModes",value:function(){var e=this;if(this.media&&this.hls.config.renderTextTracksNatively){var t=this.currentTrack;this.tracksInGroup.forEach(function(r){if(r.trackNode){var i=r===t?e._subtitleDisplay?"showing":"hidden":"disabled",n=r.trackNode.track;n.mode!==i&&(n.mode=i)}})}}},{key:"setSubtitleTrack",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=this.tracksInGroup;if(this.media||(this.queuedDefaultTrack=e),e<-1||e>=r.length||!Z(e))this.warn("Invalid subtitle track id: ".concat(e));else{var i=this.currentTrack,n=r[e]||null;if(this.trackId=e,this.currentTrack=n,t&&this.toggleTrackModes(),n){var a=!!n.details&&!n.details.live;if(n!==i||!a){this.log("Switching to subtitle-track ".concat(e)+(n?' "'.concat(n.name,'" lang:').concat(n.lang," group:").concat(n.groupId):""));var s=n.id,o=n.groupId,l=void 0===o?"":o,u=n.name,c=n.type,d=n.url;this.hls.trigger(ne.SUBTITLE_TRACK_SWITCH,{id:s,groupId:l,name:u,type:c,url:d});var h=this.switchParams(n.url,null==i?void 0:i.details,n.details);this.loadPlaylist(h)}}else i&&this.hls.trigger(ne.SUBTITLE_TRACK_SWITCH,{id:e})}}}])}(Xs),Bu=function(e){function t(e,r){var i;return s(this,t),(i=a(this,t,["gap-controller",e.logger])).hls=void 0,i.fragmentTracker=void 0,i.media=null,i.mediaSource=void 0,i.nudgeRetry=0,i.skipRetry=0,i.stallReported=!1,i.stalled=null,i.moved=!1,i.seeking=!1,i.buffered={},i.lastCurrentTime=void 0,i.ended=0,i.waiting=0,i.onMediaPlaying=function(){i.ended=0,i.waiting=0},i.onMediaWaiting=function(){var e;null!=(e=i.media)&&e.seeking||(i.waiting=self.performance.now(),i.tick())},i.onMediaEnded=function(){var e;i.hls&&(i.ended=(null==(e=i.media)?void 0:e.currentTime)||1,i.hls.trigger(ne.MEDIA_ENDED,{stalled:!1}))},i.hls=e,i.fragmentTracker=r,i.lastCurrentTime=i.getCurrentTime(),i.registerListeners(),i}return f(t,e),l(t,[{key:"registerListeners",value:function(){var e=this.hls;e&&(e.on(ne.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ne.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ne.BUFFER_APPENDED,this.onBufferAppended,this))}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ne.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ne.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ne.BUFFER_APPENDED,this.onBufferAppended,this))}},{key:"destroy",value:function(){A(t,"destroy",this,3)([]),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}},{key:"onMediaAttached",value:function(e,t){this.setInterval(100),this.mediaSource=t.mediaSource;var r=this.media=t.media;ta(r,"playing",this.onMediaPlaying),ta(r,"waiting",this.onMediaWaiting),ta(r,"ended",this.onMediaEnded)}},{key:"onMediaDetaching",value:function(e,t){this.clearInterval();var r=this.media;r&&(ra(r,"playing",this.onMediaPlaying),ra(r,"waiting",this.onMediaWaiting),ra(r,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}},{key:"onBufferAppended",value:function(e,t){this.buffered=t.timeRanges}},{key:"hasBuffered",get:function(){return Object.keys(this.buffered).length>0}},{key:"getCurrentTime",value:function(){var e,t=(null==(e=this.hls)?void 0:e.config.timelineOffset)||0;return this.media?Math.max(this.media.currentTime,t):t}},{key:"tick",value:function(){var e;if(null!=(e=this.media)&&e.readyState&&this.hasBuffered){var t=this.getCurrentTime();this.media.currentTime<t||(this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t)}}},{key:"poll",value:function(e,t){var r,i,n=null==(r=this.hls)?void 0:r.config;if(n){var a=this.media;if(a){var s=a.seeking,o=this.seeking&&!s,l=!this.seeking&&s,u=a.paused&&!s||a.ended||0===a.playbackRate;if(this.seeking=s,e!==t)return t&&(this.ended=0),this.moved=!0,s||(this.skipRetry=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.skipRetry=this.nudgeRetry=0,this.stallResolved(e),void(!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(ne.MEDIA_ENDED,{stalled:!1})));if(Bi.getBuffered(a).length){var c=Bi.bufferInfo(a,e,0),d=this.fragmentTracker;d&&this.hls&&Hu(c,e,d,this.hls);var h=c.nextStart||0;if(s&&d&&this.hls){var f=Uu(this.hls.inFlightFragments,e),v=c.len>2,g=!h||f||h-e>2&&!d.getPartialFragment(e);if(v||g)return;this.moved=!1}var p=null==(i=this.hls)?void 0:i.latestLevelDetails;if(!this.moved&&null!==this.stalled&&d){if(!(c.len>0)&&!h)return;var m=Math.max(h,c.start||0)-e,y=!(null==p||!p.live)?2*p.targetduration:2,k=Gu(e,d);if(m>0&&(m<=y||k))return void(a.paused||this._trySkipBufferHole(k))}var E=n.detectStallWithCurrentTimeMs,S=self.performance.now(),T=this.waiting,A=this.stalled;if(null===A){if(!(T>0&&S-T<E))return void(this.stalled=S);A=this.stalled=T}var b=S-A;if(!s&&(b>=E||T&&this.moved)&&this.hls){var I;if("ended"===(null==(I=this.mediaSource)?void 0:I.readyState)&&(null==p||!p.live)&&Math.abs(e-((null==p?void 0:p.edge)||0))<1){if(this.ended)return;return this.ended=e||1,void this.hls.trigger(ne.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(c),!this.media||!this.hls)return;if(a.currentTime!==e){var R=e;return e=a.currentTime,this.moved=!0,void this.log("currentTime changed ".concat(R," > ").concat(e))}}var L=Bi.bufferInfo(a,e,n.maxBufferHole);this._tryFixBufferStall(L,b,e)}else this.skipRetry=this.nudgeRetry=0}}}}},{key:"stallResolved",value:function(e){var t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){var r=self.performance.now()-t;this.log("playback not stuck anymore @".concat(e,", after ").concat(Math.round(r),"ms")),this.stallReported=!1,this.waiting=0,this.hls.trigger(ne.STALL_RESOLVED,{})}}},{key:"nudgeOnVideoHole",value:function(e,t){var r,i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(r=this.buffered.audio)&&r.length&&i&&i.length>1&&e>i.end(0)){var n=Bi.bufferedInfo(Bi.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){var a=Bi.timeRangesToArray(i),s=Bi.bufferedInfo(a,t,0).bufferedIndex;if(s>-1&&s<a.length-1){var o=Bi.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=Gu(e,this.fragmentTracker);d&&"fragment"in d?d=d.fragment:d||(d=void 0);var h=Bi.bufferInfo(this.media,e,0);this.hls.trigger(ne.ERROR,{type:re.MEDIA_ERROR,details:ie.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:c,reason:c.message,frag:d,buffer:h.len,bufferInfo:h})}}}}}},{key:"_tryFixBufferStall",value:function(e,t,r){var i,n,a=this.fragmentTracker,s=this.media,o=null==(i=this.hls)?void 0:i.config;if(s&&a&&o){var l=null==(n=this.hls)?void 0:n.latestLevelDetails,u=Gu(r,a);if(u||null!=l&&l.live&&r<l.fragmentStart)if(this._trySkipBufferHole(u)||!this.media)return;var c=e.buffered,d=this.adjacentTraversal(e,r);(c&&c.length>1&&e.len>o.maxBufferHole||e.nextStart&&(e.nextStart-r<o.maxBufferHole||d))&&(t>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}}},{key:"adjacentTraversal",value:function(e,t){var r=this.fragmentTracker,i=e.nextStart;if(r&&i){var n=r.getFragAtPos(t,de.MAIN),a=r.getFragAtPos(i,de.MAIN);if(n&&a)return a.sn-n.sn<2}return!1}},{key:"_reportStall",value:function(e){var t=this.hls,r=this.media,i=this.stallReported,n=this.stalled;if(!i&&null!==n&&r&&t){this.stallReported=!0;var a=new Error("Playback stalling at @".concat(r.currentTime," due to low buffer (").concat(Nr(e),")"));this.warn(a.message),t.trigger(ne.ERROR,{type:re.MEDIA_ERROR,details:ie.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:n}})}}},{key:"_trySkipBufferHole",value:function(e){var t=this.fragmentTracker,r=this.media,i=this.hls,n=null==i?void 0:i.config;if(!r||!t||!n)return 0;var a=r.currentTime,s=Bi.bufferInfo(r,a,0);Hu(s,a,t,i);var o=a<s.start?s.start:s.nextStart;if(o){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=t.getAppendedFrag(0,de.MAIN);h&&o<h.end&&(d=!0)}if(!d&&e){var f;if(null==(f=i.loadLevelObj)||!f.details)return 0;if(Uu(i.inFlightFragments,o))return 0;for(var v=!1,g=e.end;g<o;){var p=Gu(g,t),m=p?p.duration:0;if(!(m>0)){v=!0;break}g+=m}if(v)return 0}}var y=n.nudgeMaxRetry,k=n.skipBufferHolePadding,E=++this.skipRetry>y,S=Math.max(o,a)+k;if(E||(this.warn("skipping hole, adjusting currentTime from ".concat(a," to ").concat(S)),this.moved=!0,r.currentTime=S),null==e||!e.gap||E){var T=new Error(E?"Playhead still not moving after seeking over buffer hole from ".concat(a," to ").concat(S," after ").concat(n.nudgeMaxRetry," attempts."):"fragment loaded with buffer holes, seeking from ".concat(a," to ").concat(S)),A={type:re.MEDIA_ERROR,details:ie.BUFFER_SEEK_OVER_HOLE,fatal:E,error:T,reason:T.message,buffer:s.len,bufferInfo:s};e&&("fragment"in e?A.part=e:A.frag=e),i.trigger(ne.ERROR,A)}return S}}return 0}},{key:"_tryNudgeBuffer",value:function(e){var t=this.hls,r=this.media,i=this.nudgeRetry,n=null==t?void 0:t.config;if(!r||!n)return 0;var a=r.currentTime;if(this.nudgeRetry++,i<n.nudgeMaxRetry){var s=a+(i+1)*n.nudgeOffset,o=new Error("Nudging 'currentTime' from ".concat(a," to ").concat(s));this.warn(o.message),r.currentTime=s,t.trigger(ne.ERROR,{type:re.MEDIA_ERROR,details:ie.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(ne.ERROR,{type:re.MEDIA_ERROR,details:ie.BUFFER_STALLED_ERROR,error:l,fatal:!0,buffer:e.len,bufferInfo:e})}}}])}(Oi);function Uu(e,t){var r=Vu(e.main);if(r&&r.start<=t)return r;var i=Vu(e.audio);return i&&i.start<=t?i:null}function Vu(e){if(!e)return null;switch(e.state){case aa:case na:case ha:case fa:return null}return e.frag}function Gu(e,t){return t.getAppendedFrag(e,de.MAIN)||t.getPartialFragment(e)}function Hu(e,t,r,i){var n=i.latestLevelDetails,a=Gu(t,r);if(ya(i.config)&&!e.nextStart&&n&&a&&i.interstitialsManager){var s="type"in a?a:a.fragment,o=ei(n,s.sn);(null==o?void 0:o.level)===s.level&&ma(o,i.interstitialsManager.playerQueue,t)&&(e.nextStart=o.start)}}function Ku(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function ju(e,t,r,i,n){var a=new e(t,r,"");try{a.value=i,n&&(a.type=n)}catch(s){a=new e(t,r,Nr(n?Ie({type:n},i):i))}return a}var qu=function(){var e=Ku();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY}(),Wu=function(){return l(function e(t){var r=this;s(this,e),this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=function(){r.hls&&r.hls.trigger(ne.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(ne.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(ne.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ne.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ne.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(ne.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(ne.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(ne.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}},{key:"_unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ne.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(ne.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ne.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ne.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(ne.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(ne.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(ne.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}},{key:"onMediaAttaching",value:function(e,t){this.media=t.media}},{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.id3Track.remove(),this.id3Track=null),this.dateRangeCuesAppended={})}},{key:"onManifestLoading",value:function(){this.dateRangeCuesAppended={}}},{key:"createTrack",value:function(e){return Mu(e,"metadata","id3","","hidden")}},{key:"onFragParsingMetadata",value:function(e,t){if(this.media&&this.hls){var r=this.hls.config,i=r.enableEmsgMetadataCues,n=r.enableID3MetadataCues;if(i||n){var a=t.samples;this.id3Track||(this.id3Track=this.createTrack(this.media));var s=Ku();if(s)for(var o=0;o<a.length;o++){var l=a[o].type;if((l!==xa.emsg||i)&&n){var u=ut(a[o].data),c=a[o].pts,d=c+a[o].duration;d>qu&&(d=qu),d-c<=0&&(d=c+.25);for(var h=0;h<u.length;h++){var f=u[h];if(!ct(f)){this.updateId3CueEnds(c,l);var v=ju(s,c,d,f,l);v&&this.id3Track.track.addCue(v)}}}}}}}},{key:"updateId3CueEnds",value:function(e,t){var r,i=null==(r=this.id3Track)?void 0:r.track.cues;if(i)for(var n=i.length;n--;){var a=i[n];a.type===t&&a.startTime<e&&a.endTime===qu&&(a.endTime=e)}}},{key:"onBufferFlushing",value:function(e,t){var r=t.startOffset,i=t.endOffset,n=t.type,a=this.id3Track,s=this.hls;if(s){var o,l=s.config,u=l.enableEmsgMetadataCues,c=l.enableID3MetadataCues;if(a&&(u||c))o="audio"===n?function(e){return e.type===xa.audioId3&&c}:"video"===n?function(e){return e.type===xa.emsg&&u}:function(e){return e.type===xa.audioId3&&c||e.type===xa.emsg&&u},Fu(a.track,r,i,o)}}},{key:"onLevelUpdated",value:function(e,t){var r=t.details;this.updateDateRangeCues(r,!0)}},{key:"onLevelPtsUpdated",value:function(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}},{key:"updateDateRangeCues",value:function(e,t){var r=this;if(this.hls&&this.media){var i=this.hls.config,n=i.assetPlayerId,a=i.timelineOffset,s=i.enableDateRangeMetadataCues,o=i.interstitialsController;if(s){var l=Ku();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=ju(l,u,c,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"))&&(d.id=n,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.track.addCue(d),d.addEventListener("enter",this.onEventCueEnter))}if(e.hasProgramDateTime){var h,f=this.id3Track,v=e.dateRanges,g=Object.keys(v),p=this.dateRangeCuesAppended;if(f&&t)if(null!=(h=f.track.cues)&&h.length)for(var m,y=Object.keys(p).filter(function(e){return-1===g.indexOf(e)}),k=function(){var e=y[E],t=null==(m=p[e])?void 0:m.cues;delete p[e],t&&Object.keys(t).forEach(function(e){var i=t[e];if(i){i.removeEventListener("enter",r.onEventCueEnter);try{f.track.removeCue(i)}catch(e){}}})},E=y.length;E--;)k();else p=this.dateRangeCuesAppended={};var S=e.fragments[e.fragments.length-1];if(0!==g.length&&Z(null==S?void 0:S.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(var T=function(){var e=g[A],t=v[e],i=t.startTime,n=p[e],a=(null==n?void 0:n.cues)||{},s=(null==n?void 0:n.durationKnown)||!1,u=qu,c=t.duration;if(t.endDate&&null!==c)u=i+c,s=!0;else if(t.endOnNext&&!s){var d=g.reduce(function(e,r){if(r!==t.id){var i=v[r];if(i.class===t.class&&i.startDate>t.startDate&&(!e||t.startDate<e.startDate))return i}return e},null);d&&(u=d.startTime,s=!0)}for(var h=Object.keys(t.attr),f=0;f<h.length;f++){var m=h[f];if(Yi(m)){var y=a[m];if(y)!s||null!=n&&n.durationKnown?Math.abs(y.startTime-i)>.01&&(y.startTime=i,y.endTime=u):y.endTime=u;else if(l){var k=t.attr[m];zi(m)&&(k=vt(k));var E=ju(l,i,u,{key:m,data:k},xa.dateRange);E&&(E.id=e,r.id3Track.track.addCue(E),a[m]=E,o&&("X-ASSET-LIST"!==m&&"X-ASSET-URL"!==m||E.addEventListener("enter",r.onEventCueEnter)))}}}p[e]={cues:a,dateRange:t,durationKnown:s}},A=0;A<g.length;A++)T()}}}}}}])}();function Yu(){return self.SourceBuffer||self.WebKitSourceBuffer}function zu(){if(!qe())return!1;var e=Yu();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}var Xu,Qu,$u=0,Ju=1,Zu=2,ec=function(e){function t(e,r,i){var n;return s(this,t),(n=a(this,t,[e,r,i,"stream-controller",de.MAIN])).audioCodecSwap=!1,n.level=-1,n._forceStartLoad=!1,n._hasEnoughToStart=!1,n.altAudio=$u,n.audioOnly=!1,n._couldBacktrack=!1,n._backtrackFragment=void 0,n.audioCodecSwitch=!1,n.videoBuffer=null,n.onMediaPlaying=function(){n.tick()},n.onMediaSeeked=function(){var e=n.media,t=e?e.currentTime:null;if(null!==t&&Z(t)&&(n.log("Media seeked to ".concat(t)),n.getBufferedFrag(t))){var r=n.getFwdBufferInfoAtPos(e,t,de.MAIN,0);r&&0!==r.len?n.tick():n.log("Main buffer empty at ".concat(t,' on "seeked" event: ').concat(r?r.len:r))}},n.registerListeners(),n}return f(t,e),l(t,[{key:"registerListeners",value:function(){A(t,"registerListeners",this,3)([]);var e=this.hls;e.on(ne.MANIFEST_PARSED,this.onManifestParsed,this),e.on(ne.LEVEL_LOADING,this.onLevelLoading,this),e.on(ne.LEVEL_LOADED,this.onLevelLoaded,this),e.on(ne.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(ne.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(ne.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(ne.BUFFER_CREATED,this.onBufferCreated,this),e.on(ne.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(ne.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(ne.FRAG_BUFFERED,this.onFragBuffered,this)}},{key:"unregisterListeners",value:function(){A(t,"unregisterListeners",this,3)([]);var e=this.hls;e.off(ne.MANIFEST_PARSED,this.onManifestParsed,this),e.off(ne.LEVEL_LOADED,this.onLevelLoaded,this),e.off(ne.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(ne.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(ne.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(ne.BUFFER_CREATED,this.onBufferCreated,this),e.off(ne.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(ne.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(ne.FRAG_BUFFERED,this.onFragBuffered,this)}},{key:"onHandlerDestroying",value:function(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),A(t,"onHandlerDestroying",this,3)([])}},{key:"startLoad",value:function(e,t){if(this.levels){var r=this.lastCurrentTime,i=this.hls;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){var n=i.startLevel;-1===n&&(i.config.testBandwidth&&this.levels.length>1?(n=0,this.bitrateTest=!0):n=i.firstAutoLevel),i.nextLoadLevel=n,this.level=i.loadLevel,this._hasEnoughToStart=!!t}r>0&&-1===e&&!t&&this.initPTS.length&&(this.log("Override startPosition with lastCurrentTime @".concat(r)),e=r),this.state=aa,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,t||this.fragmentTracker.hasFragments(this.playlistType)||(this._hasEnoughToStart=this.startFragRequested=!1),this.tick()}else this._forceStartLoad=!0,this.state=na}},{key:"stopLoad",value:function(){this._forceStartLoad=!1,A(t,"stopLoad",this,3)([])}},{key:"doTick",value:function(){switch(this.state){case ga:var e=this.levels,t=this.level,r=null==e?void 0:e[t],i=null==r?void 0:r.details;if(i&&(!i.live||this.levelLastLoaded===r&&!this.waitForLive(r))){if(this.waitForCdnTuneIn(i))break;this.state=aa;break}if(this.hls.nextLoadLevel!==this.level){this.state=aa;break}break;case la:this.checkRetryDate()}this.state===aa&&this.doTickIdle(),this.onTickEnd()}},{key:"onTickEnd",value:function(){var e;A(t,"onTickEnd",this,3)([]),null!=(e=this.media)&&e.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}},{key:"doTickIdle",value:function(){var e=this.hls,t=this.levelLastLoaded,r=this.levels,i=this.media;if(null!==t&&(i||this.primaryPrefetch||!this.startFragRequested&&e.config.startFragPrefetch)&&(!this.altAudio||!this.audioOnly)){var n=this.buffering?e.nextLoadLevel:e.loadLevel;if(null!=r&&r[n]){var a=r[n],s=this.getMainFwdBufferInfo();if(null!==s){var o=this.getLevelDetails();if(o&&this._streamEnded(s,o)){var l={type:this.targetBufferType()};return this.hls.trigger(ne.BUFFER_EOS,l),void(this.state=ha)}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===ga||this.waitForLive(a))return this.level=n,this.state=ga,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=void 0);var h=this.backtrackFragment?this.backtrackFragment.start:s.end,f=this.getNextFragment(h,u);if(this.couldBacktrack&&!this.fragPrevious&&f&&pe(f)&&this.fragmentTracker.getState(f)!==yi){var v,g=(null!=(v=this.backtrackFragment)?v:f).sn-u.startSN,p=u.fragments[g-1];p&&f.cc===p.cc&&(f=p,this.fragmentTracker.removeFragment(p))}else this.backtrackFragment&&s.len&&(this.backtrackFragment=void 0);if(f&&this.isLoopLoading(f,h)){if(!f.gap){var m=this.audioOnly&&!this.altAudio?he:fe,y=(m===fe?this.videoBuffer:this.mediaBuffer)||this.media;y&&this.afterBufferFlushed(y,m)}f=this.getNextFragmentLoopLoading(f,u,s,de.MAIN,d)}f&&(this.exceedsMaxBuffer(s,d,f)||this.loadFragment(f,a,h))}}}}}}},{key:"loadFragment",value:function(e,r,i){var n=this.fragmentTracker.getState(e);n===gi||n===mi?this.bitrateTest?(this.log("Fragment ".concat(e.sn," of level ").concat(e.level," is being downloaded to test bitrate and will not be buffered")),this._loadBitrateTestFrag(e,r)):A(t,"loadFragment",this,3)([e,r,i]):this.clearTrackerIfNeeded(e)}},{key:"immediateLevelSwitch",value:function(){var e;(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==$u)&&(((null==(e=this.getLevelDetails())?void 0:e.fragmentStart)||0)>this.lastCurrentTime&&A(t,"flushMainBuffer",this,3)([0,Number.POSITIVE_INFINITY,"audio"]))}},{key:"getBufferOutput",value:function(){return this.mediaBuffer&&this.altAudio===Zu?this.mediaBuffer:this.media}},{key:"checkFragmentChanged",value:function(){var e=this.fragPlaying;if(!this.checkFragPlaying())return!1;var t=this.fragPlaying;if(t){var r=t.level;this.hls.trigger(ne.FRAG_CHANGED,{frag:t,previousFrag:e}),(null==e?void 0:e.level)!==r&&this.hls.trigger(ne.LEVEL_SWITCHED,{level:r})}return!0}},{key:"backtrackFragment",get:function(){return this._backtrackFragment},set:function(e){this._backtrackFragment=e}},{key:"couldBacktrack",get:function(){return this._couldBacktrack},set:function(e){this._couldBacktrack=e}},{key:"abortCurrentFrag",value:function(){this.backtrackFragment=void 0,A(t,"abortCurrentFrag",this,3)([])}},{key:"flushMainBuffer",value:function(e,r){A(t,"flushMainBuffer",this,3)([e,r,this.targetBufferType()])}},{key:"targetBufferType",value:function(){return this.altAudio!==Zu||this.audioOnly?null:"video"}},{key:"onMediaAttached",value:function(e,r){A(t,"onMediaAttached",this,3)([e,r]);var i=r.media;ta(i,"playing",this.onMediaPlaying),ta(i,"seeked",this.onMediaSeeked)}},{key:"onMediaDetaching",value:function(e,r){var i=this.media;i&&(ra(i,"playing",this.onMediaPlaying),ra(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,A(t,"onMediaDetaching",this,3)([e,r]),!!r.transferMedia||(this._hasEnoughToStart=!1)}},{key:"onManifestLoading",value:function(){A(t,"onManifestLoading",this,3)([]),this.log("Trigger BUFFER_RESET"),this.hls.trigger(ne.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.backtrackFragment=void 0,this.altAudio=$u,this.audioOnly=!1}},{key:"onManifestParsed",value:function(e,t){for(var r,i,n=!1,a=!1,s=0;s<t.levels.length;s++){var o=t.levels[s].audioCodec;o&&(n=n||-1!==o.indexOf("mp4a.40.2"),a=a||-1!==o.indexOf("mp4a.40.5"))}this.audioCodecSwitch=n&&a&&!("function"==typeof(null==(i=Yu())||null==(r=i.prototype)?void 0:r.changeType)),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}},{key:"onLevelLoading",value:function(e,t){if(this.levels&&this.state===aa){var r=t.levelInfo;(!r.details||r.details.live&&(this.levelLastLoaded!==r||r.details.expired)||this.waitForCdnTuneIn(r.details))&&(this.state=ga)}}},{key:"onLevelLoaded",value:function(e,t){var r,i=this,n=this.levels,a=this.startFragRequested,s=t.level,o=t.details,l=o.totalduration;if(n){this.log("Level ".concat(s," loaded [").concat(o.startSN,",").concat(o.endSN,"]").concat(o.lastPartSn?"[part-".concat(o.lastPartSn,"-").concat(o.lastPartIndex,"]"):"",", cc [").concat(o.startCC,", ").concat(o.endCC,"] duration:").concat(l));var u=t.levelInfo,c=this.fragCurrent;!c||this.state!==oa&&this.state!==la||c.level!==t.level&&c.loader&&this.abortCurrentFrag();var d=0;if(o.live||null!=(r=u.details)&&r.live){var h;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;d=this.alignPlaylists(o,u.details,null==(h=this.levelLastLoaded)?void 0:h.details)}if(u.details=o,this.levelLastLoaded=u,a||this.setStartPosition(o,d),this.hls.trigger(ne.LEVEL_UPDATED,{details:o,level:s}),this.state===ga){if(this.waitForCdnTuneIn(o))return;this.state=aa}a&&o.live&&this.synchronizeToLiveEdge(o),this.initPTS.some(function(e,t){if(t>=o.startCC)return!0;delete i.initPTS[t]}),this.tick()}else this.warn("Levels were reset while loading level ".concat(s))}},{key:"synchronizeToLiveEdge",value:function(e){var t=this.config,r=this.media;if(r){var i=this.hls.liveSyncPosition,n=this.playhead,a=e.fragmentStart,s=e.edge,o=n>=a-t.maxFragLookUpTolerance&&n<=s;if(null!==i&&r.duration>i&&(n<i||!o)){var l=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!o&&r.readyState<4||n<s-l)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),r.readyState))if(this.warn("Playback: ".concat(n," is located too far from the end of live sliding playlist: ").concat(s,", reset currentTime to : ").concat(i)),"buffered"===this.config.liveSyncMode){var u,c=Bi.bufferInfo(r,i,0);if(null==(u=c.buffered)||!u.length)return void(r.currentTime=i);if(c.start<=n)return void(r.currentTime=i);var d=Bi.bufferedInfo(c.buffered,n,0).nextStart;d&&(r.currentTime=d)}else r.currentTime=i}}}},{key:"_handleFragmentLoadProgress",value:function(e){var t,r=e.frag,i=e.part,n=e.payload,a=this.levels;if(a){var s=a[r.level];if(s){var o=s.details;if(!o)return this.warn("Dropping fragment ".concat(r.sn," of level ").concat(r.level," after level details were reset")),void this.fragmentTracker.removeFragment(r);var l=s.videoCodec,u=o.PTSKnown||!o.live,c=null==(t=r.initSegment)?void 0:t.data,d=this._getAudioCodec(s),h=this.transmuxer=this.transmuxer||new Ys(this.hls,de.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,v=-1!==f,g=_i(r,i,this.iframesOnly),p=g.decryptRange,m=g.byteRange,y=new Fi(r.level,r.sn,r.stats.chunkCount,m?m.end-m.start:n.byteLength,f,v,r.duration,this.iframesOnly,p),k=this.initPTS[r.cc];h.push(n,c,d,l,r,i,o.totalduration,u,y,k)}else this.warn("Level ".concat(r.level," not found on progress"))}else this.warn("Levels were reset while fragment load was in progress. Fragment ".concat(r.sn," of level ").concat(r.level," will not be buffered"))}},{key:"onAudioTrackSwitching",value:function(e,t){var r=this,i=this.hls,n=this.altAudio!==$u;if(qr(t.url,i))this.altAudio=Ju;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=$u,this.fragmentTracker.removeAllFragments(),i.once(ne.BUFFER_FLUSHED,function(){r.hls&&r.hls.trigger(ne.AUDIO_TRACK_SWITCHED,t)}),void i.trigger(ne.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});i.trigger(ne.AUDIO_TRACK_SWITCHED,t)}}},{key:"onAudioTrackSwitched",value:function(e,t){var r=qr(t.url,this.hls);if(r){var i=this.videoBuffer;i&&this.mediaBuffer!==i&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=i)}this.altAudio=r?Zu:$u,this.tick()}},{key:"onBufferCreated",value:function(e,t){var r,i,n=t.tracks,a=!1;for(var s in n){var o=n[s];if("main"===o.id){if(i=s,r=o,"video"===s){var l=n[s];l&&(this.videoBuffer=l.buffer)}}else a=!0}a&&r?(this.log("Alternate track found, use ".concat(i,".buffered to schedule main fragment loading")),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}},{key:"onFragBuffered",value:function(e,t){var r=t.frag,i=t.part,n=r.type===de.MAIN;if(n){if(this.fragContextChanged(r))return this.warn("Fragment ".concat(r.sn).concat(i?" p: "+i.index:""," of level ").concat(r.level," finished buffering, but was aborted. state: ").concat(this.state)),void(this.state===da&&(this.state=aa));var a=!1;if(pe(r)&&(a=!!r.gap&&!r.tagList.some(function(e){return"GAP"===e[0]})),this.fragBufferedComplete(r,i),a){var s;r.stats.retry++;var o=null==(s=this.levels)?void 0:s[r.level];o&&o.fragmentError++}}var l=this.media;l&&(!this._hasEnoughToStart&&Bi.getBuffered(l).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),n&&this.tick())}},{key:"hasEnoughToStart",get:function(){return this._hasEnoughToStart}},{key:"onError",value:function(e,t){var r;if(t.fatal)this.state=fa;else switch(t.details){case ie.FRAG_GAP:case ie.FRAG_PARSING_ERROR:case ie.FRAG_DECRYPT_ERROR:case ie.FRAG_LOAD_ERROR:case ie.FRAG_LOAD_TIMEOUT:case ie.KEY_LOAD_ERROR:case ie.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(de.MAIN,t);break;case ie.LEVEL_LOAD_ERROR:case ie.LEVEL_LOAD_TIMEOUT:case ie.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==ga||(null==(r=t.context)?void 0:r.type)!==ce.LEVEL||(this.state=aa);break;case ie.BUFFER_APPEND_NO_PROGRESS:if("main"!==t.parent)return;t.frag&&(t.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn("Marking fragment ".concat(t.frag.sn," of level ").concat(t.frag.level," as a gap after ").concat(t.appendsWithoutProgress," appends without buffered range growth, to prevent loop loading")),this.fragmentTracker.addAsGap(t.frag));break;case ie.BUFFER_ADD_CODEC_ERROR:case ie.BUFFER_APPEND_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case ie.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 ie.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}},{key:"onFragLoadEmergencyAborted",value:function(){this.state=aa,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}},{key:"onBufferFlushed",value:function(e,t){var r=t.type;if(r!==he||!this.altAudio){var i=(r===fe?this.videoBuffer:this.mediaBuffer)||this.media;i&&(this.afterBufferFlushed(i,r),this.tick())}}},{key:"onLevelsUpdated",value:function(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}},{key:"swapAudioCodec",value:function(){this.audioCodecSwap=!this.audioCodecSwap}},{key:"seekToStartPos",value:function(){var e=this.media;if(e){var t=e.currentTime,r=this.startPosition;if(r>=0&&t<r){if(e.seeking)return void this.log("could not seek to ".concat(r,", already seeking at ").concat(t));var i=this.timelineOffset;i&&r&&(r+=i);var n=this.getLevelDetails(),a=Bi.getBuffered(e),s=a.length?a.start(0):0,o=s-r,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*((null==n?void 0:n.partTarget)||0)))&&(this.log("adjusting start position by ".concat(o," to match buffer start")),r+=o,this.startPosition=r),t<r&&(this.log("seek to target start position ".concat(r," from current time ").concat(t," buffer start ").concat(s)),e.currentTime=r)}}}},{key:"_getAudioCodec",value:function(e){var t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),t}},{key:"_loadBitrateTestFrag",value:function(e,t){var r=this;e.bitrateTest=!0,this._doFragLoad(e,t).then(function(e){var i=r.hls,n=null==e?void 0:e.frag;if(n&&!r.fragContextChanged(n)){t.fragmentError=0,r.state=aa,r.startFragRequested=!1,r.bitrateTest=!1;var a=n.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),i.trigger(ne.FRAG_LOADED,e),n.bitrateTest=!1}}).catch(function(t){r.state!==na&&r.state!==fa&&(r.warn(t),r.resetFragmentLoading(e))})}},{key:"_handleTransmuxComplete",value:function(e){var t=this.playlistType,r=this.hls,i=e.remuxResult,n=e.chunkMeta,a=this.getCurrentContext(n);if(a){var s=a.frag,o=a.part,l=a.level,u=i.video,c=i.text,d=i.id3,h=i.initSegment,f=l.details,v=this.altAudio?void 0:i.audio;if(this.fragContextChanged(s))this.fragmentTracker.removeFragment(s);else{if(this.state=ca,h){var g=h.tracks;if(g){var p=s.initSegment||s;if(this.unhandledEncryptionError(h,s))return;this._bufferInitSegment(l,g,p,n),r.trigger(ne.FRAG_PARSING_INIT_SEGMENT,{frag:p,id:t,tracks:g})}var m=h.initPTS,y=h.timescale,k=this.initPTS[s.cc];if(Z(m)&&(!k||k.baseTime!==m||k.timescale!==y)){var E=h.trackId;this.initPTS[s.cc]={baseTime:m,timescale:y,trackId:E};var S=this.initPTS.slice(0);r.trigger(ne.INIT_PTS_FOUND,{timestampOffsets:S,frag:s,id:t,initPTS:m,timescale:y,trackId:E})}}if(u&&f){v&&"audiovideo"===u.type&&this.logMuxedErr(s);var T=f.fragments[s.sn-1-f.startSN],A=s.sn===f.startSN,b=!T||s.cc>T.cc;if(!1!==i.independent){var I=u.startPTS,R=u.endPTS,L=u.startDTS,P=u.endDTS;if(o)o.elementaryStreams[u.type]={startPTS:I,endPTS:R,startDTS:L,endDTS:P};else if(u.firstKeyFrame&&u.independent&&1===n.id&&!b&&(this.couldBacktrack=!0),u.dropped&&u.independent){var w=this.getMainFwdBufferInfo(),C=(w?w.end:this.getLoadPosition())+this.config.maxBufferHole,D=u.firstKeyFramePTS?u.firstKeyFramePTS:I;if(!A&&C<D-this.config.maxBufferHole&&!b)return void this.backtrack(s);b&&(s.gap=!0),s.setElementaryStreamInfo(u.type,s.start,R,s.start,P,!0)}else A&&I-(f.appliedTimelineOffset||0)>2&&(s.gap=!0);s.setElementaryStreamInfo(u.type,I,R,L,P),this.backtrackFragment&&(this.backtrackFragment=s),this.bufferFragmentData(u,s,o,n,A||b)}else{if(!A&&!b)return void this.backtrack(s);s.gap=!0}}if(v){var _=v.startPTS,M=v.endPTS,x=v.startDTS,O=v.endDTS;o&&(o.elementaryStreams[he]={startPTS:_,endPTS:M,startDTS:x,endDTS:O}),s.setElementaryStreamInfo(he,_,M,x,O),this.bufferFragmentData(v,s,o,n)}if(f&&null!=d&&d.samples.length){var F={id:t,frag:s,details:f,samples:d.samples};r.trigger(ne.FRAG_PARSING_METADATA,F)}if(f&&c){var N={id:t,frag:s,details:f,samples:c.samples};r.trigger(ne.FRAG_PARSING_USERDATA,N)}}}else this.resetWhenMissingContext(n)}},{key:"logMuxedErr",value:function(e){this.warn("".concat(pe(e)?"Media":"Init"," segment with muxed audiovideo where only video expected: ").concat(e.url))}},{key:"_bufferInitSegment",value:function(e,t,r,i){var n=this;if(this.state===ca){this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(r));var a=t.audio,s=t.video,o=t.audiovideo;if(a){var l=e.audioCodec,u=gr(a.codec,l);if("mp4a"===u&&(u="mp4a.40.5"),this.audioCodecSwitch){u&&(u=-1!==u.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");var c=a.metadata;c&&"channelCount"in c&&1!==(c.channelCount||1)&&!function(){if(void 0===Jt){var e=er.match(/Firefox\/(\d+)/i);Jt=e?parseInt(e[1]):0}return Jt}()&&(u="mp4a.40.5")}u&&-1!==u.indexOf("mp4a.40.5")&&/Android/.test(er)&&"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=de.MAIN,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=de.MAIN;var d=s.codec;if(4===(null==d?void 0:d.length))switch(d){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(d,"]").concat(s.codec!==d?" parsed-corrected="+s.codec:"").concat(s.supplemental?" supplemental="+s.supplemental:"")),delete t.audiovideo}o&&(this.iframesOnly&&this.logMuxedErr(r),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 h=Object.keys(t);if(h.length){if(this.hls.trigger(ne.BUFFER_CODECS,t),!this.hls)return;h.forEach(function(e){var a=t[e].initSegment;null!=a&&a.byteLength&&n.hls.trigger(ne.BUFFER_APPENDING,{type:e,data:a,frag:r,part:null,chunkMeta:i,parent:r.type})})}this.tickImmediate()}}},{key:"getMainFwdBufferInfo",value:function(){var e=this.getBufferOutput();return this.getFwdBufferInfo(e,de.MAIN)}},{key:"maxBufferLength",get:function(){var e=this.levels,t=this.level,r=null==e?void 0:e[t];return r?this.getMaxBufferLength(r.maxBitrate):this.config.maxBufferLength}},{key:"backtrack",value:function(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=aa}},{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 Z(t)?this.getAppendedFrag(t):null}},{key:"currentProgramDateTime",get:function(){var e,t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if(Z(t)){var r=this.getLevelDetails(),i=this.currentFrag||(r?Qr(null,r.fragments,t):null);if(i){var n=i.programDateTime;if(null!==n){var a=n+1e3*(t-i.start);return new Date(a)}}}return null}},{key:"currentLevel",get:function(){var e=this.currentFrag;return e?e.level:-1}},{key:"nextBufferedFrag",get:function(){var e=this.currentFrag;return e?this.followingBufferedFrag(e):null}},{key:"forceStartLoad",get:function(){return this._forceStartLoad}}])}(pa),tc=function(e){function t(){var e;s(this,t);for(var r=arguments.length,i=new Array(r),n=0;n<r;n++)i[n]=arguments[n];return(e=a(this,t,[].concat(i))).currentOp=void 0,e.nextOp=void 0,e.cached=[],e.cachedSize=0,e.cacheFragmentData=!0,e.initDetails=void 0,e.onBufferedToEnd=function(){var t=e.media;null!=t&&t.seeking&&(t.currentTime=t.currentTime)},e.onMediaSeeking=function(){},e}return f(t,e),l(t,[{key:"setInitPts",value:function(e){this.initPTS=e.slice()}},{key:"loadMediaAt",value:function(e,t){if(this.hls){var r=t.seekOnAppend,i=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=i,this.startPosition=e,this.state){case na:case ha:case fa:this.state=aa}this.state===aa?(this.hls.resumeBuffering(),this.tick(),this.currentOp=[i,t]):this.nextOp=[i,t],this.hls.off(ne.BUFFERED_TO_END,this.onBufferedToEnd);var n=this.media;if(r&&n)this.seekTo(i)&&(this.currentOp=[i,t],this.nextOp=void 0,this.flushPipeline(i,!0))}}},{key:"seekTo",value:function(e){var t=this.media;if(t){var r,i=null==(r=this.getLevelDetails())?void 0:r.edge,n=void 0!==i?i:t.duration;if(e>=n&&(e=n-.01),Bi.bufferInfo(t,e,0).len>0&&this.getBufferedAt(e))return t.currentTime=e,!0}return!1}},{key:"getBufferedAt",value:function(e){return this.fragmentTracker.getBufferedFrag(e,de.MAIN)}},{key:"cacheSet",value:function(e,t){if(this.hls){e.data=t;var r=this.cached;r.push(e),this.cachedSize+=t.buffer.byteLength;for(var i=this.hls.config.iframeCacheLimit;this.cachedSize>i&&r.length>1;){var n=r.shift();if(!n.data){this.cached=r.filter(function(e){return!!e.data}),this.cachedSize=r.reduce(function(e,t){var r=t.data;return r?r.buffer.byteLength:0},0);break}this.cachedSize-=n.data.byteLength,n.data=void 0}}}},{key:"onHandlerDestroying",value:function(){this.cached.length=0,this.cachedSize=0,A(t,"onHandlerDestroying",this,3)([])}},{key:"_handleFragmentLoadProgress",value:function(e){var r=e.frag,i=e.part,n=e.payload;this.cacheFragmentData&&!i&&null!=n&&n.byteLength&&!r.data&&pe(r)&&this.cacheSet(r,new Uint8Array(n.slice(0))),A(t,"_handleFragmentLoadProgress",this,3)([e])}},{key:"loadFragment",value:function(e,r,i){var n=this.fragmentTracker.getState(e);n!==gi&&n!==mi||!this.canReplayCached(e)?A(t,"loadFragment",this,3)([e,r,i]):this.replayCachedFragment(e)}},{key:"canReplayCached",value:function(e){var t;if(!this.cacheFragmentData||null==(t=e.data)||!t.byteLength)return!1;var r=e.decryptdata;return"identity"!==(null==r?void 0:r.keyFormat)||!!r.key}},{key:"replayCachedFragment",value:function(e){var t=e.data.slice().buffer;this.log("Buffering cached ".concat(e.type," sn: ").concat(e.sn," of level ").concat(e.level," (").concat(t.byteLength," bytes)")),this.fragCurrent=e,this.startFragRequested=!0;var r=e.stats=new ue;r.loading.start=r.loading.first=r.loading.end=self.performance.now(),r.loaded=r.total=t.byteLength,r.chunkCount=1,this.state=oa;var i={frag:e,part:null,payload:t,networkDetails:null};this._handleFragmentLoadProgress(i),this.hls.trigger(ne.FRAG_LOADED,i),this._handleFragmentLoadComplete(i)}},{key:"fragBufferedComplete",value:function(e,r){A(t,"fragBufferedComplete",this,3)([e,r]);var i=this.currentOp,n=this.nextOp;this.currentOp=this.nextOp=void 0,this.state=na,null!=i&&i[1].seekOnAppend&&(this.flushPipeline(i[0],!n),this.seekTo(i[0])||this.log("Could not seek to ".concat(i[0]," after fragment buffered (superseded or flushed) buffer: ").concat(this.media?ia(Bi.getBuffered(this.media)):"none"))),n&&this.loadMediaAt.apply(this,n)}},{key:"flushPipeline",value:function(e,t){if(t){var r=this.media;if(r){var i=Bi.bufferInfo(r,e,0),n=i.len?i.nextStart:0;n&&(this.fragmentTracker.removeFragmentsInRange(n,1/0,de.MAIN),this.flushMainBuffer(n,1/0))}this.hls.once(ne.BUFFERED_TO_END,this.onBufferedToEnd)}this.hls.trigger(ne.BUFFER_EOS,{type:"video"})}},{key:"playhead",get:function(){return this.nextLoadPosition}},{key:"startLoad",value:function(){if(!this.startFragRequested){var e=this.hls;e.nextLoadLevel=-1===e.startLevel?0:e.firstAutoLevel}}},{key:"seekToStartPos",value:function(){}},{key:"setStartPosition",value:function(){}},{key:"alignPlaylists",value:function(e,r,i){var n=this.initDetails;return this.initDetails=null,A(t,"alignPlaylists",this,3)([e,r,i||n||void 0])}},{key:"getMainFwdBufferInfo",value:function(){var e=this.playhead,t=this.getBufferedAt(e);if(t){var r=t.duration;return{len:r,start:e,end:e+r,bufferedIndex:-1}}return{len:0,start:e,end:e,bufferedIndex:-1}}},{key:"_streamEnded",value:function(){var e=this.playhead,t=this.fragmentTracker.getBufferedFrag(e,de.MAIN);return!(null==t||!t.endList)}}])}(ec),rc=function(e){function t(){var e;s(this,t);for(var r=arguments.length,i=new Array(r),n=0;n<r;n++)i[n]=arguments[n];return(e=a(this,t,[].concat(i)))._img=void 0,e.queued=void 0,e.cacheFragmentData=!1,e}return f(t,e),l(t,[{key:"image",get:function(){return this._img},set:function(e){var t,r=null==(t=this._img)?void 0:t.src;r&&self.URL.revokeObjectURL(r),this._img=e}},{key:"loadMediaAt",value:function(e){if(this.hls){var t=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=t,this.startPosition=e,this.state){case na:case ha:case fa:this.state=aa}if(this.state===aa){if(this.hls.resumeBuffering(),this.media||(this.media={}),this.tick(),this.state===aa){var r=this.getBufferedAt(e);r&&(this.fragCurrent=r,this.updateImage(r,null))}}else{var i=this.fragCurrent;(!i||e>=i.start&&e<i.end)&&(this.queued=[t])}}}},{key:"updateImage",value:function(e,t,r){var i=this,n=e.data;n||this.fragmentTracker.removeFragment(e);var a=this._img;if(a&&n){var s=self.performance.now();(t?t.stats:e.stats).buffering.start=e.stats.buffering.start=s,a.onload=function(){if(i.hls){var n=i.hls.levels[e.level];null!=n&&n.fragmentError&&(n.fragmentError=0,e.stats.retry=0);var a=self.performance.now(),s=t?t.stats:e.stats;s.buffering.end=e.stats.buffering.end=a,i.hls.trigger(ne.FRAG_BUFFERED,{frag:e,part:t,stats:s,id:e.type,chunkMeta:r})}},a.onerror=function(){i.handleError("Image decode error",e,t,r)};var o=a.src;o&&self.URL.revokeObjectURL(o);var l=new Blob([n],{type:"image/jpeg"});a.src=self.URL.createObjectURL(l)}else this.state=na,this.processQueued()}},{key:"processQueued",value:function(){var e=this.queued;this.queued=void 0,e&&this.loadMediaAt.apply(this,e)}},{key:"handleError",value:function(e,t,r,i){if(this.hls){var n=new Error(e);this.hls.trigger(ne.ERROR,{type:re.MEDIA_ERROR,details:ie.FRAG_PARSING_ERROR,chunkMeta:i,frag:t,part:r,fatal:!1,error:n,err:n})}}},{key:"_bufferInitSegment",value:function(){}},{key:"bufferFragmentData",value:function(e,r,i,n){A(t,"bufferFragmentData",this,3)([e,r,i,n,!0]);var a=Ct(new Uint8Array(e.data1),["mdat"]);if(0!==a.length){var s=r;this.cacheSet(s,a[0]),this.updateImage(s,i,n)}else this.handleError("Could not find I-Frame mdat",r,i,n)}},{key:"fragBufferedComplete",value:function(e,r){this.fragmentTracker.fragBuffered(e,!0),A(t,"fragBufferedComplete",this,3)([e,r]),this.processQueued()}},{key:"checkFragPlaying",value:function(){var e,t=null==(e=this.fragPrevious)?void 0:e.start;if(void 0!==t){var r=this.getAppendedFrag(t);if(r&&!me(r,this.fragPlaying))return this.fragPlaying=r,!0}return!1}},{key:"getMainFwdBufferInfo",value:function(){return{len:0,start:this.playhead,end:this.playhead,bufferedIndex:-1}}}])}(tc),ic="Image I-Frame player does not accept HTMLMediaElements",nc={seekOnAppend:!0},ac=function(e){function t(e,r){var i;return s(this,t),(i=a(this,t,["iframes",e.logger])).hls=void 0,i.stats=void 0,i.variableList=null,i.initPTS=[],i.iframeInstances=void 0,i.instanceCounter=0,Xu||(Xu=function(e){function t(e,r,i,n){var o;return s(this,t),e.streamController||(e.streamController=tc),(o=a(this,t,[e]))._url=r,o.streamController.setInitPts(i),o.streamController.initDetails=n,o}return f(t,e),l(t,[{key:"loadSource",value:function(){}},{key:"loadMediaAt",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:nc;if(!(e<0)){var r=Ie(Ie({},nc),t);this.loadingEnabled||this.startLoad(e),this.streamController.loadMediaAt(e,r)}}}])}(r)),Qu||(Qu=function(e){return function(e){function t(e,r,i,n){return s(this,t),e.cmcdController=void 0,e.emeController=void 0,e.streamController||(e.streamController=rc),e.capLevelController=void 0,e.bufferController=void 0,a(this,t,[e,r,i,n])}return f(t,e),l(t,[{key:"attachImage",value:function(e){this.streamController.image=e}},{key:"detachImage",value:function(){this.streamController.image=void 0}},{key:"loadSource",value:function(){}},{key:"attachMedia",value:function(){throw new Error(ic)}},{key:"detachMedia",value:function(){}},{key:"recoverMediaError",value:function(){}},{key:"transferMedia",value:function(){return null}},{key:"loadMediaAt",value:function(e){if(e<0)return null;this.loadingEnabled||this.startLoad(e),this.streamController.loadMediaAt(e)}}])}(e)}(Xu)),i.hls=e,i.iframeInstances=[],i.registerListeners(),i}return f(t,e),l(t,[{key:"registerListeners",value:function(){var e=this.hls;e&&(e.on(ne.MANIFEST_LOADING,this.clearAsset,this),e.on(ne.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(ne.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(ne.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(ne.FRAG_BUFFERED,this.onFragBuffered,this),e.on(ne.DESTROYING,this.onDestroying,this))}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ne.MANIFEST_LOADING,this.clearAsset,this),e.off(ne.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(ne.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(ne.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(ne.FRAG_BUFFERED,this.onFragBuffered,this),e.off(ne.DESTROYING,this.onDestroying,this))}},{key:"clearAsset",value:function(){this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances.forEach(function(e){return e.destroy()}),this.iframeInstances.length=0}},{key:"onDestroying",value:function(){this.unregisterListeners(),this.clearAsset(),this.hls=void 0}},{key:"onManifestLoaded",value:function(e,t){this.stats=t.stats,this.variableList=t.variableList}},{key:"onLevelsUpdated",value:function(e,t){var r,i=t.levels,n=null==(r=this.hls)?void 0:r.pathwayPriority;i.length&&n&&this.iframeInstances.forEach(function(e){e.pathwayPriority=n})}},{key:"onInitPtsFound",value:function(e,t){var r=t.id,i=t.timestampOffsets;r===de.MAIN&&(this.initPTS=i)}},{key:"onFragBuffered",value:function(e,t){var r,i=this,n=this.hls;n&&n.hasEnoughToStart&&((null==(r=n.mainForwardBufferInfo)?void 0:r.len)||0)>10&&this.iframeInstances.forEach(function(e){var t;e.loadingEnabled||e.startLoad((null==(t=i.hls)||null==(t=t.media)?void 0:t.currentTime)||0)})}},{key:"createIFramePlayer",value:function(e){var t;return this.createInstance(Xu,null==(t=this.hls)?void 0:t.iframeVariants,e)}},{key:"createImageIFramePlayer",value:function(e){var t,r=null==(t=this.hls)?void 0:t.iframeVariants.filter(function(e){return e.imageCodec});return this.createInstance(Qu,r,e,"image-")}},{key:"createInstance",value:function(e,t,r,i){var n=this.hls;if(!n)return null;var a=n.url,s=n.userConfig,o=n.latestLevelDetails,l=n.loadLevelObj,u=n.loadLevel,c=n.bandwidthEstimate,d=n.sessionId,h=this.stats,f=this.variableList;if(null==t||!t.length||!h||!a)return null;var v="".concat(i||"","iframe-player-").concat(this.instanceCounter++),g=n.levels,p=l||g[u],m=Yr(p,s.videoPreference),y=(null==p?void 0:p.pathwayId)||".",k=new e(Ie(Ie({},s),{},{loggerId:v,primarySessionId:d,videoPreference:m,abrEwmaDefaultEstimate:c,streamController:void 0,audioStreamController:void 0,audioTrackController:void 0,subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,id3TrackController:void 0,fpsController:void 0,gapController:void 0,iframeController:void 0,cmcd:void 0,interstitialsController:void 0,backBufferLength:1/0,maxMaxBufferLength:1,capLevelToPlayerSize:!0,enableWorker:!1,autoStartLoad:!1,startFragPrefetch:!1,testBandwidth:!1,progressive:!1},r),a,this.initPTS,o);return this.iframeInstances=this.iframeInstances.filter(function(e){return!e.url}),this.iframeInstances.push(k),k.trigger(ne.MANIFEST_LOADED,{levels:t,contentSteering:{uri:"",pathwayId:y},sessionKeys:null,audioTracks:[],iframeVariants:[],sessionData:null,startTimeOffset:null,stats:h,networkDetails:null,url:a,variableList:f}),k}}])}(Be);var sc=.025,oc=function(e){return e[e.Point=0]="Point",e[e.Range=1]="Range",e}({});function lc(e,t,r){return"".concat(e.identifier,"-").concat(r+1,"-").concat(mu(t))}var uc=function(){return l(function e(t,r){s(this,e),this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=r,this.dateRange=t,this.setDateRange(t)},[{key:"setDateRange",value:function(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}},{key:"reset",value:function(){var e;this.appendInPlaceStarted=!1,null==(e=this.assetListLoader)||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}},{key:"isAssetPastPlayoutLimit",value:function(e){var t;if(e>0&&e>=this.assetList.length)return!0;var r=this.playoutLimit;return!(e<=0||isNaN(r))&&(0===r||((null==(t=this.assetList[e])?void 0:t.startOffset)||0)>r)}},{key:"findAssetIndex",value:function(e){return this.assetList.indexOf(e)}},{key:"identifier",get:function(){return this.dateRange.id}},{key:"startDate",get:function(){return this.dateRange.startDate}},{key:"startTime",get:function(){var e=this.dateRange.startTime;if(this.snapOptions.out){var t=this.dateRange.tagAnchor;if(t)return dc(t,e)?cc(e,t):e}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-cc(t,e)<.1}return!1}},{key:"resumptionOffset",get:function(){var e=this.resumeOffset,t=Z(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 dc(t,e)?cc(e,t):e}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)<sc))},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"]?oc.Range:oc.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 cc(e,t){return e-t.start<t.duration/2&&!(Math.abs(e-(t.start+t.duration))<sc)?t.start:t.start+t.duration}function dc(e,t){return t>e.start-sc&&t<e.start+e.duration+sc}function hc(e,t,r){var i=new self.URL(e,r);return"data:"!==i.protocol&&Rr(i,"_HLS_primary_id",t),i}function fc(e,t){for(;null!=(r=e.assetList[++t])&&r.error;)var r;return t}function vc(e){var t=e.timelineStart,r=e.duration||0;return'["'.concat(e.identifier,'" ').concat(t.toFixed(2),"-").concat((t+r).toFixed(2),"]")}var gc=function(){return l(function e(t,r,i,n){var a=this;s(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(){a.reachedPlayout(a.currentTime)&&a.hls&&a.hls.trigger(ne.PLAYOUT_LIMIT_REACHED,{})};var o=this.hls=new t(r);this.interstitial=i,this.assetItem=n;var l=function(){a.hasDetails=!0};o.once(ne.LEVEL_LOADED,l),o.once(ne.AUDIO_TRACK_LOADED,l),o.once(ne.SUBTITLE_TRACK_LOADED,l),o.on(ne.MEDIA_ATTACHING,function(e,t){var r=t.media;a.removeMediaListeners(),a.mediaAttached=r,a.interstitial.playoutLimit&&(r.addEventListener("timeupdate",a.checkPlayout),a.appendInPlace&&o.on(ne.BUFFER_APPENDED,function(){var e=a.bufferedEnd;a.reachedPlayout(e)&&(a._bufferedEosTime=e,o.trigger(ne.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=hc(t,e.config.primarySessionId||"").href}catch(e){}e.loadSource(t)}}},{key:"bufferedInPlaceToEnd",value:function(e,t){var r;if(!this.appendInPlace)return!1;if(null!=(r=this.hls)&&r.bufferedToEnd)return!0;if(!e)return!1;var i=Math.min(this._bufferedEosTime||1/0,this.duration),n=this.timelineOffset+(t||0),a=Bi.bufferInfo(e,n,.02);return this.getAssetTime(a.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=Bi.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}},{key:"currentTime",get:function(){var e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}},{key:"duration",get:function(){var e=this.assetItem.duration;if(!e)return 0;var t=this.interstitial.playoutLimit;if(t){var r=t-this.startOffset;if(r>0&&r<e)return r}return e}},{key:"remaining",get:function(){var e=this.duration;return e?Math.max(0,e-this.currentTime):0}},{key:"startOffset",get:function(){return this.assetItem.startOffset}},{key:"timelineOffset",get:function(){var e;return(null==(e=this.hls)?void 0:e.config.timelineOffset)||0},set:function(e){var t=this.timelineOffset;if(e!==t){var r=e-t;if(Math.abs(r)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}},{key:"getAssetTime",value:function(e){var t=this.timelineOffset,r=this.duration;return Math.min(Math.max(0,e-t),r)}},{key:"removeMediaListeners",value:function(){var e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}},{key:"bufferSnapShot",value:function(){var e;this.mediaAttached&&(null!=(e=this.hls)&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd))}},{key:"destroy",value:function(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}},{key:"attachMedia",value:function(e){var t;this.loadSource(),null==(t=this.hls)||t.attachMedia(e)}},{key:"detachMedia",value:function(){var e;this.removeMediaListeners(),this.mediaAttached=null,null==(e=this.hls)||e.detachMedia()}},{key:"resumeBuffering",value:function(){var e;null==(e=this.hls)||e.resumeBuffering()}},{key:"pauseBuffering",value:function(){var e;null==(e=this.hls)||e.pauseBuffering()}},{key:"transferMedia",value:function(){var e;return this.bufferSnapShot(),(null==(e=this.hls)?void 0:e.transferMedia())||null}},{key:"resetDetails",value:function(){var e=this.hls;if(e&&this.hasDetails){e.stopLoad();var t=function(e){return delete e.details};e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}},{key:"on",value:function(e,t,r){var i;null==(i=this.hls)||i.on(e,t)}},{key:"once",value:function(e,t,r){var i;null==(i=this.hls)||i.once(e,t)}},{key:"off",value:function(e,t,r){var i;null==(i=this.hls)||i.off(e,t)}},{key:"toString",value:function(){var e;return"HlsAssetPlayer: ".concat(vc(this.assetItem)," ").concat(null==(e=this.hls)?void 0:e.sessionId," ").concat(this.appendInPlace?"append-in-place":"")}}])}(),pc=.033,mc=function(e){function t(e,r){var i;return s(this,t),(i=a(this,t,["interstitials-sched",r])).onScheduleUpdate=void 0,i.eventMap={},i.events=null,i.items=null,i.durations={primary:0,playout:0,integrated:0},i.onScheduleUpdate=e,i}return f(t,e),l(t,[{key:"destroy",value:function(){this.reset(),this.onScheduleUpdate=null}},{key:"reset",value:function(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(function(e){return e.reset()}),this.events=this.items=null}},{key:"resetErrorsInRange",value:function(e,t){return this.events?this.events.reduce(function(r,i){return e<=i.startOffset&&t>i.startOffset?(delete i.error,r+1):r},0):0}},{key:"duration",get:function(){var e=this.items;return e?e[e.length-1].end:0}},{key:"length",get:function(){return this.items?this.items.length:0}},{key:"getEvent",value:function(e){return e&&this.eventMap[e]||null}},{key:"hasEvent",value:function(e){return e in this.eventMap}},{key:"findItemIndex",value:function(e,t){if(e.event)return this.findEventIndex(e.event.identifier);var r=-1;e.nextEvent?r=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(r=this.findEventIndex(e.previousEvent.identifier)+1);var i=this.items;if(i)for(i[r]||(void 0===t&&(t=e.start),r=this.findItemIndexAtTime(t));r>=0&&null!=(n=i[r])&&n.event;){var n;r--}return r}},{key:"findItemIndexAtTime",value:function(e,t){var r=this.items;if(r)for(var i=0;i<r.length;i++){var n=r[i];t&&"primary"!==t&&(n=n[t]);var a=n.start,s=r[i].event,o=null!=s&&s.cue.pre?s.duration:n.end;if(e===a||e>a&&e<o)return i}return-1}},{key:"findJumpRestrictedIndex",value:function(e,t){var r=this.items;if(r)for(var i=e;i<=t&&r[i];i++){var n=r[i].event;if(null!=n&&n.restrictions.jump&&!n.appendInPlace)return i}return-1}},{key:"findEventIndex",value:function(e){var t=this.items;if(t)for(var r=t.length;r--;){var i;if((null==(i=t[r].event)?void 0:i.identifier)===e)return r}return-1}},{key:"findAssetIndex",value:function(e,t){var r=e.assetList,i=r.length;if(i>1)for(var n=0;n<i;n++){var a=r[n];if(!a.error){var s=a.timelineStart;if(t===s||t>s&&(t<s+(a.duration||0)||n===i-1))return n}}return 0}},{key:"assetIdAtEnd",get:function(){var e,t=null==(e=this.items)||null==(e=e[this.length-1])?void 0:e.event;if(t){var r=t.assetList,i=r[r.length-1];if(i)return i.identifier}return null}},{key:"parseInterstitialDateRanges",value:function(e,t){var r=this,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,n=e.main.details,a=n.dateRanges,s=this.events,o=this.parseDateRanges(a,{url:n.url},t),l=Object.keys(a),u=s?s.filter(function(e){return-1===l.indexOf(e.identifier)}):[];o.length&&o.sort(function(e,t){var r=e.cue.pre,i=e.cue.post,n=t.cue.pre,a=t.cue.post;if(r&&!n)return-1;if(n&&!r)return 1;if(i&&!a)return 1;if(a&&!i)return-1;if(!(r||n||i||a)){var s=e.startTime,o=t.startTime;if(s!==o)return s-o}return e.dateRange.tagOrder-t.dateRange.tagOrder}),this.events=o,u.forEach(function(e){r.removeEvent(e)}),this.updateSchedule(e,u,i)}},{key:"updateSchedule",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,i=arguments.length>3&&void 0!==arguments[3]&&arguments[3],n=this.events||[];if(n.length||t.length||this.length<2){var a=this.items,s=this.parseSchedule(n,e,r);(i||t.length||(null==a?void 0:a.length)!==s.length||s.some(function(e,t){return Math.abs(e.playout.start-a[t].playout.start)>.005||Math.abs(e.playout.end-a[t].playout.end)>.005}))&&(this.items=s,this.onScheduleUpdate(t,a))}}},{key:"parseDateRanges",value:function(e,t,r){for(var i=[],n=Object.keys(e),a=0;a<n.length;a++){var s=n[a],o=e[s];if(o.isInterstitial){var l=this.eventMap[s];l?l.setDateRange(o):(l=new uc(o,t),this.eventMap[s]=l,!1===r&&(l.appendInPlace=r)),i.push(l)}}return i}},{key:"parseSchedule",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,i=[],n=t.main.details,a=n.live?1/0:n.edge,s=0;if((e=e.filter(function(e){return!(e.error||e.cue.once&&e.hasPlayed)})).length){this.resolveOffsets(e,t);var o=0,l=0;if(e.forEach(function(t,u){var c=t.cue.pre,d=t.cue.post,h=e[u-1]||null,f=t.appendInPlace,v=d?a:t.startOffset,g=t.duration,p=t.timelineOccupancy===oc.Range?g:0,m=c&&n.live?r+(t.resumeOffset||0):0,y=m||t.resumptionOffset,k=(null==h?void 0:h.startTime)===v,E=v+t.cumulativeDuration,S=f?E+g:v+y;if(c||!d&&v<=0){var T=l;l+=p,t.timelineStart=E;var A=s;s+=g,i.push({event:t,start:E,end:S,playout:{start:A,end:s},integrated:{start:T,end:l}})}else{if(!(v<=a))return;if(!k){var b=v-o;if(b>pc){var I=o,R=l;l+=b;var L=s;s+=b;var P={previousEvent:e[u-1]||null,nextEvent:t,start:I,end:I+b,playout:{start:L,end:s},integrated:{start:R,end:l}};i.push(P)}else b>0&&h&&(h.cumulativeDuration+=b,i[i.length-1].end=v)}d&&(S=E),t.timelineStart=E;var w=l;l+=p;var C=s;s+=g,i.push({event:t,start:E,end:S,playout:{start:C,end:s},integrated:{start:w,end:l}})}var D=m||t.resumeTime;o=d||D>a?a:!c&&S&&t.appendInPlaceStarted&&D-S>pc?S:D}),o<a){var u,c=o,d=l,h=a-o;l+=h;var f=s;s+=h,i.push({previousEvent:(null==(u=i[i.length-1])?void 0:u.event)||null,nextEvent:null,start:o,end:c+h,playout:{start:f,end:s},integrated:{start:d,end:l}})}this.setDurations(a,s,l)}else{i.push({previousEvent:null,nextEvent:null,start:0,end:a,playout:{start:0,end:a},integrated:{start:0,end:a}}),this.setDurations(a,a,a)}return i}},{key:"setDurations",value:function(e,t,r){this.durations={primary:e,playout:t,integrated:r}}},{key:"resolveOffsets",value:function(e,t){var r=this,i=t.main.details,n=i.live?1/0:i.edge,a=0,s=-1;e.forEach(function(o,l){var u=o.cue.pre,c=o.cue.post,d=u?0:c?n:o.startTime;(r.updateAssetDurations(o),s===d?o.cumulativeDuration=a:(a=0,s=d),!c&&o.snapOptions.in&&(o.resumeAnchor=Qr(null,i.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted)&&(r.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1));!o.appendInPlace&&l+1<e.length&&(e[l+1].startTime-e[l].resumeTime<pc&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&r.warn("Could not change append strategy for abutting event ".concat(o))));var h=Z(o.resumeOffset)?o.resumeOffset:o.duration;a+=h})}},{key:"primaryCanResumeInPlaceAt",value:function(e,t){var r=this,i=e.resumeTime,n=e.startTime+e.resumptionOffset;return Math.abs(i-n)>sc?(this.log('"'.concat(e.identifier,'" resumption ').concat(i," not aligned with estimated timeline end ").concat(n)),!1):!Object.keys(t).some(function(n){var a=t[n].details,s=a.edge;if(i>=s)return r.log('"'.concat(e.identifier,'" resumption ').concat(i," past ").concat(n," playlist end ").concat(s)),!1;var o=Qr(null,a.fragments,i);if(!o)return r.log('"'.concat(e.identifier,'" resumption ').concat(i," does not align with any fragments in ").concat(n," playlist (").concat(a.fragStart,"-").concat(a.fragmentEnd,")")),!0;var l="audio"===n?.175:0;return!(Math.abs(o.start-i)<sc+l||Math.abs(o.end-i)<sc+l)&&(r.log('"'.concat(e.identifier,'" resumption ').concat(i," not aligned with ").concat(n," fragment bounds (").concat(o.start,"-").concat(o.end," sn: ").concat(o.sn," cc: ").concat(o.cc,")")),!0)})}},{key:"updateAssetDurations",value:function(e){if(e.assetListLoaded){for(var t=e.timelineStart,r=0,i=!1,n=!1,a=0;a<e.assetList.length;a++){var s=e.assetList[a],o=t+r;s.startOffset=r,s.timelineStart=o,i||(i=null===s.duration),n||(n=!!s.error),r+=s.error?0:s.duration||0}e.duration=i&&!n?Math.max(r,e.duration):r}}},{key:"removeEvent",value:function(e){e.reset(),delete this.eventMap[e.identifier]}}])}(Be);function yc(e){return"[".concat(e.event?'"'+e.event.identifier+'"':"primary",": ").concat(e.start.toFixed(2),"-").concat(e.end.toFixed(2),"]")}var kc=function(){return l(function e(t){s(this,e),this.hls=void 0,this.hls=t},[{key:"destroy",value:function(){this.hls=null}},{key:"loadAssetList",value:function(e,t){var r,i=this,n=e.assetListUrl;try{r=hc(n,this.hls.sessionId,e.baseUrl)}catch(t){var a=this.assignAssetListError(e,ie.ASSET_LIST_LOAD_ERROR,t,n);return void this.hls.trigger(ne.ERROR,a)}t&&"data:"!==r.protocol&&Rr(r,"_HLS_start_offset",""+t);var s=this.hls.config,o=new(0,s.loader)(s),l={type:ce.INTERSTITIAL_ASSET_LIST,responseType:"json",url:r.href},u=s.interstitialAssetListLoadPolicy.default,c={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:function(t,r,n,a){var s=t.data,o=null==s?void 0:s.ASSETS;if(Array.isArray(o))e.assetListResponse=s,i.hls.trigger(ne.ASSET_LIST_LOADED,{event:e,assetListResponse:s,networkDetails:a});else{var l=i.assignAssetListError(e,ie.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),n.url,r,a);i.hls.trigger(ne.ERROR,l)}},onError:function(t,r,n,a){var s=i.assignAssetListError(e,ie.ASSET_LIST_LOAD_ERROR,new Error("Error loading X-ASSET-LIST: HTTP status ".concat(t.code," ").concat(t.text," (").concat(r.url,")")),r.url,a,n);i.hls.trigger(ne.ERROR,s)},onTimeout:function(t,r,n){var a=i.assignAssetListError(e,ie.ASSET_LIST_LOAD_TIMEOUT,new Error("Timeout loading X-ASSET-LIST (".concat(r.url,")")),r.url,t,n);i.hls.trigger(ne.ERROR,a)}};return o.load(l,c,d),this.hls.trigger(ne.ASSET_LIST_LOADING,{event:e}),o}},{key:"assignAssetListError",value:function(e,t,r,i,n,a){return e.error=r,{type:re.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:i,error:r,networkDetails:a,stats:n}}}])}();function Ec(e){var t;null==e||null==(t=e.play())||t.catch(function(){})}function Sc(e,t){return"[".concat(e,"] Advancing timeline position to ").concat(t)}var Tc=function(e){function t(e,r){var i;return s(this,t),(i=a(this,t,["interstitials",e.logger])).HlsPlayerClass=void 0,i.hls=void 0,i.assetListLoader=void 0,i.mediaSelection=null,i.altSelection=null,i.media=null,i.detachedData=null,i.requiredTracks=null,i.manager=null,i.playerQueue=[],i.bufferedPos=-1,i.timelinePos=-1,i.schedule=void 0,i.playingItem=null,i.bufferingItem=null,i.waitingItem=null,i.endedItem=null,i.playingAsset=null,i.endedAsset=null,i.bufferingAsset=null,i.bufferPastEdge=!1,i.shouldPlay=!1,i.onPlay=function(){i.shouldPlay=!0},i.onPause=function(){i.shouldPlay=!1},i.onSeeking=function(){var e=i.currentTime;if(void 0!==e&&!i.playbackDisabled&&i.schedule){var t=e-i.timelinePos;if(!(Math.abs(t)<1/7056e5)){var r=t<=-.01;-1!==i.timelinePos||i.effectivePlayingItem||i.checkStart(),i.timelinePos=e,i.bufferedPos=e;var n=i.playingItem;if(n){if(r)i.schedule.resetErrorsInRange(e,e-t)&&i.updateSchedule(!0);if(i.checkBuffer(),r&&e<n.start||e>=n.end){var a,s=i.findItemIndex(n),o=i.schedule.findItemIndexAtTime(e);if(-1===o&&(o=s+(r?-1:1),i.log("seeked ".concat(r?"back ":"","to position not covered by schedule ").concat(e," (resolving from ").concat(s," to ").concat(o,")"))),!i.isInterstitial(n)&&null!=(a=i.media)&&a.paused&&(i.shouldPlay=!1),!r&&o>s){var l=i.schedule.findJumpRestrictedIndex(s+1,o);if(l>s)return void i.setSchedulePosition(l)}i.setSchedulePosition(o)}else{var u=i.playingAsset;if(u){var c,d=u.timelineStart,h=u.duration||0;if(r&&e<d||e>=d+h)null!=(c=n.event)&&c.appendInPlace&&(i.clearAssetPlayers(n.event,n),i.flushFrontBuffer(e)),i.setScheduleToAssetAtTime(e,u)}else if(i.playingLastItem&&i.isInterstitial(n)){var f=n.event.assetList[0];f&&(i.endedItem=i.playingItem,i.playingItem=null,i.setScheduleToAssetAtTime(e,f))}}}else i.checkBuffer()}}},i.onTimeupdate=function(){var e=i.currentTime;if(void 0!==e&&!i.playbackDisabled&&(-1!==i.timelinePos||i.effectivePlayingItem||i.checkStart(),e>i.timelinePos)){i.timelinePos=e,e>i.bufferedPos&&i.checkBuffer();var t=i.playingItem;if(t&&!i.playingLastItem){if(e>=t.end){i.timelinePos=t.end;var r=i.findItemIndex(t);i.setSchedulePosition(r+1)}var n=i.playingAsset;if(n)e>=n.timelineStart+(n.duration||0)&&i.setScheduleToAssetAtTime(e,n)}}},i.onScheduleUpdate=function(e,t){var r=i.schedule;if(r){var n=i.playingItem,a=r.events||[],s=r.items||[],o=r.durations,l=e.map(function(e){return e.identifier}),u=!(!a.length&&!l.length);(u||t)&&i.log("INTERSTITIALS_UPDATED (".concat(a.length,"): ").concat(a,"\nSchedule: ").concat(s.map(function(e){return yc(e)})," pos: ").concat(i.timelinePos)),l.length&&i.log("Removed events ".concat(l));var c=null,d=null;n&&(c=i.updateItem(n,i.timelinePos),i.itemsMatch(n,c)?i.playingItem=c:i.waitingItem=null),i.waitingItem=i.updateItem(i.waitingItem);var h=i.bufferingItem;if(h&&(d=i.updateItem(h,i.bufferedPos),i.itemsMatch(h,d)?i.bufferingItem=d:h.event&&(i.bufferingItem=i.playingItem,i.clearInterstitial(h.event,null))),e.forEach(function(e){e.assetList.forEach(function(e){i.clearAssetPlayer(e.identifier,null)})}),i.playerQueue.forEach(function(e){if(e.interstitial.appendInPlace){var t=e.assetItem.timelineStart,r=e.timelineOffset-t;if(r)try{e.timelineOffset=t}catch(n){Math.abs(r)>sc&&i.warn("".concat(n,' ("').concat(e.assetId,'" ').concat(e.timelineOffset,"->").concat(t,")"))}}}),u||t){if(i.hls.trigger(ne.INTERSTITIALS_UPDATED,{events:a.slice(0),schedule:s.slice(0),durations:o,removedIds:l}),i.isInterstitial(n)&&l.indexOf(n.event.identifier)>-1)return i.warn('Interstitial "'.concat(n.event.identifier,'" removed while playing')),void i.primaryFallback(n.event);n&&i.trimInPlace(c,n),h&&d!==c&&i.trimInPlace(d,h),i.checkBuffer()}}},i.hls=e,i.HlsPlayerClass=r,i.assetListLoader=new kc(e),i.schedule=new mc(i.onScheduleUpdate,e.logger),i.registerListeners(),i}return f(t,e),l(t,[{key:"registerListeners",value:function(){var e=this.hls;e&&(e.on(ne.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(ne.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ne.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ne.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(ne.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(ne.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(ne.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(ne.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(ne.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(ne.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(ne.BUFFER_APPENDED,this.onBufferAppended,this),e.on(ne.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(ne.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(ne.MEDIA_ENDED,this.onMediaEnded,this),e.on(ne.ERROR,this.onError,this),e.on(ne.DESTROYING,this.onDestroying,this))}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ne.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(ne.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ne.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ne.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(ne.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(ne.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(ne.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(ne.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(ne.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(ne.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(ne.BUFFER_CODECS,this.onBufferCodecs,this),e.off(ne.BUFFER_APPENDED,this.onBufferAppended,this),e.off(ne.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(ne.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(ne.MEDIA_ENDED,this.onMediaEnded,this),e.off(ne.ERROR,this.onError,this),e.off(ne.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=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){ra(e,"play",this.onPlay),ra(e,"pause",this.onPause),ra(e,"seeking",this.onSeeking),ra(e,"timeupdate",this.onTimeupdate)}},{key:"onMediaAttaching",value:function(e,t){var r=this.media=t.media;ta(r,"seeking",this.onSeeking),ta(r,"timeupdate",this.onTimeupdate),ta(r,"play",this.onPlay),ta(r,"pause",this.onPause)}},{key:"onMediaAttached",value:function(e,t){var r=this.effectivePlayingItem,i=this.detachedData;if(this.detachedData=null,null===r)this.checkStart();else if(!i){this.clearScheduleState();var n=this.findItemIndex(r);this.setSchedulePosition(n)}}},{key:"clearScheduleState",value:function(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}},{key:"onMediaDetaching",value:function(e,t){var r=!!t.transferMedia,i=this.media;if(this.media=null,!r&&(i&&this.removeMediaListeners(i),this.detachedData)){var n=this.getBufferingPlayer();n&&(this.log("Removing schedule state for detachedData and ".concat(n)),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,n.detachMedia()),this.shouldPlay=!1}}},{key:"interstitialsManager",get:function(){if(!this.hls)return null;if(this.manager)return this.manager;var e=this,t=function(){return e.bufferingItem||e.waitingItem},r=function(t){return t?e.getAssetPlayer(t.identifier):t},i=function(t,i,a,s,o){if(t){var l=t[i].start,u=t.event;if(u){if("playout"===i||u.timelineOccupancy!==oc.Point){var c=r(a);(null==c?void 0:c.interstitial)===u&&(l+=c.assetItem.startOffset+c[o])}}else l+=("bufferedPos"===s?n():e[s])-t.start;return l}return 0},n=function(){var t=e.bufferedPos;return t===Number.MAX_VALUE?a("primary"):Math.max(t,0)},a=function(t){var r,i;return null!=(r=e.primaryDetails)&&r.live?e.primaryDetails.edge:(null==(i=e.schedule)?void 0:i.durations[t])||0},s=function(t,n){var a,s,o=e.effectivePlayingItem;if((null==o||null==(a=o.event)||!a.restrictions.skip)&&e.schedule){e.log("seek to ".concat(t,' "').concat(n,'"'));var l=e.effectivePlayingItem,u=e.schedule.findItemIndexAtTime(t,n),c=null==(s=e.schedule.items)?void 0:s[u],d=e.getBufferingPlayer(),h=null==d?void 0:d.interstitial,f=null==h?void 0:h.appendInPlace,v=l&&e.itemsMatch(l,c);if(l&&(f||v)){var g=r(e.playingAsset),p=(null==g?void 0:g.media)||e.primaryMedia;if(p){var m="primary"===n?p.currentTime:i(l,n,e.playingAsset,"timelinePos","currentTime"),y=t-m,k=(f?m:p.currentTime)+y;if(k>=0&&(!g||f||k<=g.duration))return void(p.currentTime=k)}}if(c){var E=t;if("primary"!==n){var S=t-c[n].start;E=c.start+S}var T=!e.isInterstitial(c);if(e.isInterstitial(l)&&!l.event.appendInPlace||!T&&!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 I=0;if(T)e.timelinePos=E,e.checkBuffer();else for(var R=c.event.assetList,L=t-(c[n]||c).start,P=R.length;P--;){var w=R[P];if(w.duration&&L>=w.startOffset&&L<w.startOffset+w.duration){I=P;break}}e.setSchedulePosition(u,I)}}else{var C=e.media||(f?null==d?void 0:d.media:null);C&&(C.currentTime=E)}}}},o=function(){var r=e.effectivePlayingItem;if(e.isInterstitial(r))return r;var i=t();return e.isInterstitial(i)?i:null},l={get bufferedEnd(){var r,n=t(),a=e.bufferingItem;return a&&a===n&&(i(a,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-a.playout.start||(null==(r=e.bufferingAsset)?void 0:r.startOffset))||0},get currentTime(){var t=o(),r=e.effectivePlayingItem;return r&&r===t?i(r,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-r.playout.start:0},set currentTime(t){var r=o(),i=e.effectivePlayingItem;i&&i===r&&s(t+i.playout.start,"playout")},get duration(){var e=o();return e?e.playout.end-e.playout.start:0},get assetPlayers(){var t,r=null==(t=o())?void 0:t.event.assetList;return r?r.map(function(t){return e.getAssetPlayer(t.identifier)}):[]},get playingIndex(){var t,r=null==(t=o())?void 0:t.event;return r&&e.effectivePlayingAsset?r.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return o()}};return this.manager={get events(){var t;return(null==(t=e.schedule)||null==(t=t.events)?void 0:t.slice(0))||[]},get schedule(){var t;return(null==(t=e.schedule)||null==(t=t.items)?void 0:t.slice(0))||[]},get interstitialPlayer(){return o()?l:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){var r=t();return e.findItemIndex(r)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){var t=e.effectivePlayingItem;return e.findItemIndex(t)},primary:{get bufferedEnd(){return n()},get currentTime(){var t=e.timelinePos;return t>0?t:0},set currentTime(e){s(e,"primary")},get duration(){return a("primary")},get seekableStart(){return e.seekableStart}},integrated:{get bufferedEnd(){return i(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(e){s(e,"integrated")},get duration(){return a("integrated")},get seekableStart(){return function(t,r){var i;if(0!==t&&"primary"!==r&&null!=(i=e.schedule)&&i.length){var n,a=e.schedule.findItemIndexAtTime(t),s=null==(n=e.schedule.items)?void 0:n[a];if(s)return t+(s[r].start-s.start)}return t}(e.seekableStart,"integrated")}},skip:function(){var t=e.effectivePlayingItem,r=null==t?void 0:t.event;if(r&&!r.restrictions.skip){var i=e.findItemIndex(t);if(r.appendInPlace){var n=t.playout.start+t.event.duration;s(n+.001,"playout")}else e.advanceAfterAssetEnded(r,i,1/0)}}}}},{key:"effectivePlayingItem",get:function(){return this.waitingItem||this.playingItem||this.endedItem}},{key:"effectivePlayingAsset",get:function(){return this.playingAsset||this.endedAsset}},{key:"playingLastItem",get:function(){var e,t=this.playingItem,r=null==(e=this.schedule)?void 0:e.items;return!!(this.playbackStarted&&t&&r)&&this.findItemIndex(t)===r.length-1}},{key:"playbackStarted",get:function(){return null!==this.effectivePlayingItem}},{key:"currentTime",get:function(){var e,t;if(null!==this.mediaSelection){var r=this.waitingItem||this.playingItem;if(!this.isInterstitial(r)||r.event.appendInPlace){var i=this.media;!i&&null!=(e=this.bufferingItem)&&null!=(e=e.event)&&e.appendInPlace&&(i=this.primaryMedia);var n=null==(t=i)?void 0:t.currentTime;if(void 0!==n&&Z(n))return n}}}},{key:"primaryMedia",get:function(){var e;return this.media||(null==(e=this.detachedData)?void 0:e.media)||null}},{key:"isInterstitial",value:function(e){return!(null==e||!e.event)}},{key:"retreiveMediaSource",value:function(e,t){var r=this.getAssetPlayer(e);r&&this.transferMediaFromPlayer(r,t)}},{key:"transferMediaFromPlayer",value:function(e,t){var r=e.interstitial.appendInPlace,i=e.media;if(r&&i===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&i)return void(this.detachedData={media:i});var n=e.transferMedia();this.log("transfer MediaSource from ".concat(e," ").concat(Nr(n))),this.detachedData=n}else t&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))}},{key:"transferMediaTo",value:function(e,t){var r,i,n=this;if(e.media!==t){var a,s=null,o=this.hls,l=e!==o,u=l&&e.interstitial.appendInPlace,c=null==(r=this.detachedData)?void 0:r.mediaSource;if(o.media)u&&(s=o.transferMedia(),this.detachedData=s),a="Primary";else{var d=this.getBufferingPlayer();d?(s=d.transferMedia(),this.detachedData=s,a="".concat(d)):a=c?"detached MediaSource":"detached media"}if(!s)if(c)s=this.detachedData,this.log("using detachedData: MediaSource ".concat(Nr(s)));else if(!this.detachedData||o.media===t){var h=this.playerQueue;h.length>1&&h.forEach(function(e){if(l&&e.interstitial.appendInPlace!==u){var t=e.interstitial;n.clearInterstitial(e.interstitial,null),t.appendInPlace=!1,t.appendInPlace&&n.warn("Could not change append strategy for queued assets ".concat(t))}}),this.hls.detachMedia(),this.detachedData={media:t}}var f=s&&"mediaSource"in s&&"closed"!==(null==(i=s.mediaSource)?void 0:i.readyState);if(this.log("".concat(f?"transfering MediaSource":"attaching media"," to ").concat(l?e:"Primary"," from ").concat(a," (media.currentTime: ").concat(t.currentTime,")")),f||l){var v=f&&s?Ie({},s):{media:t},g=this.schedule;if(g&&l){var p=e.assetId===g.assetIdAtEnd;v.overrides={duration:g.duration,endOfStream:p||!1===e.appendInPlace}}if(!f&&u){var m=e,y=m.assetItem.timelineStart;if(y){var k=m.hls,E=Math.max(this.timelinePos-y,Number.EPSILON);k.startPosition!==E&&(this.log("Set ".concat(m," startPosition: ").concat(E)),k.config.startPosition=E,k.loadingEnabled&&k.startLoad(E))}}e.attachMedia(v)}else e.attachMedia(t)}}},{key:"onInterstitialCueEnter",value:function(){this.onTimeupdate()}},{key:"checkStart",value:function(){var e=this.schedule,t=null==e?void 0:e.events,r=this.hls;if(t&&!this.playbackDisabled&&this.media&&r){-1===this.bufferedPos&&(this.bufferedPos=0);var i=this.timelinePos,n=this.effectivePlayingItem;if(-1===i){if(!r.loadingEnabled)return void this.log("waiting for startLoad( <startPosition> )");var a=r.startPosition;if(this.timelinePos=a,0===t.length)this.setSchedulePosition(0);else if(t[0].cue.pre){this.log(Sc("checkStart (preroll)",a));var s=e.findEventIndex(t[0].identifier);this.setSchedulePosition(s)}else if(a>=0||!this.primaryLive){this.log(Sc("checkStart",a));var o=this.timelinePos=a>0?a:0,l=e.findItemIndexAtTime(o);this.setSchedulePosition(l)}else 0===r.liveSyncPosition?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(n&&!this.playingItem){this.log(Sc("checkStart (playing item)",n.start));var u=e.findItemIndex(n);this.setSchedulePosition(u)}}}},{key:"advanceAssetBuffering",value:function(e,t){var r=e.event,i=r.findAssetIndex(t),n=fc(r,i);if(r.isAssetPastPlayoutLimit(n)){if(this.schedule){var a,s=this.getNextItemIndex(e,!0),o=null==(a=this.schedule.items)?void 0:a[s];o&&this.bufferedToItem(o)}}else this.bufferedToEvent(e,n)}},{key:"livePrerollResumption",value:function(e,t){if(e.cue.pre&&this.primaryLive&&!Z(e.resumeOffset)&&this.hls){var r=this.getLiveStartPos();if(t){var i=this.getBufferingPlayer();return r+(null!=i&&i.interstitial.cue.pre?i.remaining:0)}return r}}},{key:"getNextItemIndex",value:function(e,t){if(this.schedule){var r=this.livePrerollResumption(e.event,t);if(void 0!==r)return this.log("find next item index @".concat(r)),this.schedule.findItemIndexAtTime(r)}return this.findItemIndex(e)+1}},{key:"advanceAfterAssetEnded",value:function(e,t,r){var i=fc(e,r);if(e.isAssetPastPlayoutLimit(i)){if(this.schedule){var n=this.schedule.items;if(n){var a=n[t],s=a.event?this.getNextItemIndex(a):t+1;if(s>=n.length)return void this.setSchedulePosition(-1);var o=e.resumeTime;this.timelinePos<o&&(this.log(Sc("advanceAfterAssetEnded",o)),this.timelinePos=o,e.appendInPlace&&!n[s].event&&this.hls.startLoad(o+.01),this.checkBuffer(this.bufferedPos<o)),this.setSchedulePosition(s)}}}else{if(e.appendInPlace){var l=e.assetList[i];l&&this.advanceInPlace(l.timelineStart)}this.setSchedulePosition(t,i)}}},{key:"setScheduleToAssetAtTime",value:function(e,t){var r=this.schedule;if(r){var i=t.parentIdentifier,n=r.getEvent(i);if(n){var a=r.findEventIndex(i),s=r.findAssetIndex(n,e);this.advanceAfterAssetEnded(n,a,s-1)}}}},{key:"setSchedulePosition",value:function(e,t){var r,i=null==(r=this.schedule)?void 0:r.items;if(i&&!this.playbackDisabled){var n=e>=0?i[e]:null;this.log("setSchedulePosition ".concat(e,", ").concat(t," (").concat(n?yc(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(vc(l))),this.endedAsset=l,this.playingAsset=null,this.hls.trigger(ne.INTERSTITIAL_ASSET_ENDED,{asset:l,assetListIndex:h,event:o,schedule:i.slice(0),scheduleIndex:e,player:c}),a!==this.playingItem)return void(this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(o,this.findItemIndex(this.playingItem),h));this.retreiveMediaSource(u,n),!c.media||null!=(d=this.detachedData)&&d.mediaSource||c.detachMedia()}if(!this.eventItemsMatch(a,n)&&(this.endedItem=a,this.playingItem=this.waitingItem=null,this.log("INTERSTITIAL_ENDED ".concat(o," ").concat(yc(a))),o.hasPlayed=!0,this.hls.trigger(ne.INTERSTITIAL_ENDED,{event:o,schedule:i.slice(0),scheduleIndex:e}),o.cue.once&&this.hls)){var f;this.updateSchedule();var v=null==(f=this.schedule)?void 0:f.items;if(n&&v){var g=this.findItemIndex(n),p=this.livePrerollResumption(o);if(void 0!==p){var m=p,y=this.getNextItemIndex(a);if(!this.isInterstitial(i[y])){var k,E=null==(k=this.primaryDetails)?void 0:k.fragments;if(o.snapOptions.in&&E){var S=Qr(null,E,p);S&&(m=Math.min(Math.max(i[y].start,cc(m,S)),i[y].end))}}if(this.log(Sc("live join (preroll)",m)),this.timelinePos=m,y!==g&&(y||0===y))return void this.advanceSchedule(y,v,void 0,a,s)}this.advanceSchedule(g,v,t,a,s)}return}}this.advanceSchedule(e,i,t,a,s)}}},{key:"advanceSchedule",value:function(e,t,r,i,n){var a=this,s=this.schedule;if(s){var o=t[e]||null,l=this.primaryMedia,u=this.playerQueue;if(u.length&&u.forEach(function(t){var r=t.interstitial,i=s.findEventIndex(r.identifier);(i<e||i>e+1)&&a.clearInterstitial(r,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);var c=o.event;if(void 0===r){var d=fc(c,(r=c.cue.pre?0:s.findAssetIndex(c,this.timelinePos))-1);if(c.isAssetPastPlayoutLimit(d)||c.appendInPlace&&this.timelinePos===o.end)return void this.advanceAfterAssetEnded(c,e,r);r=d}var h=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);var f=this.preloadAssets(c,r);if(this.eventItemsMatch(o,h||i)||(this.waitingItem=o,this.log("INTERSTITIAL_STARTED ".concat(yc(o)," ").concat(c.appendInPlace?"append in place":"")),c.hasPlayed=!1,this.hls.trigger(ne.INTERSTITIAL_STARTED,{event:c,schedule:t.slice(0),scheduleIndex:e})),!c.assetListLoaded)return void this.log("Waiting for ASSET-LIST to complete loading ".concat(c));if(c.assetListLoader&&(c.assetListLoader.destroy(),c.assetListLoader=void 0),!l)return void this.log("Waiting for attachMedia to start Interstitial ".concat(c));this.waitingItem=this.endedItem=null,this.playingItem=o;var v=c.assetList[r];if(!v)return void this.advanceAfterAssetEnded(c,e,r||0);if(f||(f=this.getAssetPlayer(v.identifier)),null===f||f.destroyed){var g=c.assetList.length;this.warn("asset ".concat(r+1,"/").concat(g," player destroyed ").concat(c)),(f=this.createAssetPlayer(c,v,r)).loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&c.appendInPlace&&this.isAssetBuffered(v))return;this.startAssetPlayer(f,r,t,e,l),this.shouldPlay&&Ec(f.media)}else o?(this.resumePrimary(o,e,i),this.shouldPlay&&Ec(this.hls.media)):n&&this.isInterstitial(i)&&(this.endedItem=null,this.playingItem=i,i.event.appendInPlace||this.attachPrimary(s.durations.primary,null))}}},{key:"playbackDisabled",get:function(){return!1===this.hls.config.enableInterstitialPlayback}},{key:"primaryDetails",get:function(){var e;return null==(e=this.mediaSelection)?void 0:e.main.details}},{key:"primaryLive",get:function(){var e;return!(null==(e=this.primaryDetails)||!e.live)}},{key:"resumePrimary",value:function(e,t,r){var i,n;this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=null,this.bufferedToItem(e),this.endedItem=null,this.log("resuming ".concat(yc(e)));var a=this.timelinePos;if(null!=(i=this.detachedData)&&i.mediaSource?this.primaryLive&&this.startLoadingPrimaryAt(a):((a<e.start||a>=e.end||a<this.seekableStart)&&(a=this.getPrimaryResumption(e,t),this.log(Sc("resumePrimary",a)),this.timelinePos=a),this.attachPrimary(a,e)),r){var s=null==(n=this.schedule)?void 0:n.items;s&&(this.log("INTERSTITIALS_PRIMARY_RESUMED ".concat(yc(e))),this.hls.trigger(ne.INTERSTITIALS_PRIMARY_RESUMED,{schedule:s.slice(0),scheduleIndex:t}),this.checkBuffer())}}},{key:"seekableStart",get:function(){var e;return this.primaryLive&&(null==(e=this.primaryDetails)?void 0:e.fragmentStart)||0}},{key:"getPrimaryResumption",value:function(e,t,r){var i=e.start;if(this.primaryLive){if(0===t)return this.hls.startPosition;var n=this.endedItem||this.playingItem,a=null!=n&&n.event?this.livePrerollResumption(n.event,r):void 0;if(void 0!==a)return a;var s=this.primaryDetails;if(s){var o=s.fragmentStart,l=s.edge;if(i<o||i>l&&!r){var u=this.hls.liveSyncPosition;return this.log("primary resumption out of bounds (".concat(i," [").concat(o,"-").concat(l,"]) snapping to liveSync ").concat(u)),u||o}}}return this.log("primary resumption itemStart: ".concat(i)),i}},{key:"getLiveStartPos",value:function(){var e,t=this.hls.startPosition,r=this.hls.liveSyncPosition||0,i=3*((null==(e=this.primaryDetails)?void 0:e.targetduration)||10);return-1===t||r&&r-t<i?r||0:t}},{key:"isAssetBuffered",value:function(e){var t=this.getAssetPlayer(e.identifier);return null!=t&&t.hls?t.hls.bufferedToEnd:Bi.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}},{key:"attachPrimary",value:function(e,t,r){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;var i=this.primaryMedia;if(i){var n=this.hls;n.media?this.checkBuffer():(this.transferMediaTo(n,i),r&&this.startLoadingPrimaryAt(e,r)),r||(this.log(Sc("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,r))}}},{key:"startLoadingPrimaryAt",value:function(e,t){var r=this.hls,i=r.loadingEnabled,n=r.bufferingEnabled,a=r.startPosition,s=r.hasEnoughToStart;if(this.log("Start loading primary @".concat(e," bufferedPos: ").concat(this.bufferedPos," startPosition: ").concat(a," skip seek: ").concat(t," has enough ").concat(s," loadingEnabled: ").concat(i," bufferingEnabled: ").concat(n)),!t&&s||!i||Math.abs(a-e)>.1){var o=this.primaryDetails;if(null!=o&&o.live&&e+.5>=o.edge){var l=this.bufferingItem;return this.log("Resume primary loading when live passes ".concat(e," buffering item: ").concat(l?yc(l):null)),r.pauseBuffering(),void(this.bufferPastEdge=!0)}r.startLoad(e,t)}else n||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(ne.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(ne.BUFFER_CODECS,this.onBufferCodecs,this)}},{key:"onLevelUpdated",value:function(e,t){if(-1!==t.level&&this.schedule){var r=this.hls.levels[t.level];if(r.details){var i=Ie(Ie({},this.mediaSelection||this.altSelection),{},{main:r});this.mediaSelection=i;var n=this.hls.startPosition;if(this.schedule.parseInterstitialDateRanges(i,this.hls.config.interstitialAppendInPlace,-1===n?0:n),this.schedule.items)if(this.effectivePlayingItem){if(this.bufferPastEdge){var a=this.primaryDetails,s=this.bufferedPos;if(null!=a&&a.live&&s+.5<a.edge){this.bufferPastEdge=!1;var o=this.bufferingItem;if(this.log("Live edge ".concat(a.edge," passed buffer: ").concat(s," buffering item: ").concat(o?yc(o):null)),(null==o?void 0:o.end)===1/0){var l=this.playingItem,u=this.isInterstitial(l)&&l.event.appendInPlace;this.hls.startLoad(Math.max(s,o.start),u)}else{var c=this.getBufferingPlayer();if(c)c.bufferedInPlaceToEnd(this.primaryMedia,c.currentTime)&&c.hls&&c.hls.trigger(ne.BUFFERED_TO_END,void 0)}}}}else this.checkStart()}}}},{key:"onAudioTrackUpdated",value:function(e,t){var r=this.hls.audioTracks[t.id],i=this.mediaSelection;if(i){var n=Ie(Ie({},i),{},{audio:r});this.mediaSelection=n}else this.altSelection=Ie(Ie({},this.altSelection),{},{audio:r})}},{key:"onSubtitleTrackUpdated",value:function(e,t){var r=this.hls.subtitleTracks[t.id],i=this.mediaSelection;if(i){var n=Ie(Ie({},i),{},{subtitles:r});this.mediaSelection=n}else this.altSelection=Ie(Ie({},this.altSelection),{},{subtitles:r})}},{key:"onAudioTrackSwitching",value:function(e,t){var r=Vr(t);this.playerQueue.forEach(function(e){var i=e.hls;return i&&(i.setAudioOption(t)||i.setAudioOption(r))})}},{key:"onSubtitleTrackSwitch",value:function(e,t){var r=Vr(t);this.playerQueue.forEach(function(e){var i=e.hls;return i&&(i.setSubtitleOption(t)||-1!==t.id&&i.setSubtitleOption(r))})}},{key:"onBufferCodecs",value:function(e,t){var r=t.tracks;r&&(this.requiredTracks=r)}},{key:"onBufferAppended",value:function(e,t){this.checkBuffer()}},{key:"onBufferFlushed",value:function(e,t){var r=this.playingItem;if(r&&!this.itemsMatch(r,this.bufferingItem)&&!this.isInterstitial(r)){var i=this.timelinePos;this.bufferedPos=i,this.checkBuffer()}}},{key:"onBufferedToEnd",value:function(e){if(this.schedule){var t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(var r=0;r<t.length;r++){var i=t[r];if(i.cue.post){var n=this.getEventItem(i.identifier);n&&this.eventItemsMatch(n,this.bufferingItem)&&this.bufferedToItem(n,0);break}}this.bufferedPos=Number.MAX_VALUE}}}},{key:"onMediaEnded",value:function(e){var t=this.playingItem;if(!this.playingLastItem&&t){var r=this.findItemIndex(t);this.setSchedulePosition(r+1)}else this.shouldPlay=!1}},{key:"updateItem",value:function(e,t){var r,i=null==(r=this.schedule)?void 0:r.items;return e&&i&&i[this.findItemIndex(e,t)]||null}},{key:"trimInPlace",value:function(e,t){var r=this;if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach(function(t,i){e.event.isAssetPastPlayoutLimit(i)&&r.clearAssetPlayer(t.identifier,null)});var i=e.end+.25,n=Bi.bufferInfo(this.primaryMedia,i,0);if(n.end>i||(n.nextStart||0)>i){this.log("trim buffered interstitial ".concat(yc(e)," (was ").concat(yc(t),")"));this.attachPrimary(i,null,!0),this.flushFrontBuffer(i)}}}},{key:"itemsMatch",value:function(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}},{key:"eventItemsMatch",value:function(e,t){var r;return!!t&&(e===t||e.event.identifier===(null==(r=t.event)?void 0:r.identifier))}},{key:"findEventIndex",value:function(e){return this.schedule?this.schedule.findEventIndex(e):-1}},{key:"getEventItem",value:function(e){if(this.schedule){var t,r=null==(t=this.schedule.items)?void 0:t[this.findEventIndex(e)];if(this.isInterstitial(r)&&r.event.identifier===e)return r}}},{key:"findItemIndex",value:function(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}},{key:"updateSchedule",value:function(){var e,t,r=arguments.length>0&&void 0!==arguments[0]&&arguments[0],i=this.mediaSelection;if(i){var n=(null==(e=this.hls)?void 0:e.liveSyncPosition)||0;null==(t=this.schedule)||t.updateSchedule(i,[],n,r)}}},{key:"checkBuffer",value:function(e){var t,r=null==(t=this.schedule)?void 0:t.items;if(r){var i=Bi.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=i.len<1),this.updateBufferedPos(i.end,r,e)}}},{key:"updateBufferedPos",value:function(e,t,r){var i=this.schedule,n=this.bufferingItem;if(!(this.bufferedPos>e)&&i)if(1===t.length&&this.itemsMatch(t[0],n))this.bufferedPos=e;else{var a=this.playingItem,s=this.findItemIndex(a),o=i.findItemIndexAtTime(e);if(this.bufferedPos<e){var l,u=this.findItemIndex(n),c=Math.min(u+1,t.length-1),d=t[c];if((-1===o&&n&&e>=n.end||null!=(l=d.event)&&l.appendInPlace&&e+.01>=d.start)&&(o=c),this.isInterstitial(n)){var h=n.event;if(c-s>1&&!1===h.appendInPlace)return;if(0===h.assetList.length&&h.assetListLoader)return}if(this.bufferedPos=e,o>u&&o>s)this.bufferedToItem(d);else{var f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&d.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(d)&&this.preloadAssets(d.event,0)}}else r&&a&&!this.itemsMatch(a,n)&&(o===s?this.bufferedToItem(a):o===s+1&&this.bufferedToItem(t[o]))}}},{key:"assetsBuffered",value:function(e,t){var r=this;return 0!==e.event.assetList.length&&!e.event.assetList.some(function(e){var i=r.getAssetPlayer(e.identifier);return!(null!=i&&i.bufferedInPlaceToEnd(t))})}},{key:"setBufferingItem",value:function(e){var t=this,r=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(e,r)&&i){var n=i.items,a=i.events;if(!n||!a)return r;var s=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));var l=o?o.remaining:r?r.end-this.timelinePos:0;if(this.log("INTERSTITIALS_BUFFERED_TO_BOUNDARY ".concat(yc(e))+(r?" (".concat(l.toFixed(2)," remaining)"):"")),!this.playbackDisabled)if(s){var u=i.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach(function(e,r){var i=t.getAssetPlayer(e.identifier);i&&(r===u&&i.loadSource(),i.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(function(e){return e.pauseBuffering()});this.hls.trigger(ne.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:a.slice(0),schedule:n.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return r}},{key:"bufferedToItem",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=this.setBufferingItem(e);if(!this.playbackDisabled)if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(null!==r){this.bufferingAsset=null;var i=this.getPrimaryResumption(e,this.findItemIndex(e),!0),n=this.bufferedPos=Math.max(i,Math.min(this.bufferedPos,e.end),this.timelinePos,e.start),a=this.detachedData;if(a)if(a.mediaSource){this.attachPrimary(n,e,!0)}else this.startLoadingPrimaryAt(n);else{var s=this.playingItem,o=this.isInterstitial(s)&&s.event.appendInPlace;this.startLoadingPrimaryAt(n,o)}}}},{key:"bufferedToEvent",value:function(e,t){var r=e.event,i=0===r.assetList.length&&!r.assetListLoader,n=r.cue.once;if(i||!n){var a=this.preloadAssets(r,t);if(null!=a&&a.interstitial.appendInPlace){var s=this.primaryMedia;s&&this.bufferAssetPlayer(a,s)}}}},{key:"preloadAssets",value:function(e,t){var r=e.assetUrl,i=e.assetList.length,n=0===i&&!e.assetListLoader,a=e.cue.once;if(n){var s,o,l=e.timelineStart,u=this.playingItem,c=this.getBufferingPlayer();if(e.appendInPlace)this.isInterstitial(u)||(null==u||null==(s=u.nextEvent)?void 0:s.identifier)!==e.identifier||this.flushFrontBuffer(l+.25);var d=0;if(c&&!c.interstitial.cue.pre||!this.primaryLive||(d=this.getLiveStartPos(),c&&(d+=c.remaining)),d&&!e.cue.pre&&!e.cue.post){var h=d-l;h>0&&(o=Math.round(1e3*h)/1e3)}if(this.log("Load interstitial asset ".concat(t+1,"/").concat(r?1:i," ").concat(e).concat(d?" live-start: ".concat(d," start-offset: ").concat(o," (timeline-start: ").concat(l,")"):"")),r)return this.createAsset(e,0,0,l,e.duration,r);var f=this.assetListLoader.loadAssetList(e,o);f&&(e.assetListLoader=f)}else if(!a&&i){for(var v=t;v<i;v++){var g=e.assetList[v],p=this.getAssetPlayerQueueIndex(g.identifier);-1!==p&&!this.playerQueue[p].destroyed||g.error||this.createAssetPlayer(e,g,v)}var m=e.assetList[t];if(m){var y=this.getAssetPlayer(m.identifier);return y&&y.loadSource(),y}}return null}},{key:"flushFrontBuffer",value:function(e){var t=this,r=this.requiredTracks;if(r){var i=this.primaryDetails;if(!(i&&e>=i.edge))this.log("Removing front buffer starting at ".concat(e)),Object.keys(r).forEach(function(r){t.hls.trigger(ne.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:r})})}}},{key:"getAssetPlayerQueueIndex",value:function(e){for(var t=this.playerQueue,r=0;r<t.length;r++)if(e===t[r].assetId)return r;return-1}},{key:"getAssetPlayer",value:function(e){var t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}},{key:"getBufferingPlayer",value:function(){var e=this.playerQueue,t=this.primaryMedia;if(t)for(var r=0;r<e.length;r++)if(e[r].media===t)return e[r];return null}},{key:"createAsset",value:function(e,t,r,i,n,a){var s={parentIdentifier:e.identifier,identifier:lc(e,a,t),duration:n,startOffset:r,timelineStart:i,uri:a};return this.createAssetPlayer(e,s,t)}},{key:"createAssetPlayer",value:function(e,t,r){var i=this,n=this.hls,a=n.userConfig,s=Yr(n.loadLevelObj||n.levels[n.currentLevel],a.videoPreference),o=n.audioTracks[n.audioTrack],l=n.subtitleTracks[n.subtitleTrack],u=0;if(this.primaryLive||e.appendInPlace){var c=this.timelinePos-t.timelineStart;if(c>=0){var d=t.duration;d&&c<d&&(u=c)}}var h=t.identifier,f=Ie(Ie({},a),{},{maxMaxBufferLength:Math.min(15,n.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:n.sessionId,assetPlayerId:h,abrEwmaDefaultEstimate:n.bandwidthEstimate,interstitialsController:void 0,startPosition:u,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:s,audioPreference:o||a.audioPreference,subtitlePreference:l||a.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(f.timelineOffset=t.timelineStart));var v=f.cmcd;null!=v&&v.sessionId&&v.contentId&&(f.cmcd=Ae({},v,{contentId:mu(t.uri)})),this.getAssetPlayer(h)&&this.warn("Duplicate date range identifier ".concat(e," and asset ").concat(h));var g=new gc(this.HlsPlayerClass,f,e,t);this.playerQueue.push(g),e.assetList[r]=t;var p=!0,m=function(n){if(n.live){var a=new Error("Interstitials MUST be VOD assets ".concat(e)),s={fatal:!0,type:re.OTHER_ERROR,details:ie.INTERSTITIAL_ASSET_ITEM_ERROR,error:a},o=i.findEventIndex(e.identifier);i.handleAssetItemError(s,e,o,r,a.message)}else{var l=n.edge-n.fragmentStart,u=t.duration;(p||null===u||l>u)&&(p=!1,i.log('Interstitial asset "'.concat(h,'" duration change ').concat(u," > ").concat(l)),t.duration=l,i.updateSchedule())}};g.on(ne.LEVEL_UPDATED,function(e,t){var r=t.details;return m(r)}),g.on(ne.LEVEL_PTS_UPDATED,function(e,t){var r=t.details;return m(r)}),g.on(ne.EVENT_CUE_ENTER,function(){return i.onInterstitialCueEnter()});var y=function(e,t){var r=i.getAssetPlayer(h);if(r&&t.tracks){r.off(ne.BUFFER_CODECS,y),r.tracks=t.tracks;var n=i.primaryMedia;i.bufferingAsset===r.assetItem&&n&&!r.media&&i.bufferAssetPlayer(r,n)}};g.on(ne.BUFFER_CODECS,y);g.on(ne.BUFFERED_TO_END,function(){var t=i.getAssetPlayer(h);if(i.log("buffered to end of asset ".concat(t)),t&&i.schedule){var r=i.getEventItem(e.identifier);r&&i.advanceAssetBuffering(r,t.assetItem)}});var k=function(t){return function(){if(i.getAssetPlayer(h)&&i.schedule){i.shouldPlay=!0;var r=i.findEventIndex(e.identifier);i.advanceAfterAssetEnded(e,r,t)}}};return g.once(ne.MEDIA_ENDED,k(r)),g.once(ne.PLAYOUT_LIMIT_REACHED,k(1/0)),g.on(ne.ERROR,function(t,n){if(i.schedule){var a=i.getAssetPlayer(h);if(n.details===ie.BUFFER_STALLED_ERROR)return null!=a&&a.appendInPlace?void i.handleInPlaceStall(e):(i.onTimeupdate(),void i.checkBuffer(!0));n.details!==ie.BUFFER_SEEK_OVER_HOLE&&i.handleAssetItemError(n,e,i.findEventIndex(e.identifier),r,"Asset player error ".concat(n.error," ").concat(e))}}),g.on(ne.DESTROYING,function(){if(i.getAssetPlayer(h)&&i.schedule){var t=new Error("Asset player destroyed unexpectedly ".concat(h)),n={fatal:!0,type:re.OTHER_ERROR,details:ie.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};i.handleAssetItemError(n,e,i.findEventIndex(e.identifier),r,t.message)}}),this.log("INTERSTITIAL_ASSET_PLAYER_CREATED ".concat(vc(t))),this.hls.trigger(ne.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:r,event:e,player:g}),g}},{key:"clearInterstitial",value:function(e,t){this.clearAssetPlayers(e,t),e.reset()}},{key:"clearAssetPlayers",value:function(e,t){var r=this;e.assetList.forEach(function(e){r.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 r=this.playerQueue[t];this.transferMediaFromPlayer(r,null),r.resetDetails()}}},{key:"clearAssetPlayer",value:function(e,t){var r=this.getAssetPlayerQueueIndex(e);if(-1!==r){var i=this.playerQueue[r];this.log("clear ".concat(i," toSegment: ").concat(t?yc(t):t)),this.transferMediaFromPlayer(i,t),this.playerQueue.splice(r,1),i.destroy()}}},{key:"emptyPlayerQueue",value:function(){for(var e;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}},{key:"startAssetPlayer",value:function(e,t,r,i,n){var a=e.interstitial,s=e.assetItem,o=e.assetId,l=a.assetList.length,u=this.playingAsset;this.endedAsset=null,this.playingAsset=s,(null==u?void 0:u.identifier)!==o&&(u&&(this.clearAssetPlayer(u.identifier,r[i]),delete u.error),this.log("INTERSTITIAL_ASSET_STARTED ".concat(t+1,"/").concat(l," ").concat(vc(s))),this.hls.trigger(ne.INTERSTITIAL_ASSET_STARTED,{asset:s,assetListIndex:t,event:a,schedule:r.slice(0),scheduleIndex:i,player:e})),this.bufferAssetPlayer(e,n)}},{key:"bufferAssetPlayer",value:function(e,t){var r;if(this.schedule){var i=e.interstitial,n=e.assetItem,a=this.getEventItem(i.identifier);if(a)if(e.loadSource(),this.setBufferingItem(a),this.bufferingAsset=n,e.bufferedInPlaceToEnd(this.primaryMedia,e.currentTime))this.advanceAssetBuffering(a,n);else{var s=this.getBufferingPlayer();if(s!==e){var o=i.appendInPlace;if(!o||!1!==(null==s?void 0:s.interstitial.appendInPlace)){var l=(null==s?void 0:s.tracks)||(null==(r=this.detachedData)?void 0:r.tracks)||this.requiredTracks;if(o&&n!==this.playingAsset){if(!e.tracks)return void this.log("Waiting for track info before buffering ".concat(e));if(l&&!We(l,e.tracks)){var u=new Error("Asset ".concat(vc(n)," SourceBuffer tracks ('").concat(Object.keys(e.tracks),"') are not compatible with primary content tracks ('").concat(Object.keys(l),"')")),c={fatal:!0,type:re.OTHER_ERROR,details:ie.INTERSTITIAL_ASSET_ITEM_ERROR,error:u},d=i.findAssetIndex(n);return void this.handleAssetItemError(c,i,this.findEventIndex(i.identifier),d,u.message)}}this.transferMediaTo(e,t)}}}}}},{key:"handleInPlaceStall",value:function(e){var t=this.schedule,r=this.primaryMedia;if(t&&r){var i=r.currentTime,n=t.findAssetIndex(e,i),a=e.assetList[n];if(a){var s=this.getAssetPlayer(a.identifier);if(s){var o=s.currentTime||i-a.timelineStart,l=s.duration-o;if(this.warn("Stalled at ".concat(o," of ").concat(o+l," in ").concat(s," ").concat(e," (media.currentTime: ").concat(i,")")),o&&(l/r.playbackRate<.5||s.bufferedInPlaceToEnd(r,s.currentTime))&&s.hls){var u=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,u,n)}}}}}},{key:"advanceInPlace",value:function(e){var t=this.primaryMedia;if(t&&t.currentTime<e){var r="advance currentTime to ".concat(e,", duration: ").concat(t.duration);t.duration>e?(this.log(r),t.currentTime=e):this.log("Cannot ".concat(r))}}},{key:"handleAssetItemError",value:function(e,t,r,i,n){if(e.details!==ie.BUFFER_STALLED_ERROR){var a=t.assetList[i]||null;if(this.warn("INTERSTITIAL_ASSET_ERROR ".concat(a?vc(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=Ae({},e,{fatal:!1,errorAction:vi(!0),asset:a,assetListIndex:i,event:t,schedule:u,scheduleIndex:r,player:l});if(this.hls.trigger(ne.INTERSTITIAL_ASSET_ERROR,c),e.fatal){var d=this.playingAsset,h=this.bufferingAsset,f=new Error(n);if(a&&(this.clearAssetPlayer(s,null),a.error=f),t.assetList.some(function(e){return!e.error}))for(var v=i;v<t.assetList.length;v++)this.resetAssetPlayer(t.assetList[v].identifier);else t.error=f;this.updateSchedule(!0),t.error?this.primaryFallback(t):(null==d?void 0:d.identifier)===s?this.advanceAfterAssetEnded(t,r,i):(null==h?void 0:h.identifier)===s&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,h)}}}}},{key:"primaryFallback",value:function(e){var t=e.timelineStart,r=this.effectivePlayingItem,i=this.playingItem,n=this.seekableStart,a=this.hls.startPosition,s=this.timelinePos;if(this.isInterstitial(r)){this.log('Fallback to primary from event "'.concat(e.identifier,'" start: ').concat(t," pos: ").concat(s," playing: ").concat(yc(r)," startPosition: ").concat(a," seekableStart: ").concat(n," error: ").concat(e.error)),-1===s&&(s=a),s=Math.max(s,n);var o=this.updateItem(r,s);this.itemsMatch(r,o)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(-1===s)return void this.checkStart();if(this.schedule&&this.isInterstitial(i)){var l=this.schedule.findItemIndexAtTime(s);this.setSchedulePosition(l)}}},{key:"onAssetListLoaded",value:function(e,t){var r,i,n=this,a=t.event,s=a.identifier,o=t.assetListResponse.ASSETS;if(null!=(r=this.schedule)&&r.hasEvent(s)){var l=a.timelineStart,u=a.duration,c=0;o.forEach(function(e,t){var r=parseFloat(e.DURATION);n.createAsset(a,t,c,l+c,r,e.URI),c+=r}),a.duration=c,this.log("Loaded asset-list with duration: ".concat(c," (was: ").concat(u,") ").concat(a));var d=this.waitingItem,h=(null==d?void 0:d.event.identifier)===s;this.updateSchedule();var f=null==(i=this.bufferingItem)?void 0:i.event;if(h){var v=this.findEventIndex(s),g=this.getEventItem(s);if(g){if(!this.playingItem&&this.timelinePos>g.end)if(this.schedule.findItemIndexAtTime(this.timelinePos)!==v)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(g)}this.setSchedulePosition(v)}else if((null==f?void 0:f.identifier)===s){var p=a.assetList[0];if(p){var m=this.getAssetPlayer(p.identifier);if(f.appendInPlace){var y=this.primaryMedia;m&&y&&this.bufferAssetPlayer(m,y)}else m&&m.loadSource()}}}}},{key:"onError",value:function(e,t){if(this.schedule)switch(t.details){case ie.ASSET_LIST_PARSING_ERROR:case ie.ASSET_LIST_LOAD_ERROR:case ie.ASSET_LIST_LOAD_TIMEOUT:var r=t.interstitial;r&&(this.updateSchedule(!0),this.primaryFallback(r));break;case ie.BUFFER_STALLED_ERROR:var i=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&i.event.appendInPlace)return void this.handleInPlaceStall(i.event);var n=this.primaryMedia;this.log("Primary player stall @".concat(this.timelinePos," currentTime: ").concat(null==n?void 0:n.currentTime," bufferedPos: ").concat(this.bufferedPos)),this.onTimeupdate(),this.checkBuffer(!0)}}}])}(Be),Ac=function(){return l(function e(t){var r=this;s(this,e),this.hls=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=function(){var e,t=r.media,i=r.levelDetails;if(t&&i&&r.hls){r.currentTime=t.currentTime;var n=r.hls.config,a=r.computeLatency();if(null!==a){r._latency=a;var s=n.lowLatencyMode,o=n.maxLiveSyncPlaybackRate;if(s&&1!==o&&i.live){var l=r.targetLatency;if(null!==l){var u=a-l,c=u<Math.min(r.maxLatency,l+i.targetduration),d=ya(n)&&!(null==(e=r.hls.interstitialsManager)||null==(e=e.playingItem)||!e.event);if(c&&u>.05&&r.forwardBufferLength>1&&!d){var h=Math.min(2,Math.max(1,o)),f=Math.round(2/(1+Math.exp(-.75*u-r.edgeStalled))*20)/20,v=Math.min(h,Math.max(1,f));r.changeMediaPlaybackRate(t,v)}else 1!==t.playbackRate&&0!==t.playbackRate&&r.changeMediaPlaybackRate(t,1)}}}}},this.hls=t,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,t=null==(e=this.hls)?void 0:e.config;if(!t)return 0;if(void 0!==t.liveMaxLatencyDuration)return t.liveMaxLatencyDuration;var r=this.levelDetails;return r?t.liveMaxLatencyDurationCount*r.targetduration:0}},{key:"targetLatency",get:function(){var e=this.levelDetails;if(null===e||!this.hls)return null;var t=this.hls.config,r=e.holdBack,i=e.partHoldBack,n=e.targetduration,a=t.liveSyncDuration,s=t.liveSyncDurationCount,o=t.lowLatencyMode,l=this.hls.userConfig,u=o&&i||r;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||0===u)&&(u=void 0!==a?a:s*n);var c=n;return u+Math.min(this.stallCount*t.liveSyncOnStallIncrease,c)},set:function(e){this.hls&&(this.stallCount=0,this.hls.config.liveSyncDuration=e,this._targetLatencyUpdated=!0)}},{key:"liveSyncPosition",get:function(){var e=this.estimateLiveEdge(),t=this.targetLatency;if(null===e||null===t||!this.hls)return null;var r=this.levelDetails;if(null===r)return null;var i=r.edge,n=e-t-this.edgeStalled,a=i-r.totalduration,s=i-(this.hls.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(a,n),s)}},{key:"drift",get:function(){var e=this.levelDetails;return null===e?1:e.drift}},{key:"edgeStalled",get:function(){var e=this.levelDetails;if(null===e||!this.hls)return 0;var t=3*(this.hls.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}},{key:"forwardBufferLength",get:function(){var e=this.media,t=this.levelDetails;if(!e||!t)return 0;var r=e.buffered.length;return(r?e.buffered.end(r-1):t.edge)-this.currentTime}},{key:"destroy",value:function(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}},{key:"registerListeners",value:function(){var e=this.hls;e&&(e.on(ne.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ne.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ne.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(ne.ERROR,this.onError,this),e.on(ne.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ne.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ne.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ne.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(ne.ERROR,this.onError,this),e.off(ne.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}},{key:"onMediaAttached",value:function(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}},{key:"onMediaDetaching",value:function(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}},{key:"onManifestLoading",value:function(){this._latency=null,this.stallCount=0}},{key:"onLevelUpdated",value:function(e,t){var r=t.details;r.advanced&&this.onTimeupdate(),!r.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}},{key:"onAssetStarted",value:function(e,t){var r,i=this.hls,n=this.media||t.event.appendInPlace&&(null==i||null==(r=i.interstitialsManager)?void 0:r.playerQueue.reduce(function(e,t){return e||t.media},null));i&&n&&n.playbackRate>1&&n.playbackRate<=i.config.maxLiveSyncPlaybackRate&&this.changeMediaPlaybackRate(n,1)}},{key:"onError",value:function(e,t){var r;t.details===ie.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(r=this.levelDetails)&&r.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}},{key:"changeMediaPlaybackRate",value:function(e,t){var r,i;e.playbackRate!==t&&(null==(r=this.hls)||r.logger.debug("[latency-controller]: latency=".concat(this.latency.toFixed(3),", targetLatency=").concat(null==(i=this.targetLatency)?void 0:i.toFixed(3),", forwardBufferLength=").concat(this.forwardBufferLength.toFixed(3),": adjusting playback rate from ").concat(e.playbackRate," to ").concat(t)),e.playbackRate=t)}},{key:"estimateLiveEdge",value:function(){var e=this.levelDetails;return null===e?null:e.edge+e.age}},{key:"computeLatency",value:function(){var e=this.estimateLiveEdge();return null===e?null:e-this.currentTime}}])}(),bc=function(e){function t(e,r,i){var n;return s(this,t),(n=a(this,t,[e,r,i,"subtitle-stream-controller",de.SUBTITLE])).currentTrackId=-1,n.tracksBuffered=[],n.mainDetails=null,n.registerListeners(),n}return f(t,e),l(t,[{key:"onHandlerDestroying",value:function(){this.unregisterListeners(),A(t,"onHandlerDestroying",this,3)([]),this.mainDetails=null}},{key:"registerListeners",value:function(){A(t,"registerListeners",this,3)([]);var e=this.hls;e.on(ne.LEVEL_LOADED,this.onLevelLoaded,this),e.on(ne.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(ne.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(ne.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(ne.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(ne.BUFFER_FLUSHING,this.onBufferFlushing,this)}},{key:"unregisterListeners",value:function(){A(t,"unregisterListeners",this,3)([]);var e=this.hls;e.off(ne.LEVEL_LOADED,this.onLevelLoaded,this),e.off(ne.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(ne.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(ne.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(ne.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(ne.BUFFER_FLUSHING,this.onBufferFlushing,this)}},{key:"startLoad",value:function(e,t){this.stopLoad(),this.state=aa,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}},{key:"onManifestLoading",value:function(){A(t,"onManifestLoading",this,3)([]),this.mainDetails=null}},{key:"onMediaDetaching",value:function(e,r){this.tracksBuffered=[],A(t,"onMediaDetaching",this,3)([e,r])}},{key:"onLevelLoaded",value:function(e,t){this.mainDetails=t.details}},{key:"onSubtitleFragProcessed",value:function(e,t){var r=t.frag,i=t.part;if(t.success){var n=this.tracksBuffered[this.currentTrackId];if(n){for(var a,s=(i||r).start,o=0;o<n.length;o++)if(s>=n[o].start&&s<=n[o].end){a=n[o];break}var l=s+(i||r).duration;if(a?a.end=l:(a={start:s,end:l},n.push(a)),!i||l>=r.end){var u=this.fragmentTracker.fragBuffered(r);i&&u&&(u.range.subs={time:[{startPTS:r.start,endPTS:l}],partial:!0}),pe(r)&&!this.fragContextChanged(r)&&(this.fragPrevious=r),this.fragBufferedComplete(r,i),this.media&&this.tickImmediate()}}}}},{key:"onBufferFlushing",value:function(e,t){var r=t.startOffset,i=t.endOffset;if(0===r&&i!==Number.POSITIVE_INFINITY){var n=i-1;if(n<=0)return;t.endOffsetSubtitles=Math.max(0,n),this.tracksBuffered.forEach(function(e){if(e)for(var t=0;t<e.length;)if(e[t].end<=n)e.shift();else{if(!(e[t].start<n))break;e[t].start=n,t++}}),this.fragmentTracker.removeFragmentsInRange(r,n,de.SUBTITLE)}}},{key:"onError",value:function(e,t){var r=t.frag;(null==r?void 0:r.type)===de.SUBTITLE&&(t.details===ie.FRAG_GAP&&this.fragmentTracker.addAsGap(r),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==na&&(this.state=aa))}},{key:"onSubtitleTracksUpdated",value:function(e,t){var r=this,i=t.subtitleTracks;this.levels&&Qs(this.levels,i)?this.levels=i.map(function(e){return new xr(e)}):(this.tracksBuffered=[],this.levels=i.map(function(e){var t=new xr(e);return r.tracksBuffered[t.id]=[],t}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,de.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null)}},{key:"onSubtitleTrackSwitch",value:function(e,t){var r;if(this.currentTrackId=t.id,this.abortCurrentFrag(),null!=(r=this.levels)&&r.length&&-1!==this.currentTrackId){var i=this.levels[this.currentTrackId];null!=i&&i.details?(this.mediaBuffer=this.mediaBufferTimeRanges,this.state!==na&&this.setInterval(500)):this.mediaBuffer=null}else this.clearInterval()}},{key:"onSubtitleTrackLoaded",value:function(e,t){var r,i=this.currentTrackId,n=this.levels,a=t.details,s=t.id;if(n){var o=n[s];if(!(s>=n.length)&&o){this.log("Subtitle track ".concat(s," loaded [").concat(a.startSN,",").concat(a.endSN,"]").concat(a.lastPartSn?"[part-".concat(a.lastPartSn,"-").concat(a.lastPartIndex,"]"):"",",duration:").concat(a.totalduration)),this.mediaBuffer=this.mediaBufferTimeRanges;var l=this.mainDetails,u=0;if(a.live||null!=(r=o.details)&&r.live){if(a.deltaUpdateFailed)return;if(!l)return void(this.startFragRequested=!1);var c;if(o.details)u=this.alignPlaylists(a,o.details,null==(c=this.levelLastLoaded)?void 0:c.details);a.alignedSliding||(ea(l,a,this),u=a.fragmentStart)}o.details=a,this.levelLastLoaded=o,l&&!this.startFragRequested&&this.setStartPosition(l,u),s===i&&(this.hls.trigger(ne.SUBTITLE_TRACK_UPDATED,{details:a,id:s,groupId:t.groupId}),this.tickImmediate())}}else this.warn("Subtitle tracks were reset while loading level ".concat(s))}},{key:"_handleFragmentLoadProgress",value:function(e){var t=e.frag,r=e.part,i=e.payload;r&&null!=i&&i.byteLength&&this.shouldDecrypt(t)&&this.decryptPayload(i,t,r)}},{key:"_handleFragmentLoadComplete",value:function(e){var t=e.frag,r=e.payload;!this.fragContextChanged(t)&&null!=r&&r.byteLength&&this.shouldDecrypt(t)&&this.decryptPayload(r,t,null)}},{key:"shouldDecrypt",value:function(e){var t=e.decryptdata;return!!(null!=t&&t.key&&t.iv&&Zi(t.method))}},{key:"decryptPayload",value:function(e,t,r){var i=this,n=t.decryptdata,a=performance.now();this.decrypter.decrypt(new Uint8Array(e),n.key.buffer,n.iv.buffer,en(n.method)).then(function(e){i.fragContextChanged(t)||i.hls.trigger(ne.FRAG_DECRYPTED,{frag:t,part:r,payload:e,stats:{tstart:a,tdecrypt:performance.now()}})}).catch(function(e){i.hls.trigger(ne.ERROR,{type:re.MEDIA_ERROR,details:ie.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t,part:r}),r||(i.warn("".concat(e.name,": ").concat(e.message)),i.state=aa)})}},{key:"doTick",value:function(){if(this.state===aa&&this.levels){var e;if(!this.media&&!this.primaryPrefetch&&(this.startFragRequested||!this.config.startFragPrefetch))return;var t=this.currentTrackId,r=this.levels[t],i=null==r?void 0:r.details;if(!i||this.waitForLive(r)||this.waitForCdnTuneIn(i))return void(this.startFragRequested=!1);var n=this.config,a=this.playhead,s=Bi.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],a,n.maxBufferHole),o=s.end,l=s.len;if(l>Math.max(this.hls.maxBufferLength+i.levelTargetDuration,(null==(e=this.hls.mainForwardBufferInfo)?void 0:e.len)||0)||l&&!this.buffering)return;var u=this.getNextFragment(o,i);if(!u)return;if(pe(u)){var c,d=u.sn-i.startSN,h=i.fragments[d-1];u.cc!==(null==h?void 0:h.cc)||null!=(c=i.partList)&&c.length||this.fragmentTracker.getState(h)!==gi||(u=h)}this.loadFragment(u,r,o)}}},{key:"loadFragment",value:function(e,r,i){var n=this.fragmentTracker.getState(e);n!==gi&&n!==mi||A(t,"loadFragment",this,3)([e,r,i])}},{key:"mediaBufferTimeRanges",get:function(){return new Ic(this.tracksBuffered[this.currentTrackId]||[])}}])}(pa),Ic=l(function e(t){s(this,e),this.buffered=void 0;var r=function(e,r,i){if((r>>>=0)>i-1)throw new DOMException("Failed to execute '".concat(e,"' on 'TimeRanges': The index provided (").concat(r,") is greater than the maximum bound (").concat(i,")"));return t[r][e]};this.buffered={get length(){return t.length},end:function(e){return r("end",e,t.length)},start:function(e){return r("start",e,t.length)}}}),Rc={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},Lc=function(e){return String.fromCharCode(Rc[e]||e)},Pc=15,wc=42,Cc={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Dc={17:2,18:4,21:6,22:8,23:10,19:13,20:15},_c={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Mc={25:2,26:4,29:6,30:8,31:10,27:13,28:15},xc=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],Oc=function(){return l(function e(){s(this,e),this.time=null,this.verboseLevel=0},[{key:"log",value:function(e,t){if(this.verboseLevel>=e){var r="function"==typeof t?t():t;je.log("".concat(this.time," [").concat(e,"] ").concat(r))}}}])}(),Fc=function(e){for(var t=[],r=0;r<e.length;r++)t.push(e[r].toString(16));return t},Nc=Object.freeze({foreground:"white",underline:!1,italics:!1,background:"black",flash:!1}),Bc=function(){return l(function e(){s(this,e),this.styles=Nc},[{key:"foreground",get:function(){return this.styles.foreground},set:function(e){var t=this.styles;this.styles={foreground:e,underline:t.underline,italics:t.italics,background:t.background,flash:t.flash}}},{key:"underline",get:function(){return this.styles.underline},set:function(e){var t=this.styles;this.styles={foreground:t.foreground,underline:e,italics:t.italics,background:t.background,flash:t.flash}}},{key:"italics",get:function(){return this.styles.italics},set:function(e){var t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:e,background:t.background,flash:t.flash}}},{key:"background",get:function(){return this.styles.background},set:function(e){var t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:t.italics,background:e,flash:t.flash}}},{key:"flash",get:function(){return this.styles.flash},set:function(e){var t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:t.italics,background:t.background,flash:e}}},{key:"reset",value:function(){this.styles=Nc}},{key:"setStyles",value:function(e){var t=this.styles,r=Object.prototype.hasOwnProperty;this.styles={foreground:r.call(e,"foreground")?e.foreground:t.foreground,underline:r.call(e,"underline")?e.underline:t.underline,italics:r.call(e,"italics")?e.italics:t.italics,background:r.call(e,"background")?e.background:t.background,flash:r.call(e,"flash")?e.flash:t.flash}}},{key:"toString",value:function(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}])}(),Uc=function(){return l(function e(){s(this,e),this.uchar=" ",this.penState=new Bc},[{key:"reset",value:function(){this.uchar=" ",this.penState.reset()}},{key:"setChar",value:function(e,t){this.uchar=e,this.penState.styles=t.styles}},{key:"setPenState",value:function(e){this.penState.styles=e.styles}},{key:"copy",value:function(e){this.uchar=e.uchar,this.penState.styles=e.penState.styles}}])}(),Vc=function(){return l(function e(t){s(this,e),this.chars=[],this.pos=0,this.currPenState=new Bc,this.cueStartTime=null,this.logger=void 0;for(var r=0;r<wc;r++)this.chars.push(new Uc);this.logger=t},[{key:"equals",value:function(e){for(var t=this.chars,r=e.chars,i=0;i<wc;i++){var n=t[i],a=r[i];if(n.uchar!==a.uchar)return!1;var s=n.penState.styles,o=a.penState.styles;if(s!==o&&(s.foreground!==o.foreground||s.underline!==o.underline||s.italics!==o.italics||s.background!==o.background||s.flash!==o.flash))return!1}return!0}},{key:"copy",value:function(e){for(var t=0;t<wc;t++)this.chars[t].copy(e.chars[t])}},{key:"isEmpty",value:function(){for(var e=this.chars,t=0;t<wc;t++){var r=e[t];if(" "!==r.uchar)return!1;var i=r.penState.styles;if(i!==Nc&&("white"!==i.foreground||i.underline||i.italics||"black"!==i.background||i.flash))return!1}return!0}},{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>=wc&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=41)}},{key:"moveCursor",value:function(e){var t=Math.min(this.pos+e,wc);if(e>1)for(var r=this.pos+1;r<t;r++)this.chars[r].setPenState(this.currPenState);this.setCursor(t)}},{key:"backSpace",value:function(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}},{key:"insertChar",value:function(e){var t=this;e>=144&&this.backSpace();var r=Lc(e);this.pos>=wc?this.logger.log(0,function(){return"Cannot insert "+e.toString(16)+" ("+r+") at position "+t.pos+". Skipping it!"}):(this.chars[this.pos].setChar(r,this.currPenState),this.moveCursor(1))}},{key:"clearFromPos",value:function(e){var t;for(t=e;t<wc;t++)this.chars[t].reset()}},{key:"clear",value:function(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}},{key:"clearToEndOfRow",value:function(){this.clearFromPos(this.pos)}},{key:"getTextString",value:function(){for(var e=[],t=!0,r=0;r<wc;r++){var i=this.chars[r].uchar;" "!==i&&(t=!1),e.push(i)}return t?"":e.join("")}},{key:"setPenStyles",value:function(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}])}(),Gc=function(){return l(function e(t){s(this,e),this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(var r=0;r<Pc;r++)this.rows.push(new Vc(t));this.logger=t},[{key:"reset",value:function(){for(var e=0;e<Pc;e++)this.rows[e].clear();this.currRow=14}},{key:"equals",value:function(e){for(var t=!0,r=0;r<Pc;r++)if(!this.rows[r].equals(e.rows[r])){t=!1;break}return t}},{key:"copy",value:function(e){for(var t=0;t<Pc;t++)for(var r=this.rows[t].chars,i=e.rows[t].chars,n=0;n<wc;n++){var a=r[n],s=i[n];a.uchar=s.uchar,a.penState.styles=s.penState.styles}}},{key:"isEmpty",value:function(){for(var e=!0,t=0;t<Pc;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 = "+Nr(e)});var t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(var r=0;r<Pc;r++)this.rows[r].clear();var i=this.currRow+1-this.nrRollUpRows,n=this.lastOutputScreen;if(n){var a=n.rows[i].cueStartTime,s=this.logger.time;if(null!==a&&null!==s&&a<s)for(var o=0;o<this.nrRollUpRows;o++)this.rows[t-this.nrRollUpRows+o+1].copy(n.rows[i+o])}}this.currRow=t;var l=this.rows[this.currRow];if(null!==e.indent){var u=e.indent,c=Math.max(u-1,0);l.setCursor(e.indent),e.color=l.chars[c].penState.foreground}var d={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(d)}},{key:"setBkgData",value:function(e){this.logger.log(2,function(){return"bkgData = "+Nr(e)}),this.backSpace(),this.setPen(e),this.insertChar(32)}},{key:"setRollUpRows",value:function(e){this.nrRollUpRows=e}},{key:"rollUp",value:function(){var e=this;if(null!==this.nrRollUpRows){this.logger.log(1,function(){return e.getDisplayText()});var t=this.currRow+1-this.nrRollUpRows,r=this.rows.splice(t,1)[0];r.clear(),this.rows.splice(this.currRow,0,r),this.logger.log(2,"Rolling up")}else this.logger.log(3,"roll_up but nrRollUpRows not set yet")}},{key:"getDisplayText",value:function(e){e=e||!1;for(var t=[],r="",i=-1,n=0;n<Pc;n++){var a=this.rows[n].getTextString();a&&(i=n+1,e?t.push("Row "+i+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(r=e?"["+t.join(" | ")+"]":t.join("\n")),r}},{key:"getTextAndFormat",value:function(){return this.rows}}])}(),Hc=function(){return l(function e(t,r,i){s(this,e),this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=t,this.outputFilter=r,this.mode=null,this.verbose=0,this.displayedMemory=new Gc(i),this.nonDisplayedMemory=new Gc(i),this.lastOutputScreen=new Gc(i),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i},[{key:"reset",value:function(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}},{key:"getHandler",value:function(){return this.outputFilter}},{key:"setHandler",value:function(e){this.outputFilter=e}},{key:"setPAC",value:function(e){this.writeScreen.setPAC(e)}},{key:"setBkgData",value:function(e){this.writeScreen.setBkgData(e)}},{key:"setMode",value:function(e){e!==this.mode&&(this.mode=e,this.logger.log(2,function(){return"MODE="+e}),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}},{key:"insertChars",value:function(e){for(var t=this,r=0;r<e.length;r++)this.writeScreen.insertChar(e[r]);var i=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,function(){return i+": "+t.writeScreen.getDisplayText(!0)}),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,function(){return"DISPLAYED: "+t.displayedMemory.getDisplayText(!0)}),this.outputDataUpdate())}},{key:"ccRCL",value:function(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}},{key:"ccBS",value:function(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}},{key:"ccAOF",value:function(){}},{key:"ccAON",value:function(){}},{key:"ccDER",value:function(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}},{key:"ccRU",value:function(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}},{key:"ccFON",value:function(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}},{key:"ccRDC",value:function(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}},{key:"ccTR",value:function(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}},{key:"ccRTD",value:function(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}},{key:"ccEDM",value:function(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}},{key:"ccCR",value:function(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}},{key:"ccENM",value:function(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}},{key:"ccEOC",value:function(){var e=this;if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){var t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,function(){return"DISP: "+e.displayedMemory.getDisplayText()})}this.outputDataUpdate(!0)}},{key:"ccTO",value:function(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}},{key:"ccMIDROW",value:function(e){var t={flash:!1};if(t.underline=e%2==1,t.italics=e>=46,t.italics)t.foreground="white";else{var r=Math.floor(e/2)-16;t.foreground=["white","green","blue","cyan","red","yellow","magenta"][r]}this.logger.log(2,"MIDROW: "+Nr(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))}}])}(),Kc=function(){return l(function e(t,r,i){s(this,e),this.channels=[null,null,null],this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0,this.field=void 0,this.outputFilters=void 0,this.logger=new Oc,this.field=t,this.outputFilters=[null,r,i]},[{key:"getHandler",value:function(e){return this.outputFilters[e]}},{key:"setHandler",value:function(e,t){var r;this.outputFilters[e]=t,null==(r=this.channels[e])||r.setHandler(t)}},{key:"getChannel",value:function(e){var t=this.channels[e];return t||(t=this.channels[e]=new Hc(this.field+e-1,this.outputFilters[e],this.logger)),t}},{key:"addData",value:function(e,t){var r=this;this.logger.time=e;for(var i=function(e){var i=127&t[e],n=127&t[e+1],a=!1,s=null;if(0===i&&0===n)return 0;r.logger.log(3,function(){return"["+Fc([t[e],t[e+1]])+"] -> ("+Fc([i,n])+")"});var o=r.cmdHistory;if(i>=16&&i<=31){if(function(e,t,r){return r.a===e&&r.b===t}(i,n,o))return jc(null,null,o),r.logger.log(3,function(){return"Repeated command ("+Fc([i,n])+") is dropped"}),0;jc(i,n,r.cmdHistory),(a=r.parseCmd(i,n))||(a=r.parseMidrow(i,n)),a||(a=r.parsePAC(i,n)),a||(a=r.parseBackgroundAttributes(i,n))}else jc(null,null,o);if(!a&&(s=r.parseChars(i,n))){var l=r.currentChannel;if(l&&l>0)r.getChannel(l).insertChars(s);else r.logger.log(2,"No channel found yet. TEXT-MODE?")}a||s||r.logger.log(2,function(){return"Couldn't parse cleaned data "+Fc([i,n])+" orig: "+Fc([t[e],t[e+1]])})},n=0;n<t.length;n+=2)i(n)}},{key:"parseCmd",value:function(e,t){if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=33&&t<=35))return!1;var r=20===e||21===e||23===e?1:2,i=this.getChannel(r);return 20===e||21===e||28===e||29===e?32===t?i.ccRCL():33===t?i.ccBS():34===t?i.ccAOF():35===t?i.ccAON():36===t?i.ccDER():37===t?i.ccRU(2):38===t?i.ccRU(3):39===t?i.ccRU(4):40===t?i.ccFON():41===t?i.ccRDC():42===t?i.ccTR():43===t?i.ccRTD():44===t?i.ccEDM():45===t?i.ccCR():46===t?i.ccENM():47===t&&i.ccEOC():i.ccTO(t-32),this.currentChannel=r,!0}},{key:"parseMidrow",value:function(e,t){var r=0;if((17===e||25===e)&&t>=32&&t<=47){if((r=17===e?1:2)!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;var i=this.channels[r];return!!i&&(i.ccMIDROW(t),this.logger.log(3,function(){return"MIDROW ("+Fc([e,t])+")"}),!0)}return!1}},{key:"parsePAC",value:function(e,t){var r;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127)&&!((16===e||24===e)&&t>=64&&t<=95))return!1;var i=e<=23?1:2;return r=t>=64&&t<=95?1===i?Cc[e]:_c[e]:1===i?Dc[e]:Mc[e],this.getChannel(i).setPAC(this.interpretPAC(r,t)),this.currentChannel=i,!0}},{key:"interpretPAC",value:function(e,t){var r,i={color:null,italics:!1,indent:null,underline:!1,row:e};return r=t>95?t-96:t-64,i.underline=!(1&~r),r<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(i.italics=!0,i.color="white"):i.indent=4*Math.floor((r-16)/2),i}},{key:"parseChars",value:function(e,t){var r,i,n=null,a=null;(e>=25?(r=2,a=e-8):(r=1,a=e),a>=17&&a<=19)?(i=17===a?t+80:18===a?t+112:t+144,this.logger.log(2,function(){return"Special char '"+Lc(i)+"' in channel "+r}),n=[i]):e>=32&&e<=127&&(n=0===t?[e]:[e,t]);return n&&this.logger.log(3,function(){return"Char codes = "+Fc(n).join(",")}),n}},{key:"parseBackgroundAttributes",value:function(e,t){var r;if(!((16===e||24===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=45&&t<=47))return!1;var i={};16===e||24===e?(r=Math.floor((t-32)/2),i.background=xc[r],t%2==1&&(i.background=i.background+"_semi")):45===t?i.background="transparent":(i.foreground="black",47===t&&(i.underline=!0));var n=e<=23?1:2;return this.getChannel(n).setBkgData(i),!0}},{key:"reset",value:function(){for(var e=0;e<Object.keys(this.channels).length;e++){var t=this.channels[e];t&&t.reset()}jc(null,null,this.cmdHistory)}},{key:"cueSplitAtTime",value:function(e){for(var t=0;t<this.channels.length;t++){var r=this.channels[t];r&&r.cueSplitAtTime(e)}}}])}();function jc(e,t,r){r.a=e,r.b=t}var qc=function(){return l(function e(t,r){s(this,e),this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=t,this.trackName=r},[{key:"dispatchCue",value:function(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}},{key:"newCue",value:function(e,t,r){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=r,this.timelineController.createCaptionsTrack(this.trackName)}},{key:"reset",value:function(){this.cueRanges=[],this.startTime=null}}])}(),Wc=function(){return l(function e(t){s(this,e),this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.cueCache={},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.cueCache={},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(ne.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(ne.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(ne.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ne.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(ne.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(ne.FRAG_LOADING,this.onFragLoading,this),t.on(ne.FRAG_LOADED,this.onFragLoaded,this),t.on(ne.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(ne.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(ne.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(ne.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(ne.BUFFER_APPENDED,this.onBufferAppended,this),t.on(ne.BUFFER_FLUSHING,this.onBufferFlushing,this)},[{key:"destroy",value:function(){var e=this.hls;e.off(ne.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(ne.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ne.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(ne.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(ne.FRAG_LOADING,this.onFragLoading,this),e.off(ne.FRAG_LOADED,this.onFragLoaded,this),e.off(ne.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(ne.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(ne.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(ne.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(ne.BUFFER_APPENDED,this.onBufferAppended,this),e.off(ne.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 qc(this,"textTrack1"),t=new qc(this,"textTrack2"),r=new qc(this,"textTrack3"),i=new qc(this,"textTrack4");this.cea608Parser1=new Kc(1,e,t),this.cea608Parser2=new Kc(3,r,i)}},{key:"addCues",value:function(e,t,r,i,n){for(var a=!1,s=n.length;s--;){var o=n[s],l=Yc(o[0],o[1],t,r);if(l>=0&&(o[0]=Math.min(o[0],t),o[1]=Math.max(o[1],r),a=!0,l/(r-t)>.5))return}if(a||n.push([t,r]),this.config.renderTextTracksNatively){var u=this.cueCache[e];if(u){var c=this.Cues.newCue(null,t,r,i);c.length&&u.push.apply(u,c)}else{var d=this.captionsTracks[e].track;this.Cues.newCue(d,t,r,i)}}else{var h,f=this.Cues.newCue(null,t,r,i),v=null==(h=this.captionsProperties[e])?void 0:h.media;this.hls.trigger(ne.CUES_PARSED,{type:"captions",cues:f,track:e,closedCaptions:v})}}},{key:"onInitPtsFound",value:function(e,t){var r=this,i=t.id,n=t.timestampOffsets,a=this.unparsedVttFrags;i===de.MAIN&&(this.initPTS=n),a.length&&(this.unparsedVttFrags=[],a.forEach(function(e){r.initPTS[e.frag.cc]?r.onFragLoaded(ne.FRAG_LOADED,e):r.hls.trigger(ne.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e.frag,part:null,error:new Error("Subtitle discontinuity domain does not match main")})}))}},{key:"createCaptionsTrack",value:function(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}},{key:"createNativeTrack",value:function(e){if(!this.captionsTracks[e]){var t=this.captionsProperties,r=this.captionsTracks,i=this.cueCache,n=this.media,a=t[e],s=a.label,o=a.languageCode;n&&(i[e]=[],r[e]=Mu(n,"captions",s,o,"hidden"))}}},{key:"createNonNativeTrack",value:function(e){if(!this.nonNativeCaptionsTracks[e]){var t=this.captionsProperties[e];if(t){var r={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=r,this.hls.trigger(ne.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[r]})}}}},{key:"onMediaAttaching",value:function(e,t){this.media=t.media}},{key:"onMediaDetaching",value:function(e,t){var r=!!t.transferMedia;if(this.media=null,!r){if(this.config.renderTextTracksNatively){var i=this.captionsTracks,n=this.cueCache;for(var a in i)i[a].remove(),delete n[a]}this.cueCache={},this.captionsTracks={},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.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}},{key:"onSubtitleTracksUpdated",value:function(e,t){var r=t.subtitleTracks||[];if(r.length&&!this.config.renderTextTracksNatively&&!Qs(this.tracks,r)){var i=r.map(function(e){return{label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e}});this.hls.trigger(ne.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:i})}this.tracks=r}},{key:"onManifestLoaded",value:function(e,t){var r=this;this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(function(e){var t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(t){var i="textTrack".concat(t[1]),n=r.captionsProperties[i];n&&(n.label=e.name,e.lang&&(n.languageCode=e.lang),n.media=e)}})}},{key:"closedCaptionsForLevel",value:function(e){var t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]}},{key:"onFragLoading",value:function(e,t){if(this.enabled&&t.frag.type===de.MAIN){var r,i,n=this.cea608Parser1,a=this.cea608Parser2,s=this.lastSn,o=t.frag,l=o.cc,u=o.sn,c=null!=(r=null==(i=t.part)?void 0:i.index)?r:-1;n&&a&&(u!==s+1||u===s&&c!==this.lastPartIndex+1||l!==this.lastCc)&&(n.reset(),a.reset()),this.lastCc=l,this.lastSn=u,this.lastPartIndex=c}}},{key:"onFragLoaded",value:function(e,t){var r,i=t.frag,n=t.payload;if(i.level<this.tracks.length&&i.type===de.SUBTITLE)if(n.byteLength||null!=(r=i.initSegment)&&null!=(r=r.data)&&r.byteLength){var a=i.decryptdata,s="stats"in t;if(null==a||!a.encrypted||s){var o=this.tracks[i.level],l=this.vttCCs;l[i.cc]||(l[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),(null==o?void 0:o.textCodec)===Tu?this._parseIMSC1(t):this._parseVTTs(t)}}else{var u="part"in t?t.part:null;this.hls.trigger(ne.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,part:u,error:new Error("Empty subtitle payload")})}}},{key:"_parseIMSC1",value:function(e){var t=this,r=e.frag,i=e.payload,n="part"in e?e.part:null,a=this.hls;Ru(i,this.initPTS[r.cc],function(e){t._appendCues(e,r.level),a.trigger(ne.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:r,part:n})},function(e){a.logger.log("Cannot parse IMSC1 (sn: ".concat(r.sn," @").concat(r.start,"): ").concat(e)),a.trigger(ne.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,part:n,error:e})})}},{key:"_parseVTTs",value:function(e){var t,r=this,i=e.frag,n=e.payload,a="part"in e?e.part:null,s=this.initPTS,o=this.unparsedVttFrags,l=s.length-1;if(s[i.cc]||-1!==l){var u=this.hls,c=null==(t=i.initSegment)?void 0:t.data;Su(c?Kt(c,new Uint8Array(n)).buffer:n,this.initPTS[i.cc],this.vttCCs,i.cc,(a&&!c?a:i).start,function(e){r._appendCues(e,i.level),u.trigger(ne.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i,part:a})},function(t){var n=t.message.startsWith("Missing initPTS");u.logger.log("".concat(n?"Deferred parsing of":"Cannot parse"," VTT cue (sn: ").concat(i.sn," @").concat(i.start,"): ").concat(t)),n?o.push(e):(r.config.enableIMSC1&&r._fallbackToIMSC1(e),u.trigger(ne.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,part:a,error:t}))})}else o.push(e)}},{key:"_fallbackToIMSC1",value:function(e){var t=this,r=e.frag,i=e.payload,n=this.tracks[r.level];n.textCodec||Ru(i,this.initPTS[r.cc],function(){n.textCodec=Tu,t._parseIMSC1(e)},function(){n.textCodec="wvtt"})}},{key:"_appendCues",value:function(e,t){var r=this.hls;if(this.config.renderTextTracksNatively){var i,n=null==(i=this.tracks[t].trackNode)?void 0:i.track;if(!n||"disabled"===n.mode)return;e.forEach(function(e){return Ou(n,e)})}else{var a=this.tracks[t];if(!a)return;var s=a.default?"default":"subtitles"+t;r.trigger(ne.CUES_PARSED,{type:"subtitles",cues:e,track:s,subtitleTrack:a})}}},{key:"onFragDecrypted",value:function(e,t){t.frag.type===de.SUBTITLE&&this.onFragLoaded(ne.FRAG_LOADED,t)}},{key:"onSubtitleTracksCleared",value:function(){this.tracks=[],this.captionsTracks={}}},{key:"onFragParsingUserdata",value:function(e,t){if(this.enabled&&this.config.enableCEA708Captions){var r=t.frag,i=t.samples;if(r.type!==de.MAIN||"NONE"!==this.closedCaptionsForLevel(r))for(var n=0;n<i.length;n++){var a=i[n].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();var s=this.extractCea608Data(a);this.cea608Parser1.addData(i[n].pts,s[0]),this.cea608Parser2.addData(i[n].pts,s[1])}}}}},{key:"onBufferAppended",value:function(e,t){if(this.config.renderTextTracksNatively){var r,i=t.type,n=t.timeRanges;if("video"===i&&null!=(r=n[i])&&r.length){var a=this.captionsTracks,s=this.cueCache;Object.keys(s).forEach(function(e){var t,r=null==(t=a[e])?void 0:t.track;if(r)for(var i=s[e],n=0;n<i.length;n++)Ou(r,i[n]);delete s[e]})}}}},{key:"onBufferFlushing",value:function(e,t){var r=t.startOffset,i=t.endOffset,n=t.endOffsetSubtitles,a=t.type,s=this.media;if(s&&!(s.currentTime<i)){if(!a||"video"===a){var o=this.captionsTracks,l=this.cueCache;Object.keys(o).forEach(function(e){return Fu(o[e].track,r,i)}),Object.keys(l).forEach(function(e){for(var t=l[e],n=t.length;n--;){var a=t[n];a.startTime>=r&&a.endTime<=i&&t.splice(n,1)}})}this.config.renderTextTracksNatively&&0===r&&void 0!==n&&this.tracks.forEach(function(e){var t,i=null==(t=e.trackNode)?void 0:t.track;i&&Fu(i,r,n)})}}},{key:"extractCea608Data",value:function(e){for(var t=[[],[]],r=31&e[0],i=2,n=0;n<r;n++){var a=e[i++],s=127&e[i++],o=127&e[i++];if(0!==s||0!==o)if(!!(4&a)){var l=3&a;0!==l&&1!==l||(t[l].push(s),t[l].push(o))}}return t}}])}();function Yc(e,t,r,i){return Math.min(t,i)-Math.max(e,r)}var zc=/\s/,Xc={newCue:function(e,t,r,i){for(var n,a,s,o,l,u=[],c=self.VTTCue||self.TextTrackCue,d=0;d<i.rows.length;d++)if(s=!0,o=0,l="",!(n=i.rows[d]).isEmpty()){for(var h,f=0;f<n.chars.length;f++)zc.test(n.chars[f].uchar)&&s?o++:(l+=n.chars[f].uchar,s=!1);n.cueStartTime=t,t===r&&(r+=1e-4),o>=16?o--:o++;var v=gu(l.trim()),g=Eu(t,r,v);null!=e&&null!=(h=e.cues)&&h.getCueById(g)||((a=new c(t,r,v)).id=g,a.line=d+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*o/32)),u.push(a))}return e&&u.length&&(u.sort(function(e,t){return"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line}),u.forEach(function(t){return Ou(e,t)})),u}},Qc=function(){return l(function e(){s(this,e),this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=0,this.config=null,this.callbacks=null,this.context=null,this.stats=new ue},[{key:"destroy",value:function(){this.callbacks=this.context=this.config=null,this.abortInternal(),this.stats=null}},{key:"load",value:function(e,t,r){var i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=r,this.loadInternal()}},{key:"abort",value:function(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.getNetworkDetails())}},{key:"loadtimeout",value:function(){if(this.config){var e=this.config.loadPolicy.timeoutRetry;if(Me(e,this.stats.retry,!0))this.retry(e);else{var t;je.warn("timeout while loading ".concat(null==(t=this.context)?void 0:t.url));var r=this.callbacks;r&&(this.abortInternal(),r.onTimeout(this.stats,this.context,this.getNetworkDetails()))}}}},{key:"retry",value:function(e){var t=this,r=this.context,i=this.stats;this.retryDelay=De(e,i.retry),i.retry++,je.warn("".concat(status?"HTTP Status "+status:"Timeout"," while loading ").concat(null==r?void 0:r.url,", retrying ").concat(i.retry,"/").concat(e.maxNumRetry," in ").concat(this.retryDelay,"ms")),this.abortInternal(),this.resetInternalLoader(),self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(function(){return t.loadInternal()},this.retryDelay)}}])}();var $c=/(\d+)-(\d+)\/(\d+)/,Jc=function(e){function t(e){var r;return s(this,t),(r=a(this,t)).fetchSetup=void 0,r.request=null,r.response=null,r.controller=null,r.fetchSetup=e.fetchSetup||Zc,r}return f(t,e),l(t,[{key:"destroy",value:function(){this.request=null,A(t,"destroy",this,3)([]),this.response=null,this.controller=null,this.fetchSetup=null}},{key:"abortInternal",value:function(){self.clearTimeout(this.retryTimeout),this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}},{key:"getNetworkDetails",value:function(){return this.response}},{key:"resetInternalLoader",value:function(){this.response=null}},{key:"loadInternal",value:function(){var e=this,t=this.config,r=this.context,i=this.stats;if(t&&r){i.loading.first=0,i.loaded=0,i.aborted=!1,this.controller=new self.AbortController;var n=function(e,t){var r={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(Ae({},e.headers))};e.rangeEnd&&r.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return r}(r,this.controller.signal),a="arraybuffer"===r.responseType,s=a?"byteLength":"length",o=t.loadPolicy,l=o.maxTimeToFirstByteMs,u=o.maxLoadTimeMs;this.request=this.fetchSetup(r,n),self.clearTimeout(this.requestTimeout),t.timeout=l&&Z(l)?l:u,this.requestTimeout=self.setTimeout(function(){e.loadtimeout()},t.timeout),(Ks(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(function(n){var s;e.response=n;var o=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(e.requestTimeout),t.timeout=u,e.requestTimeout=self.setTimeout(function(){e.loadtimeout()},u-(o-i.loading.start)),!n.ok){var l=n.status,c=n.statusText;throw new ed(c||"fetch, bad network response",l,n)}i.loading.first=o,i.total=function(e){var t=e.get("Content-Range");if(t){var r=function(e){var t=$c.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(Z(r))return r}var i=e.get("Content-Length");if(i)return parseInt(i)}(n.headers)||i.total;var d=null==(s=e.callbacks)?void 0:s.onProgress;return d&&Z(t.highWaterMark)?e.loadProgressively(n,i,r,t.highWaterMark,d):a?n.arrayBuffer():"json"===r.responseType?n.json():n.text()}).then(function(n){var a,o,l=e.response;if(!l)throw new Error("loader destroyed");self.clearTimeout(e.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);var u=n[s];u&&(i.loaded=i.total=u);var c={url:l.url,data:n,code:l.status},d=null==(a=e.callbacks)?void 0:a.onProgress;d&&!Z(t.highWaterMark)&&d(i,r,n,l),null==(o=e.callbacks)||o.onSuccess(c,i,r,l)}).catch(function(n){if(self.clearTimeout(e.requestTimeout),!i.aborted){var a,s=n&&n.code||0,o=n?n.message:null,l=t.loadPolicy.errorRetry;if(Me(l,i.retry,!1,{url:r.url,data:void 0,code:s}))e.retry(l);else je.error("".concat(s," while loading ").concat(r.url)),null==(a=e.callbacks)||a.onError({code:s,text:o},r,n?n.details:null,i)}})}}},{key:"getCacheAge",value:function(){var e=null;if(this.response){var t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}},{key:"getResponseHeader",value:function(e){return this.response?this.response.headers.get(e):null}},{key:"loadProgressively",value:function(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,n=arguments.length>4?arguments[4]:void 0,a=new ka,s=e.body.getReader(),o=function(){return s.read().then(function(s){if(s.done)return a.dataLength&&n(t,r,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));var l=s.value,u=l.length;return t.loaded+=u,u<i||a.dataLength?(a.push(l),a.dataLength>=i&&n(t,r,a.flush().buffer,e)):n(t,r,l.buffer,e),o()}).catch(function(){return Promise.reject()})};return o()}}])}(Qc);function Zc(e,t){return new self.Request(e.url,t)}var ed=function(e){function t(e,r,i){var n;return s(this,t),(n=a(this,t,[e])).code=void 0,n.details=void 0,n.code=r,n.details=i,n}return f(t,e),l(t)}(w(Error)),td=/^age:\s*[\d.]+\s*$/im,rd=function(e){function t(e){var r;return s(this,t),(r=a(this,t)).xhrSetup=void 0,r.loader=null,r.xhrSetup=e.xhrSetup||null,r}return f(t,e),l(t,[{key:"destroy",value:function(){A(t,"destroy",this,3)([]),this.loader=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:"getNetworkDetails",value:function(){return this.loader}},{key:"resetInternalLoader",value:function(){this.loader=null}},{key:"loadInternal",value:function(){var e=this,t=this.config,r=this.context;if(t&&r){var i=this.loader=new self.XMLHttpRequest,n=this.stats;n.loading.first=0,n.loaded=0,n.aborted=!1;var a=this.xhrSetup;a?Promise.resolve().then(function(){if(e.loader===i&&!e.stats.aborted)return a.call(e,i,r.url,r)}).catch(function(t){if(e.loader===i&&!e.stats.aborted)return i.open("GET",r.url,!0),a.call(e,i,r.url,r)}).then(function(){e.loader!==i||e.stats.aborted||e.openAndSendXhr(i,r,t)}).catch(function(t){var a;null==(a=e.callbacks)||a.onError({code:i.status,text:t.message},r,i,n)}):this.openAndSendXhr(i,r,t)}}},{key:"openAndSendXhr",value:function(e,t,r){e.readyState||e.open("GET",t.url,!0);var i=t.headers,n=r.loadPolicy,a=n.maxTimeToFirstByteMs,s=n.maxLoadTimeMs;if(i)for(var o in i)e.setRequestHeader(o,i[o]);t.rangeEnd&&e.setRequestHeader("Range","bytes=".concat(t.rangeStart,"-").concat(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),r.timeout=a&&Z(a)?a:s,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),e.send()}},{key:"readystatechange",value:function(){var e=this.context,t=this.loader,r=this.stats;if(e&&t){var i=t.readyState,n=this.config;if(!r.aborted&&i>=2&&(0===r.loading.first&&(r.loading.first=Math.max(self.performance.now(),r.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(r.loading.first-r.loading.start)))),4===i)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;var a=t.status,s="text"===t.responseType?t.responseText:null;if(a>=200&&a<300){var o=null!=s?s:t.response;if(null!=o){var l,u;r.loading.end=Math.max(self.performance.now(),r.loading.first);var c="arraybuffer"===t.responseType?o.byteLength:o.length;r.loaded=r.total=c,r.bwEstimate=8e3*r.total/(r.loading.end-r.loading.first);var d=null==(l=this.callbacks)?void 0:l.onProgress;d&&d(r,e,o,t);var h={url:t.responseURL,data:o,code:a};return e.rangeEnd&&c!==e.rangeEnd-e.rangeStart&&je.warn("Payload length ".concat(c," does not match requested Range: bytes=").concat(e.rangeStart,"-").concat(e.rangeEnd-1)),void(null==(u=this.callbacks)||u.onSuccess(h,r,e,t))}}var f,v=n.loadPolicy.errorRetry;if(Me(v,r.retry,!1,{url:e.url,data:void 0,code:a}))this.retry(v);else je.error("".concat(a," while loading ").concat(e.url)),null==(f=this.callbacks)||f.onError({code:a,text:t.statusText},e,t,r)}}}},{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&&td.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}}])}(Qc),id=Ie(Ie({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,loopBackBufferFlush:void 0,startOnSegmentBoundary:!1,nextAudioTrackBufferFlushForwardOffset:.25,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,skipBufferHolePadding:.1,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveMaxUnchangedPlaylistRefresh: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,appendTimeout:1/0,ignorePlaylistParsingErrors:!1,loader:rd,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,handleMpegTsVideoIntegrityErrors:"process",abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,abrSwitchInterval:0,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:pn,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,emsgKLVSchemaUri:void 0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,iframeCacheLimit:2097152,useMediaCapabilities:!0,preserveManualLevelOnError:!1,errorPenaltyExpireMs:0,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,streamController:ec,abrController:zr,bufferController:io,capLevelController:co,errorController:di,fpsController:su,id3TrackController:Wu,gapController:Bu,latencyController:Ac},{cueHandler:Xc,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:bc,subtitleTrackController:Nu,timelineController:Wc,audioStreamController:zs,audioTrackController:Js,emeController:iu,cmcdController:$l,contentSteeringController:Jl,iframeController:ac,interstitialsController:Tc});function nd(e,t,r){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');if(void 0!==t.liveMaxUnchangedPlaylistRefresh){var i=t.liveMaxUnchangedPlaylistRefresh,n=(a=i,s=2,o=1/0,Math.max(s,Math.min(a,o)));n!==i&&r.warn('hls.js config: "liveMaxUnchangedPlaylistRefresh" clamped from '.concat(i," to ").concat(n,".")),t.liveMaxUnchangedPlaylistRefresh=n}var a,s,o,l=ad(e),u=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(function(e){var i="".concat("level"===e?"playlist":e,"LoadPolicy"),n=void 0===t[i],a=[];u.forEach(function(r){var s="".concat(e,"Loading").concat(r),o=t[s];if(void 0!==o&&n){a.push(s);var u=l[i].default;switch(t[i]={default:u},r){case"TimeOut":u.maxLoadTimeMs=o,u.maxTimeToFirstByteMs=o;break;case"MaxRetry":u.errorRetry.maxNumRetry=o,u.timeoutRetry.maxNumRetry=o;break;case"RetryDelay":u.errorRetry.retryDelayMs=o,u.timeoutRetry.retryDelayMs=o;break;case"MaxRetryTimeout":u.errorRetry.maxRetryDelayMs=o,u.timeoutRetry.maxRetryDelayMs=o}}}),a.length&&r.warn('hls.js config: "'.concat(a.join('", "'),'" setting(s) are deprecated, use "').concat(i,'": ').concat(Nr(t[i])))}),Ie(Ie({},l),t)}function ad(e){return e&&"object"===R(e)?Array.isArray(e)?e.map(ad):Object.keys(e).reduce(function(t,r){return t[r]=ad(e[r]),t},{}):e}function sd(e,t){var r=e.loader;r!==Jc&&r!==rd?(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=Jc,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}var od=function(e){function t(e,r){var i;return s(this,t),(i=a(this,t,[e,"level-controller"]))._levels=[],i._firstLevel=-1,i._maxAutoLevel=-1,i._startLevel=void 0,i.currentLevel=null,i.currentLevelIndex=-1,i.manualLevelIndex=-1,i.steering=void 0,i.lastABRSwitchTime=-1,i._iframeVariants=[],i.onParsedComplete=void 0,i.steering=r,i._registerListeners(),i}return f(t,e),l(t,[{key:"_registerListeners",value:function(){var e=this.hls;e.on(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ne.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(ne.LEVEL_LOADED,this.onLevelLoaded,this),e.on(ne.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(ne.FRAG_BUFFERED,this.onFragBuffered,this),e.on(ne.ERROR,this.onError,this)}},{key:"_unregisterListeners",value:function(){var e=this.hls;e.off(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ne.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(ne.LEVEL_LOADED,this.onLevelLoaded,this),e.off(ne.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(ne.FRAG_BUFFERED,this.onFragBuffered,this),e.off(ne.ERROR,this.onError,this)}},{key:"destroy",value:function(){this._unregisterListeners(),this.steering=null,this.resetLevels(),A(t,"destroy",this,3)([])}},{key:"stopLoad",value:function(){this._levels.forEach(function(e){e.loadError=0,e.fragmentError=0}),A(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,this._iframeVariants=[]}},{key:"onManifestLoading",value:function(e,t){this.resetLevels()}},{key:"onManifestLoaded",value:function(e,t){var r=this,i=this.hls.config.preferManagedMediaSource,n=[],a={},s={},o=!1,l=!1,u=!1,c=!1;t.levels.forEach(function(e){var t=e.attrs,d=cd(e,i),h=e.audioCodec,f=e.videoCodec,v=e.imageCodec,g=e.width,p=e.height;if(d){o||(o=!(!g||!p)),l||(l=!!f),u||(u=!!h),c||(c=!!v);var m=t.CODECS,y=t["FRAME-RATE"],k=t["HDCP-LEVEL"],E=t["PATHWAY-ID"],S=t.RESOLUTION,T=t["VIDEO-RANGE"],A="".concat(E||".","-"),b="".concat(A).concat(e.bitrate,"-").concat(S,"-").concat(y,"-").concat(m,"-").concat(T,"-").concat(k);if(a[b])if(a[b].uri===e.url||e.attrs["PATHWAY-ID"])e.iframes||(a[b].addGroupId("audio",t.AUDIO),a[b].addGroupId("text",t.SUBTITLES));else{var I=s[b]+=1;e.attrs["PATHWAY-ID"]=new Array(I+1).join(".");var R=r.createLevel(e);a[b]=R,n.push(R)}else{var L=r.createLevel(e);a[b]=L,s[b]=1,n.push(L)}}else r.log('Some or all CODECS not supported "'.concat(t.CODECS,'"'))}),this.filterAndSortMediaOptions(n,t,o,l,u,c)}},{key:"createLevel",value:function(e){var t=new xr(e),r=e.supplemental;if(null!=r&&r.videoCodec&&!ud(r.videoCodec,this.hls.config.preferManagedMediaSource)){var i=new Error('SUPPLEMENTAL-CODECS not supported "'.concat(r.videoCodec,'"'));this.log(i.message),t.supportedResult=Tr(i,[])}return t}},{key:"filterAndSortMediaOptions",value:function(e,t,r,i,n,a){var s,o=this,l=[],u=[],c=e,d=(null==(s=t.stats)?void 0:s.parsing)||{},h=this.hls.config.preferManagedMediaSource;if((r||i)&&n&&(c=c.filter(function(e){var t,r=e.videoCodec,i=e.videoRange,n=e.width,a=e.height;return(!!r||!(!n||!a))&&(!!(t=i)&&Pr.indexOf(t)>-1)})),i&&a&&(c=c.filter(function(e){return!e.imageCodec})),0===c.length)return Promise.resolve().then(function(){if(o.hls){var e="no level with compatible codecs found in manifest",r=e;t.levels.length&&(r="one or more CODECS in variant not supported: ".concat(Nr(t.levels.map(function(e){return e.attrs.CODECS}).filter(function(e,t,r){return r.indexOf(e)===t}))),o.warn(r),e+=" (".concat(r,")"));var i=new Error(e);o.hls.trigger(ne.ERROR,{type:re.MEDIA_ERROR,details:ie.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:i,reason:r})}}),void(d.end=performance.now());t.audioTracks&&dd(l=t.audioTracks.filter(function(e){return!e.audioCodec||ld(e.audioCodec,h)})),t.subtitles&&dd(u=t.subtitles);var f=c.slice(0);c.sort(function(e,t){if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return Pr.indexOf(e.videoRange)-Pr.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){var i=cr(e.videoCodec),n=cr(t.videoCodec);if(i!==n)return n-i}if(e.uri===t.uri&&e.codecSet!==t.codecSet){var a=dr(e.codecSet),s=dr(t.codecSet);if(a!==s)return s-a}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0});var v=f[0];if(this.steering&&(c=this.steering.filterParsedLevels(c)).length!==f.length)for(var g=0;g<f.length;g++)if(f[g].pathwayId===c[0].pathwayId){v=f[g];break}this._levels=c;for(var p=0;p<c.length;p++)if(c[p]===v){var m;this._firstLevel=p;var y=v.bitrate,k=this.hls.bandwidthEstimate;if(this.log("manifest loaded, ".concat(c.length," level(s) found, first bitrate: ").concat(y)),void 0===(null==(m=this.hls.userConfig)?void 0:m.abrEwmaDefaultEstimate)){var E=Math.min(y,this.hls.config.abrEwmaDefaultEstimateMax);E>k&&k===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=E)}break}var S=t.iframeVariants.filter(function(e){return cd(e,h)});this._iframeVariants=S;var T=n&&!i,A=this.hls.config,b=!(!A.audioStreamController||!A.audioTrackController),I={levels:c,audioTracks:l,subtitleTracks:u,iframeVariants:S,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:i,altAudio:b&&!T&&l.some(function(e){return!!e.url})};d.end=performance.now(),this.hls.trigger(ne.MANIFEST_PARSED,I)}},{key:"iframeVariants",get:function(){return 0===this._iframeVariants.length?null:this._iframeVariants}},{key:"levels",get:function(){return 0===this._levels.length?null:this._levels}},{key:"loadLevelObj",get:function(){return this.currentLevel}},{key:"level",get:function(){return this.currentLevelIndex},set:function(e){var t=this._levels;if(0!==t.length){if(e<0||e>=t.length){var r=new Error("invalid level idx"),i=e<0;if(this.hls.trigger(ne.ERROR,{type:re.OTHER_ERROR,details:ie.LEVEL_SWITCH_ERROR,level:e,fatal:i,error:r,reason:r.message}),i)return;e=Math.min(e,t.length-1)}var n=this.currentLevelIndex,a=this.currentLevel,s=a?a.attrs["PATHWAY-ID"]:void 0,o=t[e],l=o.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=o,n!==e||!a||s!==l){this.log("Switching to level ".concat(e," (").concat(o.height?o.height+"p ":"").concat(o.videoRange?o.videoRange+" ":"").concat(o.codecSet?o.codecSet+" ":"","@").concat(o.bitrate,")").concat(l?" with Pathway "+l:""," from level ").concat(n).concat(s?" with Pathway "+s:""));var u={level:e,attrs:o.attrs,details:o.details,bitrate:o.bitrate,averageBitrate:o.averageBitrate,maxBitrate:o.maxBitrate,realBitrate:o.realBitrate,width:o.width,height:o.height,codecSet:o.codecSet,audioCodec:o.audioCodec,videoCodec:o.videoCodec,audioGroups:o.audioGroups,subtitleGroups:o.subtitleGroups,loaded:o.loaded,loadError:o.loadError,fragmentError:o.fragmentError,name:o.name,id:o.id,uri:o.uri,url:o.url,urlId:0,audioGroupIds:o.audioGroupIds,textGroupIds:o.textGroupIds};this.hls.trigger(ne.LEVEL_SWITCHING,u);var c=o.details;if(!c||c.live){var d=this.switchParams(o.uri,null==a?void 0:a.details,c);this.loadPlaylist(d)}}}}},{key:"manualLevel",get:function(){return this.manualLevelIndex},set:function(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}},{key:"firstLevel",get:function(){return this._firstLevel},set:function(e){this._firstLevel=e}},{key:"startLevel",get:function(){if(void 0===this._startLevel){var e=this.hls.config.startLevel;return void 0!==e?e:this.hls.firstAutoLevel}return this._startLevel},set:function(e){this._startLevel=e}},{key:"pathways",get:function(){return this.steering?this.steering.pathways():[]}},{key:"pathwayPriority",get:function(){return this.steering?this.steering.pathwayPriority:null},set:function(e){if(this.steering){var t=this.steering.pathways(),r=e.filter(function(e){return-1!==t.indexOf(e)});if(e.length<1)return void this.warn("pathwayPriority ".concat(e," should contain at least one pathway from list: ").concat(t));this.steering.pathwayPriority=r}}},{key:"onError",value:function(e,t){!t.fatal&&t.context&&t.context.type===ce.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}},{key:"onFragBuffered",value:function(e,t){var r=t.frag;if(r.type===de.MAIN){var i=r.elementaryStreams;if(!Object.keys(i).some(function(e){return!!i[e]}))return;var n=this._levels[r.level];null!=n&&n.loadError&&(this.log("Resetting level error count of ".concat(n.loadError," on frag buffered")),n.loadError=0)}}},{key:"onLevelLoaded",value:function(e,t){var r,i,n=t.level,a=t.details,s=t.levelInfo;if(!s)return this.warn("Invalid level index ".concat(n)),void(null!=(i=t.deliveryDirectives)&&i.skip&&(a.deltaUpdateFailed=!0));if(s===this.currentLevel||t.withoutMultiVariant){0===s.fragmentError&&(s.loadError=0);var o=s.details;o===t.details&&o.advanced&&(o=void 0),this.playlistLoaded(n,t,o)}else null!=(r=t.deliveryDirectives)&&r.skip&&(a.deltaUpdateFailed=!0)}},{key:"loadPlaylist",value:function(e){A(t,"loadPlaylist",this,3)([]),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}},{key:"loadingPlaylist",value:function(e,r){A(t,"loadingPlaylist",this,3)([e,r]);var i=this.getUrlWithDirectives(e.uri,r),n=this.currentLevelIndex,a=e.attrs["PATHWAY-ID"],s=e.details,o=null==s?void 0:s.age;this.log("Loading level index ".concat(n).concat(void 0!==(null==r?void 0:r.msn)?" at sn "+r.msn+" part "+r.part:"").concat(a?" Pathway "+a:"").concat(o&&s.live?" age "+o.toFixed(1)+(s.type&&" "+s.type||""):""," ").concat(i)),this.hls.trigger(ne.LEVEL_LOADING,{url:i,level:n,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:r||null})}},{key:"nextLoadLevel",get:function(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},set:function(e){var t=this.currentLevelIndex;if(-1===this.manualLevelIndex&&e!==t&&-1!==e){var r=this.hls.config.abrSwitchInterval;if(r>0){var i=performance.now(),n=i-this.lastABRSwitchTime,a=1e3*r;if(this.lastABRSwitchTime>-1&&n<a)return void this.warn("Preventing ABR level switch: ".concat(t," -> ").concat(e," (").concat(Math.round(n),"ms < ").concat(a,"ms / ").concat(r,"s)"));this.lastABRSwitchTime=i,this.log("Allowing ABR level switch: ".concat(t," -> ").concat(e," (").concat(Math.round(n),"ms >= ").concat(a,"ms / ").concat(r,"s)"))}}this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}},{key:"removeLevel",value:function(e){var t,r=this;if(1!==this._levels.length){var i=this._levels.filter(function(t,i){return i!==e||(r.steering&&r.steering.removeLevel(t),t===r.currentLevel&&(r.currentLevel=null,r.currentLevelIndex=-1,t.details&&t.details.fragments.forEach(function(e){return e.level=-1})),!1)});zn(i),this._levels=i,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);var n=i.length-1;this._firstLevel=Math.min(this._firstLevel,n),this._startLevel&&(this._startLevel=Math.min(this._startLevel,n)),this.hls.trigger(ne.LEVELS_UPDATED,{levels:i})}}},{key:"onLevelsUpdated",value:function(e,t){var r=t.levels;this._levels=r}},{key:"checkMaxAutoUpdated",value:function(){var e=this.hls,t=e.autoLevelCapping,r=e.maxAutoLevel,i=e.maxHdcpLevel;this._maxAutoLevel!==r&&(this._maxAutoLevel=r,this.hls.trigger(ne.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:r,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}])}(Xs);function ld(e,t){return or(e,"audio",t)}function ud(e,t){return or(e,"video",t)}function cd(e,t){var r=e.audioCodec,i=e.videoCodec;r&&(e.audioCodec=r=vr(r,t)||void 0),i&&(i=e.videoCodec=function(e){for(var t=e.split(","),r=0;r<t.length;r++){var i=t[r].split(".");i.length>2&&"avc1"===i[0]&&(t[r]="avc1.".concat(parseInt(i[1]).toString(16)).concat(("000"+parseInt(i[2]).toString(16)).slice(-4)))}return t.join(",")}(i));var n=e.unknownCodecs;return!((null==n?void 0:n.length)||0||r&&!ld(r,t)||i&&!ud(i,t))}function dd(e){var t={};e.forEach(function(e){var r=e.groupId||"";e.id=t[r]=t[r]||0,t[r]++})}var hd=function(e){function t(e,r){var i;return s(this,t),(i=a(this,t,["key-loader",r])).config=void 0,i.keyLoaderInfo={},i.emeController=null,i.config=e,i}return f(t,e),l(t,[{key:"abort",value:function(e){for(var t in this.keyLoaderInfo){var r=this.keyLoaderInfo[t].loader;if(r){var i;if(e&&e!==(null==(i=r.context)?void 0:i.frag.type))return;r.abort()}}}},{key:"destroy",value:function(){for(var e in this.keyLoaderInfo){var t=this.keyLoaderInfo[e].loader;t&&t.destroy()}this.emeController=null,this.keyLoaderInfo={}}},{key:"loadClear",value:function(e,t,r){return this.emeController?this.emeController.loadClear(e,t,r):null}},{key:"load",value:function(e,t){var r=this;return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(function(i){return r.loadInternal(e,t,i)}):this.loadInternal(e,t)}},{key:"loadInternal",value:function(e,t,r){var i=this;r&&e.setKeyFormat(r);var n=e.decryptdata;if(!n){var a=new Error(r?"Expected frag.decryptdata to be defined after setting format ".concat(r):"Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ".concat(this.emeController&&this.config.emeEnabled,")"));return Promise.reject(fd(e,ie.KEY_LOAD_ERROR,a))}var s=e;switch(n.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===n.keyFormat?this.loadKeyHTTP(s):t?t.then(function(){return i.loadKeyEME(s)}):this.loadKeyEME(s);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(s);default:return Promise.reject(fd(e,ie.KEY_LOAD_ERROR,new Error('Key supplied with unsupported METHOD: "'.concat(n.method,'"'))))}}},{key:"loadKeyEME",value:function(e){if(this.emeController&&this.config.emeEnabled){var t;if(!e.decryptdata.keyId&&null!=(t=e.initSegment)&&t.data){var r=function(e){var t=[];return Ut(e,function(e){return t.push(e.subarray(8,24))}),t}(e.initSegment.data);if(r.length){var i=r[0],n=e.decryptdata.uri;if(i.some(function(e){return 0!==e}))this.log("Using keyId found in init segment ".concat(ft(i)," keyUri: ").concat(n)),kn.setKeyIdForUri(n,i);else{var a=kn.addKeyIdForUri(n);this.log("Patching empty keyId with ".concat(ft(a)," keyUri: ").concat(n)),i=a}e.decryptdata.keyId=i}}return this.emeController.loadKey(e).then(function(){return{frag:e,keyInfo:{decryptdata:e.decryptdata}}})}return Promise.reject(fd(e,ie.KEY_LOAD_ERROR,new Error("emeEnabled with controller: ".concat(this.emeController&&this.config.emeEnabled,")"))))}},{key:"loadKeyHTTP",value:function(e){var t=this,r=e.decryptdata,i=r.uri;if(!i)return Promise.reject(fd(e,ie.KEY_LOAD_ERROR,new Error('Invalid key URI: "'.concat(i,'"'))));var n=this.keyLoaderInfo[i];if(n){if(n.decryptdata.key)return r.key=n.decryptdata.key,n.keyLoadPromise=null,Promise.resolve({frag:e,keyInfo:n});if(n.keyLoadPromise)return n.keyLoadPromise.then(function(t){return r.key=n.decryptdata.key,Ie(Ie({},t),{},{frag:e})})}this.log("Loading".concat(r.keyId?" keyId: "+ft(r.keyId):""," URI: ").concat(r.uri," from ").concat(e.type," ").concat(e.level));var a=this.config,s=new(0,a.loader)(a);e.keyLoader=s;var o=this.keyLoaderInfo[i]={decryptdata:r,keyLoadPromise:null,loader:s};return o.keyLoadPromise=new Promise(function(r,n){var l={type:ce.KEY,keyInfo:o,frag:e,responseType:"arraybuffer",url:i},u=a.keyLoadPolicy.default,c={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:function(e,i,a,s){var o=a.frag,l=a.keyInfo,u=a.url;if(!o.decryptdata||l!==t.keyLoaderInfo[u])return n(fd(o,ie.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),s));l.decryptdata.key=o.decryptdata.key=new Uint8Array(e.data),o.keyLoader=l.loader=l.keyLoadPromise=null,r({frag:o,keyInfo:l})},onError:function(r,a,s,o){t.resetLoader(a),n(fd(e,ie.KEY_LOAD_ERROR,new Error("HTTP Error ".concat(r.code," loading key ").concat(r.text)),s,Ie({url:i,data:void 0},r)))},onTimeout:function(r,i,a){t.resetLoader(i),n(fd(e,ie.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),a))},onAbort:function(r,i,a){t.resetLoader(i),n(fd(e,ie.INTERNAL_ABORTED,new Error("key loading aborted"),a))}};s.load(l,c,d)})}},{key:"resetLoader",value:function(e){var t=e.frag,r=e.keyInfo,i=e.url,n=r.loader;t.keyLoader===n&&(t.keyLoader=r.loader=r.keyLoadPromise=null),delete this.keyLoaderInfo[i],n&&n.destroy()}}])}(Be);function fd(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ie.KEY_LOAD_ERROR,r=arguments.length>2?arguments[2]:void 0,i=arguments.length>3?arguments[3]:void 0,n=arguments.length>4?arguments[4]:void 0;return new xi({type:re.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:r,networkDetails:i||null})}function vd(e){switch(e.type){case ce.AUDIO_TRACK:return de.AUDIO;case ce.SUBTITLE_TRACK:return de.SUBTITLE;default:return de.MAIN}}function gd(e,t){var r=e.url;return void 0!==r&&0!==r.indexOf("data:")||(r=t.url),r}var pd=function(){return l(function e(t){s(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(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ne.LEVEL_LOADING,this.onLevelLoading,this),e.on(ne.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(ne.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(ne.LEVELS_UPDATED,this.onLevelsUpdated,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(ne.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ne.LEVEL_LOADING,this.onLevelLoading,this),e.off(ne.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(ne.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(ne.LEVELS_UPDATED,this.onLevelsUpdated,this)}},{key:"createInternalLoader",value:function(e){var t=this.hls.config,r=t.pLoader,i=t.loader,n=new(r||i)(t);return this.loaders[e.type]=n,n}},{key:"getInternalLoader",value:function(e){return this.loaders[e.type]}},{key:"resetInternalLoader",value:function(e){this.loaders[e]&&delete this.loaders[e]}},{key:"destroyInternalLoaders",value:function(){for(var e in this.loaders){var t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}},{key:"destroy",value:function(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}},{key:"onManifestLoading",value:function(e,t){var r=t.url;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:ce.MANIFEST,url:r,deliveryDirectives:null,levelOrTrack:null})}},{key:"onLevelLoading",value:function(e,t){var r=t.id,i=t.level,n=t.pathwayId,a=t.url,s=t.deliveryDirectives,o=t.levelInfo;this.load({id:r,level:i,pathwayId:n,responseType:"text",type:ce.LEVEL,url:a,deliveryDirectives:s,levelOrTrack:o})}},{key:"onAudioTrackLoading",value:function(e,t){var r=t.id,i=t.groupId,n=t.url,a=t.deliveryDirectives,s=t.track;this.load({id:r,groupId:i,level:null,responseType:"text",type:ce.AUDIO_TRACK,url:n,deliveryDirectives:a,levelOrTrack:s})}},{key:"onSubtitleTrackLoading",value:function(e,t){var r=t.id,i=t.groupId,n=t.url,a=t.deliveryDirectives,s=t.track;this.load({id:r,groupId:i,level:null,responseType:"text",type:ce.SUBTITLE_TRACK,url:n,deliveryDirectives:a,levelOrTrack:s})}},{key:"onLevelsUpdated",value:function(e,t){var r=this.loaders[ce.LEVEL];if(r){var i=r.context;i&&!t.levels.some(function(e){return e===i.levelOrTrack})&&(r.abort(),delete this.loaders[ce.LEVEL])}}},{key:"load",value:function(e){var t,r,i,n=this,a=this.hls.config,s=this.getInternalLoader(e);if(s){var o=this.hls.logger,l=s.context;if((null==l?void 0:l.levelOrTrack)===e.levelOrTrack&&(l.url===e.url||l.deliveryDirectives&&!e.deliveryDirectives))return void(l.url===e.url?o.log("[playlist-loader]: ignore ".concat(e.url," ongoing request")):o.log("[playlist-loader]: ignore ".concat(e.url," in favor of ").concat(l.url)));o.log("[playlist-loader]: aborting previous loader for type: ".concat(e.type)),s.abort()}if((r=e.type===ce.MANIFEST?a.manifestLoadPolicy.default:Ae({},a.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),Z(null==(t=e.deliveryDirectives)?void 0:t.part))&&(e.type===ce.LEVEL&&null!==e.level?i=this.hls.levels[e.level].details:e.type===ce.AUDIO_TRACK&&null!==e.id?i=this.hls.audioTracks[e.id].details:e.type===ce.SUBTITLE_TRACK&&null!==e.id&&(i=this.hls.subtitleTracks[e.id].details),i)){var u=i.partTarget,c=i.targetduration;if(u&&c){var d=1e3*Math.max(3*u,.8*c);r=Ae({},r,{maxTimeToFirstByteMs:Math.min(d,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(d,r.maxTimeToFirstByteMs)})}}var h=r.errorRetry||r.timeoutRetry||{},f={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:h.maxNumRetry||0,retryDelay:h.retryDelayMs||0,maxRetryDelay:h.maxRetryDelayMs||0},v={onSuccess:function(e,t,r,i){var a=n.getInternalLoader(r);n.resetInternalLoader(r.type);var s=e.data;t.parsing.start=performance.now(),Rn.isMediaPlaylist(s)||r.type!==ce.MANIFEST?n.handleTrackOrLevelPlaylist(e,t,r,i||null,a):n.handleMasterPlaylist(e,t,r,i)},onError:function(e,t,r,i){n.handleNetworkError(t,r,!1,e,i)},onTimeout:function(e,t,r){n.handleNetworkError(t,r,!0,void 0,e)}};s.load(e,f,v)}},{key:"checkAutostartLoad",value:function(){if(this.hls){var e=this.hls,t=e.config,r=t.autoStartLoad,i=t.startPosition,n=e.forceStartLoad;(r||n)&&(this.hls.logger.log("".concat(r?"auto":"force"," startLoad with configured startPosition ").concat(i)),this.hls.startLoad(i))}}},{key:"handleMasterPlaylist",value:function(e,t,r,i){var n=this,a=this.hls,s=e.data,o=gd(e,r),l=Rn.parseMasterPlaylist(s,o);if(l.playlistParsingError)return t.parsing.end=performance.now(),void this.handleManifestParsingError(e,r,l.playlistParsingError,i,t);var u=l.contentSteering,c=l.levels,d=l.iframeVariants,h=l.sessionData,f=l.sessionKeys,v=l.startTimeOffset,g=l.variableList;this.variableList=g,c.forEach(function(e){var t=e.unknownCodecs;if(t)for(var r=n.hls.config.preferManagedMediaSource,i=e.audioCodec,a=e.videoCodec,s=t.length;s--;){var o=t[s];or(o,"audio",r)?(e.audioCodec=i=i?"".concat(i,",").concat(o):o,ar.audio[i.substring(0,4)]=2,t.splice(s,1)):or(o,"video",r)&&(e.videoCodec=a=a?"".concat(a,",").concat(o):o,ar.video[a.substring(0,4)]=2,t.splice(s,1))}});var p=Rn.parseMasterPlaylistMedia(s,o,l),m=p.AUDIO,y=void 0===m?[]:m,k=p.SUBTITLES,E=p["CLOSED-CAPTIONS"];y.length&&(y.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"),y.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Wi({}),bitrate:0,url:""})));a.trigger(ne.MANIFEST_LOADED,{levels:c,audioTracks:y,subtitles:k,iframeVariants:d,captions:E,contentSteering:u,url:o,stats:t,networkDetails:i,sessionData:h,sessionKeys:f,startTimeOffset:v,variableList:g})}},{key:"handleTrackOrLevelPlaylist",value:function(e,t,r,i,n){var a=this.hls,s=r.id,o=r.level,l=r.type,u=gd(e,r),c=Z(o)?o:Z(s)?s:0,d=vd(r),h=Rn.parseLevelPlaylist(e.data,u,c,d,0,this.variableList);if(l===ce.MANIFEST){var f={attrs:new Wi({}),bitrate:0,details:h,name:"",url:u};h.requestScheduled=t.loading.start+jn(h,0),a.trigger(ne.MANIFEST_LOADED,{levels:[f],audioTracks:[],iframeVariants:[],url:u,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),r.levelDetails=h,this.handlePlaylistLoaded(h,e,t,r,i,n)}},{key:"handleManifestParsingError",value:function(e,t,r,i,n){this.hls.trigger(ne.ERROR,{type:re.NETWORK_ERROR,details:ie.MANIFEST_PARSING_ERROR,fatal:t.type===ce.MANIFEST,url:e.url,err:r,error:r,reason:r.message,response:e,context:t,networkDetails:i,stats:n})}},{key:"handleNetworkError",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=arguments.length>3?arguments[3]:void 0,n=arguments.length>4?arguments[4]:void 0,a="A network ".concat(r?"timeout":"error"+(i?" (status "+i.code+")":"")," occurred while loading ").concat(e.type);e.type===ce.LEVEL?a+=": ".concat(e.level," id: ").concat(e.id):e.type!==ce.AUDIO_TRACK&&e.type!==ce.SUBTITLE_TRACK||(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=ie.UNKNOWN,l=!1,u=this.getInternalLoader(e);switch(e.type){case ce.MANIFEST:o=r?ie.MANIFEST_LOAD_TIMEOUT:ie.MANIFEST_LOAD_ERROR,l=!0;break;case ce.LEVEL:o=r?ie.LEVEL_LOAD_TIMEOUT:ie.LEVEL_LOAD_ERROR,l=!1;break;case ce.AUDIO_TRACK:o=r?ie.AUDIO_TRACK_LOAD_TIMEOUT:ie.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case ce.SUBTITLE_TRACK:o=r?ie.SUBTITLE_TRACK_LOAD_TIMEOUT:ie.SUBTITLE_LOAD_ERROR,l=!1}u&&this.resetInternalLoader(e.type);var c={type:re.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:u,context:e,error:s,networkDetails:t,stats:n};if(i){var d=e.url;t&&"url"in t&&(d=t.url),c.response=Ie({url:d,data:void 0},i)}this.hls.trigger(ne.ERROR,c)}},{key:"handlePlaylistLoaded",value:function(e,t,r,i,n,a){var s=this.hls,o=i.type,l=i.level,u=i.levelOrTrack,c=i.id,d=i.groupId,h=i.deliveryDirectives,f=gd(t,i),v=vd(i),g="number"==typeof i.level&&v===de.MAIN?l:void 0;u&&"iframes"in u&&u.iframes&&!e.iframesOnly&&(e.playlistParsingError=new Error("EXT-X-I-FRAME-STREAM-INF media playlist MUST contain an EXT-X-I-FRAMES-ONLY tag"),e.iframesOnly=!0);var p=e.playlistParsingError;if(p){if(this.hls.logger.warn("".concat(p," ").concat(e.url)),!s.config.ignorePlaylistParsingErrors)return void s.trigger(ne.ERROR,{type:re.NETWORK_ERROR,details:ie.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:p,reason:p.message,response:t,context:i,level:g,parent:v,networkDetails:n,stats:r});e.playlistParsingError=null}if(e.fragments.length)switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),a.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case ce.MANIFEST:case ce.LEVEL:if(g)if(u){if(u!==s.levels[g]){var m=s.levels.indexOf(u);m>-1&&(g=m)}}else g=0;s.trigger(ne.LEVEL_LOADED,{details:e,levelInfo:u||s.levels[0],level:g||0,id:c||0,stats:r,networkDetails:n,deliveryDirectives:h,withoutMultiVariant:o===ce.MANIFEST,context:i});break;case ce.AUDIO_TRACK:s.trigger(ne.AUDIO_TRACK_LOADED,{details:e,track:u,id:c||0,groupId:d||"",stats:r,networkDetails:n,deliveryDirectives:h,context:i});break;case ce.SUBTITLE_TRACK:s.trigger(ne.SUBTITLE_TRACK_LOADED,{details:e,track:u,id:c||0,groupId:d||"",stats:r,networkDetails:n,deliveryDirectives:h,context:i})}else{var y=e.playlistParsingError=new Error("No Segments found in Playlist");s.trigger(ne.ERROR,{type:re.NETWORK_ERROR,details:ie.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:y,reason:y.message,response:t,context:i,level:g,parent:v,networkDetails:n,stats:r})}}}])}(),md=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};s(this,e),this.config=void 0,this.userConfig=void 0,this.logger=void 0,this._url=null,this.streamController=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Aa,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.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.iframeController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;var r=this.logger=function(e,t,r){var i=Ge();if("object"===("undefined"==typeof console?"undefined":R(console))&&!0===e||"object"===R(e)){var n=["debug","log","info","warn","error"];n.forEach(function(t){i[t]=He(t,e,r)});try{i.log('Debug logs enabled for "'.concat(t,'" in hls.js version ',"1.7.3"))}catch(e){return Ge()}n.forEach(function(t){Ke[t]=He(t,e)})}else Ae(Ke,i);return i}(t.debug||!1,"Hls instance",t.loggerId||t.assetPlayerId),i=this.config=nd(e.DefaultConfig,t,r);this.userConfig=t,i.progressive&&sd(i,r);var n=i.streamController,a=i.abrController,o=i.bufferController,l=i.capLevelController,u=i.errorController,c=i.fpsController,d=i.id3TrackController,h=i.iframeController,f=i.gapController,v=new u(this),g=this.abrController=new a(this),p=new ki(this),m=i.interstitialsController,y=m?this.interstitialsController=new m(this,e):null,k=o?this.bufferController=new o(this,p):null,E=l?this.capLevelController=new l(this):null,S=c?new c(this):null,T=i.cmcdController,A=T?this.cmcdController=new T(this):null,b=new pd(this),I=i.contentSteeringController,L=I?new I(this):null,P=this.levelController=new od(this,L),w=d?new d(this):void 0,C=new hd(this.config,this.logger),D=this.streamController=new n(this,p,C),_=this.gapController=f?new f(this,p):void 0;E&&E.setStreamController(D);var M=[b,P,D];y&&M.splice(1,0,y),L&&M.splice(1,0,L),this.networkControllers=M;var x=[g];k&&x.push(k),_&&x.push(_),E&&x.push(E),S&&(S.setStreamController(D),x.push(S)),w&&x.push(w),x.push(p),this.audioTrackController=this.createController(i.audioTrackController,M);var O=i.audioStreamController;O&&M.push(this.audioStreamController=new O(this,p,C)),this.subtitleTrackController=this.createController(i.subtitleTrackController,M);var F=i.subtitleStreamController;F&&M.push(this.subtititleStreamController=new F(this,p,C)),this.createController(i.timelineController,x),C.emeController=this.emeController=this.createController(i.emeController,x),A&&x.push(A),this.latencyController=this.createController(i.latencyController,x),this.coreComponents=x,this.iframeController=h?new h(this,e):void 0,M.push(v);var N=v.onErrorOut;"function"==typeof N&&this.on(ne.ERROR,N,v),this.on(ne.MANIFEST_LOADED,b.onManifestLoaded,b)}return l(e,[{key:"createController",value:function(e,t){if(e){var r=new e(this);return t&&t.push(r),r}return null}},{key:"on",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this;this._emitter.on(e,t,r)}},{key:"once",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this;this._emitter.once(e,t,r)}},{key:"removeAllListeners",value:function(e){this._emitter.removeAllListeners(e)}},{key:"off",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this,i=arguments.length>3?arguments[3]:void 0;this._emitter.off(e,t,r,i)}},{key:"listeners",value:function(e){return this._emitter.listeners(e)}},{key:"emit",value:function(e,t,r){return this._emitter.emit(e,t,r)}},{key:"trigger",value:function(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),!this.triggeringException){this.triggeringException=!0;var r=e===ne.ERROR;this.trigger(ne.ERROR,{type:re.OTHER_ERROR,details:ie.INTERNAL_EXCEPTION,fatal:r,event:e,error:t}),this.triggeringException=!1}}return!1}},{key:"listenerCount",value:function(e){return this._emitter.listenerCount(e)}},{key:"destroy",value:function(){this.logger.log("destroy"),this.trigger(ne.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,this.iframeController=void 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(ne.ERROR,{type:re.OTHER_ERROR,details:ie.ATTACH_MEDIA_ERROR,fatal:!0,error:t})}else{this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());var r="media"in e,i=r?e.media:e,n=r?e:{media:i};this._media=i,this.trigger(ne.MEDIA_ATTACHING,n)}}},{key:"detachMedia",value:function(){this.logger.log("detachMedia");var e={};this.trigger(ne.MEDIA_DETACHING,e),this._media=null,this.trigger(ne.MEDIA_DETACHED,e)}},{key:"transferMedia",value:function(){var e;this._media=null;var t=(null==(e=this.bufferController)?void 0:e.transferMedia())||null,r={transferMedia:t};return this.trigger(ne.MEDIA_DETACHING,r),this.trigger(ne.MEDIA_DETACHED,r),t}},{key:"loadSource",value:function(e){var t;this.stopLoad();var r=this.media,i=this._url,n=this._url=le.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log("loadSource:".concat(n)),r&&i&&(i!==n||null!=(t=this.bufferController)&&t.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(r)),this.trigger(ne.MANIFEST_LOADING,{url:e})}},{key:"url",get:function(){return this._url}},{key:"hasEnoughToStart",get:function(){return this.streamController.hasEnoughToStart}},{key:"startPosition",get:function(){return this.streamController.startPositionValue}},{key:"startLoad",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:-1,t=arguments.length>1?arguments[1]:void 0;this.logger.log("startLoad(".concat(e+(t?", <skip seek to start>":""),")")),this.started=!0,this.resumeBuffering();for(var r=0;r<this.networkControllers.length&&(this.networkControllers[r].startLoad(e,t),this.started&&this.networkControllers);r++);}},{key:"stopLoad",value:function(){this.logger.log("stopLoad"),this.started=!1;for(var e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!this.started&&this.networkControllers);e++);}},{key:"loadingEnabled",get:function(){return this.started&&this.streamController.state!==na}},{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=c({},de.MAIN,this.streamController.inFlightFrag);return this.audioStreamController&&(e[de.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[de.SUBTITLE]=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=this.started,r=null==e?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&(r?this.startLoad(r):this.config.autoStartLoad||this.startLoad()))}},{key:"removeLevel",value:function(e){this.levelController.removeLevel(e)}},{key:"sessionId",get:function(){var e=this._sessionId;return e||(e=this._sessionId=Je()),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=this.capLevelController,r=!!e;t&&r!==this.config.capLevelToPlayerSize&&(r?t.startCapping():(t.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=r)}},{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 Lr.indexOf(e)>-1})(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}},{key:"autoLevelEnabled",get:function(){return-1===this.levelController.manualLevel}},{key:"manualLevel",get:function(){return this.levelController.manualLevel}},{key:"minAutoLevel",get:function(){var e=this.levels,t=this.config.minAutoBitrate;if(!e)return 0;for(var r=e.length,i=0;i<r;i++)if(e[i].maxBitrate>=t)return i;return 0}},{key:"maxAutoLevel",get:function(){var e,t=this.levels,r=this.autoLevelCapping,i=this.maxHdcpLevel;if(e=-1===r&&null!=t&&t.length?t.length-1:r,i)for(var n=e;n--;){var a=t[n].attrs["HDCP-LEVEL"];if(a&&a<=i)return n}return e}},{key:"firstAutoLevel",get:function(){return this.abrController.firstAutoLevel}},{key:"nextAutoLevel",get:function(){return this.abrController.nextAutoLevel},set:function(e){this.abrController.nextAutoLevel=e}},{key:"playingDate",get:function(){return this.streamController.currentProgramDateTime}},{key:"mainForwardBufferInfo",get:function(){return this.streamController.getMainFwdBufferInfo()}},{key:"audioForwardBufferInfo",get:function(){var e;return(null==(e=this.audioStreamController)?void 0:e.getFwdBufferInfo())||null}},{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:"nextAudioTrack",get:function(){var e,t;return null!=(e=null==(t=this.audioStreamController)?void 0:t.nextAudioTrack)?e:-1},set:function(e){var t=this.audioTrackController;t&&(t.nextAudioTrack=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(){var e,t;return null!=(e=null==(t=this.latencyController)?void 0:t.liveSyncPosition)?e:null}},{key:"latency",get:function(){var e;return(null==(e=this.latencyController)?void 0:e.latency)||0}},{key:"maxLatency",get:function(){var e;return(null==(e=this.latencyController)?void 0:e.maxLatency)||0}},{key:"targetLatency",get:function(){var e;return(null==(e=this.latencyController)?void 0:e.targetLatency)||null},set:function(e){this.latencyController&&(this.latencyController.targetLatency=e)}},{key:"drift",get:function(){var e;return(null==(e=this.latencyController)?void 0:e.drift)||null}},{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(){return this.interstitialsController?this.interstitialsController.interstitialsManager:null}},{key:"iframeVariants",get:function(){var e=this.levelController.iframeVariants;return e||[]}},{key:"createIFramePlayer",value:function(e){return this._url&&this.iframeController?this.iframeController.createIFramePlayer(e):null}},{key:"createImageIFramePlayer",value:function(e){return this._url&&this.iframeController?this.iframeController.createImageIFramePlayer(e):null}},{key:"getMediaDecodingInfo",value:function(e){return Ar(e,Ur(arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.allAudioTracks),navigator.mediaCapabilities)}}],[{key:"version",get:function(){return ba}},{key:"isMSESupported",value:function(){return zu()}},{key:"isSupported",value:function(){return function(){if(!zu())return!1;var e=qe();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(ur(t,"video"))})||["mp4a.40.2","fLaC"].some(function(t){return e.isTypeSupported(ur(t,"audio"))}))}()}},{key:"getMediaSource",value:function(){return qe()}},{key:"Events",get:function(){return ne}},{key:"MetadataSchema",get:function(){return xa}},{key:"ErrorTypes",get:function(){return re}},{key:"ErrorDetails",get:function(){return ie}},{key:"DefaultConfig",get:function(){return e.defaultConfig?e.defaultConfig:id},set:function(t){e.defaultConfig=t}}])}();function yd(){var e,t,r,i=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=function(e){var t=e.match(/Chrome\/(\d+)/);return t&&t[1]?parseInt(t[1],10):0}(i),h=function(e){var t=e.match(/AppleWebKit\/(\d+)/);return t&&t[1]?parseInt(t[1],10):0}(i);if(r=d>0?d:void 0,/Web0S|webOS|LG Browser|LGSTB/i.test(i)){if(a="LG WebOS",l=!0,(f=i.match(/Web0S[/\s]*([\d.]+)/i)||i.match(/webOS[/\s]*([\d.]+)/i))&&f[1]||(f=i.match(/webOSTV[/\s-]*([\d.]+)/i)||i.match(/webOS\.TV[/\s-]*([\d.]+)/i)),f&&f[1])e=o=(v=(s=f[1]).split("."))[0]?parseInt(v[0],10):0;else d>0?d>=79?(e=6,s="6.0",o=6):d>=68?(e=5,s="5.0",o=5):d>=53?(e=4,s="4.0",o=4):d>=38?(e=3,s="3.0",o=3):(e=2,s="2.0",o=2):(s="Unknown",e=void 0);u=void 0!==e&&e<3}else if(/Tizen/i.test(i)){var f,v;if(a="Samsung Tizen",l=!0,"Unknown"!==(s=(f=i.match(/Tizen[/\s]*([\d.]+)/i))&&f[1]?f[1]:"Unknown"))t=o=(v=s.split("."))[0]?parseInt(v[0],10):0;u=void 0!==t&&t<3}else/SMART-TV|SmartTV/i.test(i)?(a="Smart TV",l=!0,u=d>0&&d<53):/NetCast/i.test(i)?(a="LG NetCast",l=!0,u=!0):/BRAVIA/i.test(i)?(a="Sony BRAVIA",l=!0,u=d>0&&d<53):(d>0&&(a="Chrome",s=d.toString(),o=d,d<50&&(c=!1)),h>0&&h<600&&(c=!1));return"undefined"!=typeof Promise&&"undefined"!=typeof Map&&"undefined"!=typeof Set||(c=!1),"undefined"==typeof URLSearchParams&&(c=!1),{name:a,version:s,majorVersion:o,isSmartTV:l,isLegacyTV:u,platform:n,supportsModernJS:c,webOSVersion:e,tizenVersion:t,chromeVersion:r}}function kd(){var e,t=yd();return"Samsung Tizen"===t.name&&(null!==(e=t.tizenVersion)&&void 0!==e?e:0)>=5}function Ed(){var e={};return yd().isSmartTV&&(e.allowNativeHls=!0,e.pauseContentDuringAds=!0),e}function Sd(e){if(void 0===e&&(e=!1),e){var t=yd();console.log("[StormcloudVideoPlayer] Browser Compatibility Info:",_(_(_(_({browser:"".concat(t.name," ").concat(t.version),platform:t.platform,isSmartTV:t.isSmartTV,isLegacyTV:t.isLegacyTV,supportsModernJS:t.supportsModernJS},void 0!==t.webOSVersion?{webOSVersion:t.webOSVersion}:{}),void 0!==t.tizenVersion?{tizenVersion:t.tizenVersion}:{}),void 0!==t.chromeVersion?{chromeVersion:t.chromeVersion}:{}),{userAgent:navigator.userAgent}))}}md.defaultConfig=void 0;var Td=/\[([A-Z][A-Z0-9_]*)\]/g,Ad=/\[CACHEBUSTER\]|\[cachebuster\]|\[timestamp\]|\[random\]|\[INSERT_RANDOM_NUMBER\]|%%CACHEBUSTER%%|%%CACHEBUST%%|\$\{CACHEBUSTER\}|\$\{CACHEBUSTING\}|\{cachebuster\}|\{random\}/g,bd=new Set(["ADCATEGORIES","ADCOUNT","ADPLAYHEAD","ADSERVINGID","ADTYPE","APIFRAMEWORKS","APPBUNDLE","ASSETURI","BLOCKEDADCATEGORIES","BREAKMAXADLENGTH","BREAKMAXADS","BREAKMAXDURATION","BREAKMINADLENGTH","BREAKPOSITION","CACHEBUSTING","CLICKPOS","CLICKTYPE","CLIENTUA","CONTENTID","CONTENTPLAYHEAD","CONTENTURI","DEVICEIP","DEVICEUA","DOMAIN","ERRORCODE","EXTENSIONS","GDPRCONSENT","IFA","IFATYPE","INVENTORYSTATE","LATLONG","LIMITADTRACKING","MEDIAMIME","MEDIAPLAYHEAD","OMIDPARTNER","PAGEURL","PLACEMENTTYPE","PLAYERCAPABILITIES","PLAYERSIZE","PLAYERSTATE","PODSEQUENCE","REASON","REGULATIONS","SERVERSIDE","SERVERUA","TIMESTAMP","TRANSACTIONID","UNIVERSALADID","VASTVERSIONS","VERIFICATIONVENDORS"]);function Id(){return String(Math.floor(9e7*Math.random())+1e7)}function Rd(e){if(null!=e&&Number.isFinite(e)&&!(e<0)){var t=Math.floor(e),r=String(Math.floor(t/3600)).padStart(2,"0"),i=String(Math.floor(t%3600/60)).padStart(2,"0"),n=String(t%60).padStart(2,"0"),a=String(Math.floor(1e3*(e-t))).padStart(3,"0");return"".concat(r,":").concat(i,":").concat(n,".").concat(a)}}function Ld(e,t){if(void 0===t&&(t={}),!e)return e;var r=function(e){var t=new Map,r=function(e,r){null!=r&&""!==r&&t.set(e,r)},i=Rd(e.adPlayheadSeconds);if(r("ADPLAYHEAD",i),r("MEDIAPLAYHEAD",i),r("CONTENTPLAYHEAD",Rd(e.contentPlayheadSeconds)),r("ASSETURI",e.assetUri),r("MEDIAMIME",e.mediaMime),r("TIMESTAMP",(new Date).toISOString()),r("SERVERSIDE","0"),null!=e.errorCode&&""!==e.errorCode&&r("ERRORCODE",String(e.errorCode)),null!=e.playerWidth&&null!=e.playerHeight&&r("PLAYERSIZE","".concat(Math.round(e.playerWidth),",").concat(Math.round(e.playerHeight))),r("IFA",e.deviceId),r("IFATYPE",e.deviceIdType),null!=e.limitAdTracking&&r("LIMITADTRACKING",e.limitAdTracking?"1":"0"),r("PAGEURL",e.pageUrl),e.pageUrl)try{r("DOMAIN",new URL(e.pageUrl).hostname)}catch(e){}return r("CLIENTUA",e.clientUa),r("DEVICEUA",e.clientUa),null!=e.podSequence&&r("PODSEQUENCE",String(e.podSequence)),r("ADSERVINGID",e.adServingId),null!=e.reason&&""!==e.reason&&r("REASON",String(e.reason)),t}(t);return e.replace(Ad,function(){return Id()}).replace(Td,function(e,t){if("CACHEBUSTING"===t)return Id();var i=r.get(t);return null!=i?encodeURIComponent(i):bd.has(t)?"":e})}var Pd=["creativeView","loaded","start","firstQuartile","midpoint","thirdQuartile","complete","mute","unmute","pause","resume","fullscreen","exitFullscreen","playerExpand","playerCollapse","notUsed"];function wd(e){var t,r=null===(t=null==e?void 0:e.textContent)||void 0===t?void 0:t.trim();return r||void 0}function Cd(e){if(e){var t=e.trim().split(":");if(3===t.length){var r=N(t.map(function(e){return parseFloat(e)}),3),i=r[0],n=r[1],a=r[2];if([i,n,a].every(function(e){return void 0!==e&&Number.isFinite(e)}))return 3600*i+60*n+a}}}var Dd=new Set,_d=405;function Md(e,t){var r,i,n,a,s,o,l,u,c=!1,d=!1,h=Math.max(0,Math.min(1,e.volume||1)),f=new Map,v=null==t?void 0:t.mainHlsInstance,g="__stormcloudAdContainer",p="__stormcloudAdVideo",m="__stormcloudFrameCounterReliable",y="__stormcloudRvfcReliable",k=null!==(r=e[p])&&void 0!==r?r:void 0,E=null!==(i=e[g])&&void 0!==i?i:void 0,S=[],T=[],A=[],b=0,I=new Map,R=new Map,L=[],P=0,w=0,C=!1;function D(){return{impression:!1,loaded:!1,start:!1,firstQuartile:!1,midpoint:!1,thirdQuartile:!1,complete:!1,viewabilitySettled:!1,lastMuted:void 0,progressFired:new Set}}var M,N,B=D(),U=new Set,V=0,G=0,H=!1,K=[];function j(e,t){var r,i,n=f.get(e);if(n)try{for(var a=F(Array.from(n)),s=a.next();!s.done;s=a.next()){var o=s.value;try{o(t)}catch(t){console.warn("[HlsAdPlayer] Error in event listener for ".concat(e,":"),t)}}}catch(e){r={error:e}}finally{try{s&&!s.done&&(i=a.return)&&i.call(a)}finally{if(r)throw r.error}}}function q(t,r){if(t&&0!==t.length){var i=function(t){var r;void 0===t&&(t={});var i=t.errorCode,n=t.reason,o=null!==(r=t.ad)&&void 0!==r?r:a,l={adPlayheadSeconds:null==k?void 0:k.currentTime,contentPlayheadSeconds:e.currentTime,assetUri:null==s?void 0:s.url,mediaMime:null==s?void 0:s.type,playerWidth:(null==k?void 0:k.clientWidth)||(null==E?void 0:E.clientWidth),playerHeight:(null==k?void 0:k.clientHeight)||(null==E?void 0:E.clientHeight)};return null!=i&&(l.errorCode=i),"undefined"!=typeof navigator&&navigator.userAgent&&(l.clientUa=navigator.userAgent),"undefined"!=typeof location&&location.href&&(l.pageUrl=location.href),A.length>0&&(l.podSequence=b+1),(null==o?void 0:o.adServingId)&&(l.adServingId=o.adServingId),null!=n&&(l.reason=n),l}(r);t.forEach(function(e){try{var t,r=Ld(e,i),n=new Image(1,1);Dd.add(n);var a=function(){void 0!==t&&clearTimeout(t),n.onload=null,n.onerror=null,Dd.delete(n)};n.onload=a,n.onerror=a,t=setTimeout(a,3e4),n.src=r,console.log("[HlsAdPlayer] Fired tracking pixel: ".concat(r))}catch(e){console.warn("[HlsAdPlayer] Error firing tracking pixel:",e)}})}}function W(e){if(0===e.length)throw new Error("No media files available");var t=e[0];if(!t)throw new Error("No media files available");if(1===e.length)return t;var r=function(){if(!v||!v.levels)return null;var e=v.currentLevel;if(-1===e||!v.levels[e]){var t=v.loadLevel;if(-1!==t&&v.levels[t]){var r=v.levels[t];return{width:r.width||1920,height:r.height||1080,bitrate:r.bitrate||5e6}}return null}var i=v.levels[e];return{width:i.width||1920,height:i.height||1080,bitrate:i.bitrate||5e6}}();if(!r)return console.log("[HlsAdPlayer] No main stream quality info, using first media file"),t;console.log("[HlsAdPlayer] Main stream quality:",r);var i=e.map(function(e){var t=Math.abs(e.width-r.width)+Math.abs(e.height-r.height),i=1e3*(e.bitrate||5e3),n=Math.abs(i-r.bitrate);return{file:e,score:2*t+n/1e3,resolutionDiff:t,bitrateDiff:n}});i.sort(function(e,t){return e.score-t.score});var n=i[0];return n?(console.log("[HlsAdPlayer] Selected media file:",{url:n.file.url,resolution:"".concat(n.file.width,"x").concat(n.file.height),bitrate:n.file.bitrate,score:n.score,resolutionDiff:n.resolutionDiff,bitrateDiff:n.bitrateDiff}),n.file):(console.log("[HlsAdPlayer] No best match found, using first media file"),t)}function Y(e){var t=e.type.toLowerCase(),r=e.url.toLowerCase();return"application/x-mpegurl"===t||"application/vnd.apple.mpegurl"===t||t.includes("mpegurl")||r.includes(".m3u8")}function z(e){var t=e.type.toLowerCase(),r=e.url.toLowerCase();return t.startsWith("video/")||r.endsWith(".mp4")||r.includes(".mp4?")}function X(e,t){var r=e.querySelectorAll(":scope > MediaFiles > MediaFile"),i=[];return t&&console.log("[HlsAdPlayer] Found ".concat(r.length," MediaFile element(s) in VAST XML")),r.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(t&&console.log("[HlsAdPlayer] MediaFile ".concat(r,': type="').concat(a,'", url="').concat(s,'", width="').concat(o,'", height="').concat(l,'"')),s)if("VPAID"!==(e.getAttribute("apiFramework")||"").toUpperCase()){var u=e.getAttribute("bitrate"),c=u?parseInt(u,10):void 0,d={url:s,type:a,width:parseInt(o||"1920",10),height:parseInt(l||"1080",10),bitrate:c&&c>0?c:void 0};if(function(e){var t=e.type.toLowerCase(),r=(e.url.toLowerCase().split("?")[0]||"").trim();return t.startsWith("audio/")||r.endsWith(".mp3")||r.endsWith(".aac")||r.endsWith(".m4a")||r.endsWith(".ogg")||r.endsWith(".oga")||r.endsWith(".opus")||r.endsWith(".wav")||r.endsWith(".weba")}(d))console.warn("[HlsAdPlayer] MediaFile ".concat(r,' skipped (audio-only, type="').concat(a,'") — audio ads are not played to avoid a black screen'));else{var h=null!=e.getAttribute("width")&&null!=e.getAttribute("height");!Y(d)&&h&&(d.width<=1||d.height<=1)?console.warn("[HlsAdPlayer] MediaFile ".concat(r," skipped (degenerate dimensions ").concat(d.width,"x").concat(d.height,', type="').concat(a,'") — likely an audio-only placeholder rendition')):Y(d)||z(d)?(i.push(d),t&&console.log("[HlsAdPlayer] Added ".concat(Y(d)?"HLS":"progressive"," MediaFile: ").concat(s))):t&&console.log("[HlsAdPlayer] MediaFile ".concat(r,' ignored (type="').concat(a,'" is not supported)'))}}else t&&console.log("[HlsAdPlayer] MediaFile ".concat(r," ignored (VPAID creatives are not supported)"));else t&&console.warn("[HlsAdPlayer] MediaFile ".concat(r," has empty URL"))}),i}function Q(){var e,t,r={impression:[],clickTracking:[],error:[],viewable:[],notViewable:[],viewUndetermined:[],verificationNotExecuted:[],progress:[]};try{for(var i=F(Pd),n=i.next();!n.done;n=i.next()){r[n.value]=[]}}catch(t){e={error:t}}finally{try{n&&!n.done&&(t=i.return)&&t.call(i)}finally{if(e)throw e.error}}return r}function $(e,t){t.forEach(function(t){var r=wd(t);r&&e.push(r)})}function J(e,t){e.querySelectorAll(":scope > TrackingEvents > Tracking").forEach(function(e){var r=e.getAttribute("event"),i=wd(e);if(r&&i)if("progress"!==r)-1!==Pd.indexOf(r)&&t[r].push(i);else{var n=function(e){if(e){var t=e.trim();if(t.endsWith("%")){var r=parseFloat(t);return Number.isFinite(r)?{offsetPercent:r}:void 0}var i=Cd(t);return void 0!==i?{offsetSeconds:i}:void 0}}(e.getAttribute("offset"));n&&t.progress.push(_({url:i},n))}}),$(t.clickTracking,e.querySelectorAll(":scope > VideoClicks > ClickTracking"))}function Z(e,t){$(t.impression,e.querySelectorAll(":scope > Impression")),$(t.error,e.querySelectorAll(":scope > Error")),$(t.viewable,e.querySelectorAll(":scope > ViewableImpression > Viewable")),$(t.notViewable,e.querySelectorAll(":scope > ViewableImpression > NotViewable")),$(t.viewUndetermined,e.querySelectorAll(":scope > ViewableImpression > ViewUndetermined")),e.querySelectorAll(':scope > AdVerifications > Verification, :scope > Extensions > Extension[type="AdVerifications"] > AdVerifications > Verification').forEach(function(e){$(t.verificationNotExecuted,e.querySelectorAll(':scope > TrackingEvents > Tracking[event="verificationNotExecuted"]'))})}function ee(e,t){var r,i,n=e,a=t;try{for(var s=F(Object.keys(n)),o=s.next();!o.done;o=s.next()){var l=o.value,u=a[l];u&&u.length>0&&(n[l]=n[l].concat(u))}}catch(e){r={error:e}}finally{try{o&&!o.done&&(i=s.return)&&i.call(s)}finally{if(r)throw r.error}}return e}function te(e){var t=(new DOMParser).parseFromString(e,"text/xml"),r=t.querySelector("parsererror");return r?(console.error("[HlsAdPlayer] XML parsing error (malformed VAST XML):",r.textContent),null):t}function re(e){var t=parseInt(e.getAttribute("sequence")||"",10);return Number.isFinite(t)?t:void 0}function ie(e){var t=[];return $(t,e.querySelectorAll(":scope > Error")),{type:"empty",errorUrls:t,errorCode:303}}function ne(e,t){var r,i,n;void 0===t&&(t=!1);try{var a=e.querySelector(":scope > Wrapper");if(a){var s=wd(a.querySelector(":scope > VASTAdTagURI"));if(!s)return console.warn("[HlsAdPlayer] <Wrapper> has no VASTAdTagURI"),{type:"empty"};var o=Q();return Z(a,o),a.querySelectorAll(":scope > Creatives > Creative > Linear").forEach(function(e){return J(e,o)}),{type:"wrapper",vastAdTagUri:s,trackingUrls:o,rules:{followAdditionalWrappers:"false"!==a.getAttribute("followAdditionalWrappers")}}}var l=e.querySelector(":scope > InLine");if(!l)return console.warn("[HlsAdPlayer] <Ad> has neither <InLine> nor <Wrapper>"),{type:"empty"};var u=[];if($(u,l.querySelectorAll(":scope > Error")),"true"===e.getAttribute("conditionalAd"))return console.warn("[HlsAdPlayer] Skipping conditional <Ad> (VPAID-only)"),{type:"empty",errorUrls:u,errorCode:403};var c=void 0,d=[];try{for(var h=F(Array.from(l.querySelectorAll(":scope > Creatives > Creative > Linear"))),f=h.next();!f.done;f=h.next()){var v=f.value,g=X(v,t);if(g.length>0){c=v,d=g;break}}}catch(e){r={error:e}}finally{try{f&&!f.done&&(i=h.return)&&i.call(h)}finally{if(r)throw r.error}}if(!c)return console.warn("[HlsAdPlayer] No supported linear media files in <Ad>"),{type:"empty",errorUrls:u,errorCode:403};var p=Q();return Z(l,p),J(c,p),{type:"inline",ad:{id:e.getAttribute("id")||"unknown",title:wd(l.querySelector(":scope > AdTitle"))||"Ad",duration:null!==(n=Cd(wd(c.querySelector(":scope > Duration"))))&&void 0!==n?n:30,mediaFiles:d,trackingUrls:p,clickThrough:wd(c.querySelector(":scope > VideoClicks > ClickThrough")),adServingId:wd(l.querySelector(":scope > AdServingId"))}}}catch(e){return console.error("[HlsAdPlayer] Error parsing <Ad> element:",e),{type:"empty"}}}function ae(e){return x(this,arguments,void 0,function(e,t){var r,i,n;return void 0===t&&(t="include"),O(this,function(a){switch(a.label){case 0:r=function(t){return fetch(e,{mode:"cors",credentials:t,headers:{Accept:"application/xml, text/xml, */*"},referrerPolicy:"no-referrer-when-downgrade"})},a.label=1;case 1:return a.trys.push([1,3,,7]),[4,r(t)];case 2:return i=a.sent(),[3,7];case 3:return n=a.sent(),"omit"===t?[3,5]:(console.warn('[HlsAdPlayer] VAST fetch failed with credentials="'.concat(t,'", retrying without credentials:'),n),[4,r("omit")]);case 4:return i=a.sent(),[3,6];case 5:throw n;case 6:return[3,7];case 7:if(!i.ok)throw new Error("Failed to fetch VAST: ".concat(i.statusText));return[2,i.text()]}})})}function se(e){return x(this,arguments,void 0,function(e,t,r,i){var n,a,s,o,l;return void 0===t&&(t=0),void 0===r&&(r=Q()),void 0===i&&(i={followAdditionalWrappers:!0}),O(this,function(u){switch(u.label){case 0:return u.trys.push([0,2,,3]),[4,ae(e,0===t?"include":"omit")];case 1:return n=u.sent(),[3,3];case 2:if(a=u.sent(),0===t)throw a;return console.warn("[HlsAdPlayer] Wrapped VAST request failed:",a),q(r.error,{errorCode:301}),[2,null];case 3:return console.log("[HlsAdPlayer] VAST XML received"),console.log("[HlsAdPlayer] VAST XML content (first 2000 chars):",n.substring(0,2e3)),s=function(e){var t,r;try{var i=te(e);if(!i)return{type:"empty"};var n=i.documentElement,a=Array.from(n.querySelectorAll(":scope > Ad")),s=null!==(t=a.find(function(e){return void 0===re(e)}))&&void 0!==t?t:a[0];if(!s)return console.warn("[HlsAdPlayer] No Ad element found in VAST ".concat(null!==(r=n.getAttribute("version"))&&void 0!==r?r:""," response")),ie(n);var o=ne(s,!0);return"wrapper"===o.type&&console.log("[HlsAdPlayer] VAST wrapper detected, following VASTAdTagURI: ".concat(o.vastAdTagUri)),o}catch(e){return console.error("[HlsAdPlayer] Error parsing VAST XML:",e),{type:"empty"}}}(n),"empty"===s.type?(q((null!==(o=s.errorUrls)&&void 0!==o?o:[]).concat(r.error),{errorCode:null!==(l=s.errorCode)&&void 0!==l?l:303}),[2,null]):"wrapper"===s.type?t>=5||!i.followAdditionalWrappers?(console.warn(i.followAdditionalWrappers?"[HlsAdPlayer] VAST wrapper depth limit (".concat(5,") reached, aborting redirect chain"):'[HlsAdPlayer] Parent wrapper set followAdditionalWrappers="false"; rejecting nested wrapper'),q(r.error.concat(s.trackingUrls.error),{errorCode:302}),[2,null]):(ee(r,s.trackingUrls),[2,se(s.vastAdTagUri,t+1,r,s.rules)]):(ee(s.ad.trackingUrls,r),[2,s.ad])}})})}function oe(e){return x(this,void 0,void 0,function(){var t,r,i,n,a,s,o,l,u,c,d,h,f,v,g,p,m,y,k,E,S,T,A,b,I,R=this;return O(this,function(L){switch(L.label){case 0:return[4,ae(e)];case 1:if(t=L.sent(),console.log("[HlsAdPlayer] Pod VAST XML received (length=".concat(t.length,")")),0===t.trim().length)return console.warn("[HlsAdPlayer] Pod VAST response body is empty (no fill)"),[2,[]];if(!(r=te(t)))return console.error("[HlsAdPlayer] Pod VAST XML content (first 2000 chars):",t.substring(0,2e3)),[2,[]];if(i=r.documentElement,0===(n=Array.from(i.querySelectorAll(":scope > Ad"))).length)return console.warn("[HlsAdPlayer] No <Ad> elements in VAST ".concat(null!==(T=i.getAttribute("version"))&&void 0!==T?T:""," pod response (no fill)")),"empty"===(a=ie(i)).type&&(null===(A=a.errorUrls)||void 0===A?void 0:A.length)&&q(a.errorUrls,{errorCode:null!==(b=a.errorCode)&&void 0!==b?b:303}),[2,[]];if(s=function(e){return x(R,void 0,void 0,function(){var t,r,i;return O(this,function(n){return"inline"===(t=ne(e)).type?[2,t.ad]:"wrapper"===t.type?[2,se(t.vastAdTagUri,1,t.trackingUrls,t.rules)]:((null===(r=t.errorUrls)||void 0===r?void 0:r.length)&&q(t.errorUrls,{errorCode:null!==(i=t.errorCode)&&void 0!==i?i:403}),[2,null])})})},o=n.filter(function(e){return void 0!==re(e)}).sort(function(e,t){return re(e)-re(t)}),l=n.filter(function(e){return void 0===re(e)}),u=[],0!==o.length)return[3,10];L.label=2;case 2:L.trys.push([2,7,8,9]),c=F(l),d=c.next(),L.label=3;case 3:return d.done?[3,6]:(g=d.value,[4,s(g)]);case 4:(p=L.sent())&&u.push(p),L.label=5;case 5:return d=c.next(),[3,3];case 6:return[3,9];case 7:return h=L.sent(),y={error:h},[3,9];case 8:try{d&&!d.done&&(k=c.return)&&k.call(c)}finally{if(y)throw y.error}return[7];case 9:return[3,20];case 10:L.trys.push([10,18,19,20]),f=F(o),v=f.next(),L.label=11;case 11:return v.done?[3,17]:(g=v.value,[4,s(g)]);case 12:p=L.sent(),L.label=13;case 13:return!p&&l.length>0?[4,s(l.shift())]:[3,15];case 14:return p=L.sent(),[3,13];case 15:p&&u.push(p),L.label=16;case 16:return v=f.next(),[3,11];case 17:return[3,20];case 18:return m=L.sent(),E={error:m},[3,20];case 19:try{v&&!v.done&&(S=f.return)&&S.call(f)}finally{if(E)throw E.error}return[7];case 20:return console.log("[HlsAdPlayer] Parsed ".concat(u.length," ad(s) from VAST ").concat(null!==(I=i.getAttribute("version"))&&void 0!==I?I:""," pod response")),[2,u]}})})}function le(){var e=document.createElement("video");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e.style.objectFit="contain",e.style.backgroundColor="#000",e.playsInline=!0,e.muted=!1,e.volume=1,console.log("[HlsAdPlayer] Created ad video element with volume ".concat(e.volume)),e}function ue(){var r,i;if(k&&a&&!(S.length>0)){var n=function(){return c&&!!a&&!!k&&B.start&&!B.complete&&!k.ended};S=[{type:"timeupdate",handler:function(){var e,t,r,i;if(a&&k){Ae(),fe();var n=k.currentTime;if(B.start)try{for(var s=F(a.trackingUrls.progress),o=s.next();!o.done;o=s.next()){var l=o.value;if(!B.progressFired.has(l))n>=(null!==(r=l.offsetSeconds)&&void 0!==r?r:(null!==(i=l.offsetPercent)&&void 0!==i?i:0)/100*a.duration)&&(B.progressFired.add(l),q([l.url]))}}catch(t){e={error:t}}finally{try{o&&!o.done&&(t=s.return)&&t.call(s)}finally{if(e)throw e.error}}if(a.duration>0){var u=n/a.duration;u>=.25&&!B.firstQuartile&&(B.firstQuartile=!0,q(a.trackingUrls.firstQuartile)),u>=.5&&!B.midpoint&&(B.midpoint=!0,q(a.trackingUrls.midpoint)),u>=.75&&!B.thirdQuartile&&(B.thirdQuartile=!0,q(a.trackingUrls.thirdQuartile))}}}},{type:"loadedmetadata",handler:function(){if(c&&k){var e=k.videoWidth,t=k.videoHeight;(e<=1||t<=1)&&(console.warn("[HlsAdPlayer] Ad creative has no usable video dimensions (".concat(e,"x").concat(t,") - skipping this creative")),Ie())}}},{type:"canplay",handler:function(){a&&!B.loaded&&(B.loaded=!0,q(a.trackingUrls.loaded))}},{type:"playing",handler:function(){!function(){Te(),Ae(),C=!1,function(){if(be(),!k)return;var t=k.requestVideoFrameCallback;if("function"!=typeof t)return;var r=function(){l=void 0,c&&(C=!0,e[y]=!0)};try{l=t.call(k,r)}catch(e){console.warn("[HlsAdPlayer] Error requesting video frame callback:",e),l=void 0}}();var t=!kd();o=window.setInterval(function(){if(c&&k){if(t&&!C&&!k.paused){var r=function(e){try{if("function"==typeof e.getVideoPlaybackQuality){var t=e.getVideoPlaybackQuality();if(t&&"number"==typeof t.totalVideoFrames)return t.totalVideoFrames}var r=e.webkitDecodedFrameCount;if("number"==typeof r)return r}catch(e){console.warn("[HlsAdPlayer] Unable to read decoded video frame count:",e)}return}(k);if(void 0!==r&&r>0)C=!0,e[m]=!0;else if(k.currentTime>=1.5){var i=k.currentTime>w+.05;if("function"==typeof k.requestVideoFrameCallback&&i&&!0===e[y])return void Ie();if(0===r&&i&&!0===e[m])return void Ie()}}k.currentTime>w+.05||k.paused?Ae():Date.now()-P>=4e3&&function(){if(console.warn("[HlsAdPlayer] Ad playback stalled (no progress) - recovering to avoid a blank frame"),Te(),de(_d),b<A.length-1&&Se())return;Le()}()}},1e3)}(),a&&k&&(B.impression||(B.impression=!0,U.add(a),q(a.trackingUrls.impression),q(a.trackingUrls.creativeView),q(a.trackingUrls.verificationNotExecuted,{reason:2}),j("ad_impression",{adId:a.id,index:b,total:A.length||1})),B.start||(B.start=!0,B.lastMuted=k.muted||0===k.volume,q(a.trackingUrls.start),console.log("[HlsAdPlayer] Ad started playing")))}},{type:"ended",handler:function(){a&&!B.complete&&(fe(),ve(),B.complete=!0,q(a.trackingUrls.complete),console.log("[HlsAdPlayer] Ad completed"),b<A.length-1&&Se()||function(){console.log("[HlsAdPlayer] Handling ad completion"),ve(),Te(),c=!1,pe(!1),e.muted=!0,Re(),(null==t?void 0:t.continueLiveStreamDuringAds)||(e.style.visibility="visible",e.style.opacity="1");(null==t?void 0:t.continueLiveStreamDuringAds)&&(e.paused?(console.log("[HlsAdPlayer] Content video paused in live mode, resuming playback"),e.play().catch(function(e){console.error("[HlsAdPlayer] Error resuming content playback in live mode:",e)})):console.log("[HlsAdPlayer] Content video already playing in live mode"));j("content_resume")}())}},{type:"error",handler:function(e){c&&(console.error("[HlsAdPlayer] Ad video error:",e),de(function(e){switch(null==e?void 0:e.code){case 1:return 400;case 2:return 401;case 4:return 403;default:return 405}}(null==k?void 0:k.error)),b<A.length-1&&Se()||Le())}},{type:"volumechange",handler:function(){if(a&&k){var e=k.muted||0===k.volume;B.start?e!==B.lastMuted&&(B.lastMuted=e,q(e?a.trackingUrls.mute:a.trackingUrls.unmute)):B.lastMuted=e}}},{type:"pause",handler:function(){G=0,n()&&q(a.trackingUrls.pause)}},{type:"play",handler:function(){n()&&q(a.trackingUrls.resume)}}];try{for(var s=F(S),u=s.next();!u.done;u=s.next()){var d=u.value,h=d.type,f=d.handler;k.addEventListener(h,f)}}catch(e){r={error:e}}finally{try{u&&!u.done&&(i=s.return)&&i.call(s)}finally{if(r)throw r.error}}}}function ce(){var e,t;if(k)try{for(var r=F(S),i=r.next();!i.done;i=r.next()){var n=i.value,a=n.type,s=n.handler;k.removeEventListener(a,s)}}catch(t){e={error:t}}finally{try{i&&!i.done&&(t=r.return)&&t.call(r)}finally{if(e)throw e.error}}S=[]}function de(e){a&&(U.add(a),q(a.trackingUrls.error,{errorCode:e}))}function he(){var e,t;try{for(var r=F(A),i=r.next();!i.done;i=r.next()){var n=i.value;U.has(n)||(U.add(n),q(n.trackingUrls.notUsed,{ad:n}))}}catch(t){e={error:t}}finally{try{i&&!i.done&&(t=r.return)&&t.call(r)}finally{if(e)throw e.error}}}function fe(){if(a&&k&&M&&B.impression&&!B.viewabilitySettled){var e=k.currentTime;V>=.5&&"visible"===document.visibilityState&&!k.paused?void 0!==N&&e>=N&&(G+=e-N):G=0,N=e,G>=2&&(B.viewabilitySettled=!0,q(a.trackingUrls.viewable))}}function ve(){a&&B.impression&&!B.viewabilitySettled&&(B.viewabilitySettled=!0,q(M?a.trackingUrls.notViewable:a.trackingUrls.viewUndetermined))}function ge(){var e,t,r,i;if(E&&!(T.length>0)){var n=function(e){c&&j("ad_interaction",e)};T=[{type:"click",handler:function(){return function(){if(c&&a&&(q(a.trackingUrls.clickTracking),j("ad_click",{adId:a.id,clickThrough:a.clickThrough}),a.clickThrough))try{window.open(a.clickThrough,"_blank","noopener")}catch(e){console.warn("[HlsAdPlayer] Failed to open ClickThrough URL:",e)}}()}},{type:"mousedown",handler:n},{type:"touchstart",handler:n}];try{for(var s=F(T),o=s.next();!o.done;o=s.next()){var l=o.value,u=l.type,d=l.handler;E.addEventListener(u,d)}}catch(t){e={error:t}}finally{try{o&&!o.done&&(t=s.return)&&t.call(s)}finally{if(e)throw e.error}}var h=function(){return function(){var e;if(c&&a&&E&&B.start){var t=null!==(e=document.fullscreenElement)&&void 0!==e?e:document.webkitFullscreenElement,r=!!t&&t.contains(E);if(r!==H){H=r;var i=a.trackingUrls;q(r?i.fullscreen.concat(i.playerExpand):i.exitFullscreen.concat(i.playerCollapse))}}}()};K=[{type:"fullscreenchange",handler:h},{type:"webkitfullscreenchange",handler:h}];try{for(var f=F(K),v=f.next();!v.done;v=f.next()){var g=v.value;u=g.type,d=g.handler;document.addEventListener(u,d)}}catch(e){r={error:e}}finally{try{v&&!v.done&&(i=f.return)&&i.call(f)}finally{if(r)throw r.error}}"undefined"!=typeof IntersectionObserver&&(M=new IntersectionObserver(function(e){var t=e[e.length-1];t&&(V=t.isIntersecting?t.intersectionRatio:0)},{threshold:[0,.25,.5,.75,1]})).observe(E)}}function pe(t){t?e.dataset.stormcloudAdPlaying="true":delete e.dataset.stormcloudAdPlaying}function me(){B=D(),G=0,N=void 0}function ye(e){if(k){var t=k.play();u=t,t.catch(function(r){u===t&&(console.error("[HlsAdPlayer] Error starting ".concat(e,":"),r),Le())}).finally(function(){u===t&&(u=void 0)})}}function ke(){if(u=void 0,n&&(n.destroy(),n=void 0),k)try{k.pause(),k.removeAttribute("src"),k.load()}catch(e){console.warn("[HlsAdPlayer] Error preparing ad video for new source:",e)}}function Ee(){if(!k||!a)throw new Error("No ad video element or ad to load");var e=W(a.mediaFiles);if(!e)throw new Error("No media file available for ad");s=e;var t=Y(e);if(console.log("[HlsAdPlayer] Loading ".concat(t?"HLS":"progressive"," ad (pod ").concat(b+1,"/").concat(A.length||1,") from: ").concat(e.url)),t&&md.isSupported())n&&n.destroy(),(n=new md({enableWorker:!0,lowLatencyMode:!1})).loadSource(e.url),n.attachMedia(k),n.on(md.Events.MANIFEST_PARSED,function(){console.log("[HlsAdPlayer] HLS manifest parsed, starting playback"),ye("HLS ad playback")}),n.on(md.Events.ERROR,function(e,t){console.error("[HlsAdPlayer] HLS error:",t),t.fatal&&Le()});else if(t&&k.canPlayType("application/vnd.apple.mpegurl"))k.src=e.url,ye("native HLS ad playback");else{if(t||!z(e))throw new Error("Unsupported ad media file type: ".concat(e.type));n&&(n.destroy(),n=void 0),k.src=e.url,k.load(),ye("progressive ad playback")}}function Se(){if(b>=A.length-1)return!1;ve(),b++,a=A[b],s=void 0,me(),a&&console.log("[HlsAdPlayer] Advancing to next pod ad (".concat(b+1,"/").concat(A.length,"): ").concat(a.title,", duration: ").concat(a.duration,"s")),Te(),kd()?(!function(){if(console.log("[HlsAdPlayer] Recreating ad video element (single-decoder platform)"),ce(),ke(),k)try{k.remove()}catch(e){console.warn("[HlsAdPlayer] Error removing ad video element:",e)}k=le(),null==E||E.appendChild(k),e[p]=k,k.volume=Math.max(0,Math.min(1,h)),k.muted=d}(),ue()):ke();try{return Ee(),j("pod_ad_started",{index:b,total:A.length}),!0}catch(e){return console.error("[HlsAdPlayer] Failed to load next pod ad:",e),!1}}function Te(){null!=o&&(clearInterval(o),o=void 0),be()}function Ae(){P=Date.now(),k&&(w=k.currentTime)}function be(){if(null!=l&&k&&"function"==typeof k.cancelVideoFrameCallback)try{k.cancelVideoFrameCallback(l)}catch(e){console.warn("[HlsAdPlayer] Error cancelling video frame callback:",e)}l=void 0}function Ie(){console.warn("[HlsAdPlayer] Ad audio is advancing but no video frames decoded (black screen) - skipping this creative"),Te(),de(_d),b<A.length-1&&Se()||Le()}function Re(){ke(),E&&(E.style.display="none",E.style.pointerEvents="none")}function Le(){console.log("[HlsAdPlayer] Handling ad error"),ve(),Te(),c=!1,pe(!1),e.muted=!0,Re(),(null==t?void 0:t.continueLiveStreamDuringAds)||(e.style.visibility="visible",e.style.opacity="1"),j("ad_error")}return{initialize:function(){var t;if(console.log("[HlsAdPlayer] Initializing"),!E){var r=document.createElement("div");r.style.position="absolute",r.style.left="0",r.style.top="0",r.style.right="0",r.style.bottom="0",r.style.display="none",r.style.alignItems="center",r.style.justifyContent="center",r.style.pointerEvents="none",r.style.zIndex="30",r.style.backgroundColor="#000",null===(t=e.parentElement)||void 0===t||t.appendChild(r),E=r}e[g]=E,ge()},requestAds:function(e){return x(this,void 0,void 0,function(){var t,r,i;return O(this,function(n){switch(n.label){case 0:if(console.log("[HlsAdPlayer] Requesting ads:",e),c)return console.warn("[HlsAdPlayer] Cannot request new ads while an ad is playing"),[2,Promise.reject(new Error("Ad already playing"))];n.label=1;case 1:return n.trys.push([1,5,,6]),t=[],I.has(e)?(r=I.get(e),I.delete(e),r&&(t=[r]),console.log("[HlsAdPlayer] Using preloaded VAST response:",e),[3,4]):[3,2];case 2:return[4,oe(e)];case 3:t=n.sent(),n.label=4;case 4:return t.length?(A=t,b=0,a=t[0],s=void 0,console.log("[HlsAdPlayer] Pod parsed: ".concat(t.length,' ad(s), first="').concat(null==a?void 0:a.title,'", duration=').concat(null==a?void 0:a.duration,"s")),[2,Promise.resolve()]):(console.warn("[HlsAdPlayer] No ads available from VAST response"),j("ad_error"),[2,Promise.reject(new Error("No ads available from VAST response"))]);case 5:return i=n.sent(),console.error("[HlsAdPlayer] Error requesting ads:",i),j("ad_error"),[2,Promise.reject(i)];case 6:return[2]}})})},play:function(){return x(this,void 0,void 0,function(){var r;return O(this,function(i){if(!a)return console.warn("[HlsAdPlayer] Cannot play: No ad loaded (no ads available)"),[2,Promise.reject(new Error("No ad loaded"))];console.log("[HlsAdPlayer] Starting ad playback");try{return k||(k=le(),null==E||E.appendChild(k),e[p]=k),ue(),me(),r=e.volume,h=Math.max(0,Math.min(1,r||h)),(null==t?void 0:t.continueLiveStreamDuringAds)?console.log("[HlsAdPlayer] Content continues (Live mode)"):(e.pause(),console.log("[HlsAdPlayer] Content paused (VOD mode)")),console.log("[HlsAdPlayer] FORCE MUTING main video"),e.muted=!0,c=!0,pe(!0),k&&(k.volume=Math.max(0,Math.min(1,h)),k.muted=d,console.log("[HlsAdPlayer] Set ad video volume to ".concat(k.volume,", muted: ").concat(k.muted,", originalMutedState: ").concat(d,", contentVolume: ").concat(r))),E&&(E.style.display="flex",E.style.pointerEvents="auto"),j("content_pause"),Ee(),[2,Promise.resolve()]}catch(e){return console.error("[HlsAdPlayer] Error playing ad:",e),Le(),[2,Promise.reject(e)]}return[2]})})},pause:function(){if(c&&k)try{k&&!k.paused&&k.pause()}catch(e){console.warn("[HlsAdPlayer] Error pausing ad:",e)}},resume:function(){if(c&&k)try{k&&k.paused&&k.play().catch(function(){})}catch(e){console.warn("[HlsAdPlayer] Error resuming ad:",e)}},stop:function(){return x(this,void 0,void 0,function(){var r;return O(this,function(i){return console.log("[HlsAdPlayer] Stopping ad"),ve(),he(),Te(),c=!1,pe(!1),r=e.muted,e.muted=d,e.volume=Math.max(0,Math.min(1,h)),console.log("[HlsAdPlayer] Restored mute state on stop: ".concat(r," -> ").concat(d,", volume: ").concat(e.volume)),Re(),e.style.visibility="visible",e.style.opacity="1",(null==t?void 0:t.continueLiveStreamDuringAds)&&e.paused&&(console.log("[HlsAdPlayer] Content video paused in live mode, resuming playback on stop"),e.play().catch(function(e){console.error("[HlsAdPlayer] Error resuming content playback in live mode on stop:",e)})),a=void 0,s=void 0,A=[],b=0,[2]})})},destroy:function(){var t,r;console.log("[HlsAdPlayer] Destroying"),ve(),he(),Te();try{for(var i=F(L),n=i.next();!n.done;n=i.next()){var o=n.value;clearTimeout(o)}}catch(e){t={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}L=[],c=!1,pe(!1),e.muted=d,e.volume=Math.max(0,Math.min(1,h)),ce(),function(){var e,t,r,i;if(E)try{for(var n=F(T),a=n.next();!a.done;a=n.next()){var s=a.value,o=s.type,l=s.handler;E.removeEventListener(o,l)}}catch(t){e={error:t}}finally{try{a&&!a.done&&(t=n.return)&&t.call(n)}finally{if(e)throw e.error}}T=[];try{for(var u=F(K),c=u.next();!c.done;c=u.next()){var d=c.value;o=d.type,l=d.handler,document.removeEventListener(o,l)}}catch(e){r={error:e}}finally{try{c&&!c.done&&(i=u.return)&&i.call(u)}finally{if(r)throw r.error}}K=[],null==M||M.disconnect(),M=void 0}(),Re(),a=void 0,s=void 0,A=[],b=0,f.clear(),I.clear(),R.clear()},isAdPlaying:function(){return c},resize:function(e,t){console.log("[HlsAdPlayer] Resizing to ".concat(e,"x").concat(t)),E&&(E.style.width="".concat(e,"px"),E.style.height="".concat(t,"px")),k&&(k.style.width="".concat(e,"px"),k.style.height="".concat(t,"px"))},on:function(e,t){f.has(e)||f.set(e,new Set),f.get(e).add(t)},off:function(e,t){var r;null===(r=f.get(e))||void 0===r||r.delete(t)},updateOriginalMutedState:function(e,t){var r="number"!=typeof t||Number.isNaN(t)?h:Math.max(0,Math.min(1,t));console.log("[HlsAdPlayer] updateOriginalMutedState called: { muted: ".concat(d," -> ").concat(e,", volume: ").concat(h," -> ").concat(r," }")),d=e,h=r},getOriginalMutedState:function(){return d},getOriginalVolume:function(){return h},setAdVolume:function(e){if(k&&c){var t=Math.max(0,Math.min(1,e));k.volume=t,k.muted=0===t}},getAdVolume:function(){return k&&c?k.volume:1},showPlaceholder:function(){var t;if(e.style.opacity="0",e.style.visibility="hidden",!E){var r=document.createElement("div");r.style.position="absolute",r.style.left="0",r.style.top="0",r.style.right="0",r.style.bottom="0",r.style.display="none",r.style.alignItems="center",r.style.justifyContent="center",r.style.pointerEvents="none",r.style.zIndex="10",r.style.backgroundColor="#000",null===(t=e.parentElement)||void 0===t||t.appendChild(r),E=r}E&&(E.style.display="flex",E.style.pointerEvents="auto")},hidePlaceholder:function(){E&&!c&&(E.style.display="none",E.style.pointerEvents="none"),c||(e.style.visibility="visible",e.style.opacity="1")},getLoadedAdDuration:function(){return null==a?void 0:a.duration},getLoadedAdId:function(){return null==a?void 0:a.id},getPodAdCount:function(){return A.length},getPodTotalDurationMs:function(){return A.reduce(function(e,t){return e+(t.duration>0?1e3*t.duration:0)},0)}}}var xd=[/^localhost$/i,/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,/^0\.0\.0\.0$/,/^::1$/,/^10\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,/^192\.168\.\d{1,3}\.\d{1,3}$/,/^172\.(1[6-9]|2\d|3[0-1])\.\d{1,3}\.\d{1,3}$/];function Od(e){if(!e)return null!=e?e:"";var t,r,i;try{t=new URL(e)}catch(t){return e}if("http:"!==t.protocol&&"https:"!==t.protocol)return e;if(r=t.hostname,!(i=r.replace(/^\[/,"").replace(/\]$/,"").toLowerCase())||!(i.endsWith(".local")||i.endsWith(".localhost")||xd.some(function(e){return e.test(i)})))return e;var n=t.pathname.replace(/\/{2,}/g,"/")||"/index.html";return"file://".concat(n)}var Fd,Nd,Bd;function Ud(){var e;return"undefined"!=typeof window&&(null===(e=window.goog)||void 0===e?void 0:e.pal)?Promise.resolve():Bd||(Bd=new Promise(function(e,t){var r,i=document.querySelector('script[data-pal="true"]');if(i){if(null===(r=window.goog)||void 0===r?void 0:r.pal)return void e();var n=setTimeout(function(){return t(new Error("PAL SDK load timeout"))},1e4);return i.addEventListener("load",function(){clearTimeout(n),e()}),void i.addEventListener("error",function(){clearTimeout(n),t(new Error("PAL SDK load failed"))})}var a=document.createElement("script");a.src="https://imasdk.googleapis.com/pal/sdkloader/pal.js",a.async=!0,a.setAttribute("data-pal","true"),a.onload=function(){return e()},a.onerror=function(){return t(new Error("PAL SDK load failed"))},document.head.appendChild(a)}),Bd)}function Vd(){var e,t="";return{generateNonce:function(){return x(this,arguments,void 0,function(r){var i,n,a,s,o,l,u,c,d,h;return void 0===r&&(r={}),O(this,function(f){switch(f.label){case 0:return f.trys.push([0,3,,4]),[4,Ud()];case 1:return f.sent(),i=function(e){if(Fd&&Nd===e)return Fd;var t=window.goog,r=new t.pal.ConsentSettings;return r.allowStorage=e,Fd=new t.pal.NonceLoader(r),Nd=e,Fd}(null===(l=r.allowStorage)||void 0===l||l),n=window.goog,(a=new n.pal.NonceRequest).adWillAutoPlay=null===(u=r.adWillAutoPlay)||void 0===u||u,a.adWillPlayMuted=null!==(c=r.adWillPlayMuted)&&void 0!==c&&c,a.playerVolume=null!==(d=r.playerVolume)&&void 0!==d?d:a.adWillPlayMuted?0:1,a.continuousPlayback=null===(h=r.continuousPlayback)||void 0===h||h,a.descriptionUrl=Od(r.descriptionUrl||("undefined"!=typeof window?window.location.href:"")),a.iconsSupported=!0,a.playerType="StormcloudVideoPlayer",a.playerVersion="1.0",a.supportedApiFrameworks="2,7,9",a.url=Od(r.descriptionUrl||("undefined"!=typeof window?window.location.href:"")),a.videoWidth=r.videoWidth||640,a.videoHeight=r.videoHeight||480,r.ppid&&(a.ppid=r.ppid),r.sessionId&&(a.sessionId=r.sessionId),console.log("[PAL] NonceRequest before generateNonce:",JSON.stringify({adWillAutoPlay:a.adWillAutoPlay,adWillPlayMuted:a.adWillPlayMuted,playerVolume:a.playerVolume,continuousPlayback:a.continuousPlayback,descriptionUrl:a.descriptionUrl,iconsSupported:a.iconsSupported,playerType:a.playerType,playerVersion:a.playerVersion,supportedApiFrameworks:a.supportedApiFrameworks,url:a.url,videoWidth:a.videoWidth,videoHeight:a.videoHeight,ppid:a.ppid,sessionId:a.sessionId},null,2)),[4,i.loadNonceManager(a)];case 2:return s=f.sent(),e=s,t=s.getNonce(),console.log("[PAL] Nonce generated successfully"),[2,t];case 3:return o=f.sent(),console.warn("[PAL] Failed to generate nonce:",o),t="",e=void 0,[2,""];case 4:return[2]}})})},getCurrentNonce:function(){return t},injectNonce:function(e){if(!t||!e)return e;try{var r=new URL(e);return r.searchParams.delete("paln"),r.searchParams.set("givn",t),r.toString()}catch(r){var i=e.replace(/([?&])paln=[^&]*/g,"").replace(/[?&]$/,""),n=i.includes("?")?"&":"?";return"".concat(i).concat(n,"givn=").concat(encodeURIComponent(t))}},sendPlaybackStart:function(){try{null==e||e.sendPlaybackStart()}catch(e){}},sendPlaybackEnd:function(){try{null==e||e.sendPlaybackEnd()}catch(e){}},sendAdClick:function(){try{null==e||e.sendAdClick()}catch(e){}},sendAdTouch:function(t){try{null==e||e.sendAdTouch(t)}catch(e){}},reset:function(){t="",e=void 0}}}var Gd={enabled:!0,baseUrl:"https://player-analytics-ingest-api-760490581852.us-central1.run.app/api/adstorm/player-tracking"},Hd=_({},Gd);function Kd(e){Object.assign(Hd,e)}function jd(){return!0===Hd.enabled}function qd(e){var t=Hd.baseUrl.replace(/\/+$/,"");return"".concat(t,"impressions"===e?"/impressions/ingest":"/metrics/ingest")}function Wd(e,t,r){return x(this,void 0,void 0,function(){var i,n;return O(this,function(a){switch(a.label){case 0:if(!jd()||!e)return[2,!1];a.label=1;case 1:return a.trys.push([1,3,,4]),[4,fetch(qd(t),{method:"POST",headers:{"Content-Type":"application/json",Authorization:"License-Key ".concat(e)},body:JSON.stringify(r)})];case 2:return(i=a.sent()).ok?[2,!0]:(console.warn("[StormcloudVideoPlayer] Tracking ingest failed (".concat(i.status,") for ").concat(t)),[2,!1]);case 3:return n=a.sent(),console.warn("[StormcloudVideoPlayer] Tracking ingest error for ".concat(t,":"),n),[2,!1];case 4:return[2]}})})}var Yd="stormcloud.ctv.sid",zd="stormcloud.player.id",Xd=["rdid","ifa","advertisingId","advertising_id","deviceAdvertisingId","aaid","adid","rida","tifa","lgudid"],Qd=new Set(["aaid","adid"]);function $d(e){var t,r,i=mh(),n=fh(),a=i.deviceId||(e?Sh():void 0)||n.deviceId,s=i.deviceIdType||Th("deviceIdType")||Th("idtype")||n.deviceIdType||sh(),o=i.deviceId?i.limitAdTracking:n.limitAdTracking,l=null!=a?null!==(t=null!=o?o:Ah())&&void 0!==t&&t:void 0;if(!a&&e){var u=oh(zd);u&&(a=u,s="dpid",l=null!==(r=null!=o?o:Ah())&&void 0!==r&&r)}var c=function(e){var t=function(e){var t,r,i,n,a,s;if("undefined"==typeof window)return;var o=["dth","deviceTypeHint"],l=nh(window.__STORMCLOUD_DTH__);if(null!=l)return l;try{for(var u=F(yh()),c=u.next();!c.done;c=u.next()){var d=c.value;try{for(var h=(i=void 0,F(o)),f=h.next();!f.done;f=h.next()){var v=f.value,g=null==d?void 0:d[v];if(null!=(y=nh("function"==typeof g?ah(g,d):g)))return y}}catch(e){i={error:e}}finally{try{f&&!f.done&&(n=h.return)&&n.call(h)}finally{if(i)throw i.error}}}}catch(e){t={error:e}}finally{try{c&&!c.done&&(r=u.return)&&r.call(u)}finally{if(t)throw t.error}}if(!e)return;try{for(var p=F(["stormcloud.dth","dth"]),m=p.next();!m.done;m=p.next()){var y;if(null!=(y=nh(Th(v=m.value))))return y}}catch(e){a={error:e}}finally{try{m&&!m.done&&(s=p.return)&&s.call(p)}finally{if(a)throw a.error}}return}(e);return null!=t?t:function(e){var t=e?Jd.CONNECTED_TV:Jd.DESKTOP;if("undefined"==typeof navigator)return t;var r=navigator.userAgent||"",i=navigator.maxTouchPoints||0;if(eh.test(r))return Jd.SET_TOP_BOX;if(th.test(r))return Jd.GAME_CONSOLE;if(rh.test(r)&&!/Mobile/i.test(r))return Jd.CONNECTED_TV;if(ih.test(r))return Jd.FEATURE_PHONE;if(/iPad/i.test(r)||/Macintosh/i.test(r)&&i>1)return Jd.TABLET;if(/iPhone|iPod/i.test(r))return Jd.SMARTPHONE;if(/Android/i.test(r))return/Mobile/i.test(r)?Jd.SMARTPHONE:0===i?Jd.SET_TOP_BOX:Jd.TABLET;return/Mobile|Windows Phone|BlackBerry/i.test(r)?Jd.SMARTPHONE:t}(e)}(e);return _(_(_(_(e?{isCtv:!0,sessionId:lh()}:{isCtv:!1},a?{deviceId:a}:{}),a&&s?{deviceIdType:s}:{}),a&&null!=l?{limitAdTracking:l}:{}),{deviceTypeHint:c})}var Jd={FEATURE_PHONE:1,SMARTPHONE:2,DESKTOP:3,TABLET:4,CONNECTED_TV:5,GAME_CONSOLE:6,SET_TOP_BOX:7},Zd={featurephone:Jd.FEATURE_PHONE,smartphone:Jd.SMARTPHONE,mobile:Jd.SMARTPHONE,phone:Jd.SMARTPHONE,desktop:Jd.DESKTOP,pc:Jd.DESKTOP,tablet:Jd.TABLET,ctv:Jd.CONNECTED_TV,tv:Jd.CONNECTED_TV,connectedtv:Jd.CONNECTED_TV,smarttv:Jd.CONNECTED_TV,console:Jd.GAME_CONSOLE,gameconsole:Jd.GAME_CONSOLE,stb:Jd.SET_TOP_BOX,settopbox:Jd.SET_TOP_BOX},eh=/LGSTB|\bSTB\b|STB\d|Set-?Top|SetTopBox|TV ?Box|Kaon|Humax|Arris|Technicolor|Sagemcom|Infomir|MAG\d{3}|KreaTV|Amino|Formuler|Dune ?HD|TiVo|MiBOX|Mi Box|SHIELD Android TV|\bAFT[A-Z]|Roku|AppleTV|Apple TV|CrKey/i,th=/PlayStation|Xbox|Nintendo/i,rh=/Web0S|webOS|Tizen|SMART-TV|SmartTV|NetCast|BRAVIA|HbbTV|VIDAA|Hisense|Philips|Viera|AQUOS|Android TV|Google TV|\bTV\b/i,ih=/KAIOS|MIDP|J2ME|Series40|Opera Mini/i;function nh(e){if("number"==typeof e)return Number.isInteger(e)&&e>=1&&e<=7?e:void 0;if("string"==typeof e){var t=e.trim();return/^[1-7]$/.test(t)?parseInt(t,10):Zd[t.toLowerCase().replace(/[\s_-]/g,"")]}}function ah(e,t){try{return e.call(t)}catch(e){return}}function sh(){if("undefined"!=typeof navigator){var e=navigator.userAgent;return/Roku/i.test(e)?"rida":/Tizen|Samsung/i.test(e)?"tifa":/AppleTV|Apple TV/i.test(e)?"tvOS":/AFT|Fire TV|Amazon/i.test(e)?"afai":/Web0S|webOS|LG Browser|LGSTB|LGE/i.test(e)?"lgudid":/Android|Google TV/i.test(e)?"aaid":/iPhone|iPad|iPod/i.test(e)?"idfa":void 0}}function oh(e){if("undefined"!=typeof window){var t=uh(e);if(t)return ch(e,t),t;var r=hh();return ch(e,r),r}}function lh(){var e=uh(Yd);if(e)return ch(Yd,e),e;var t=hh();return ch(Yd,t),t}function uh(e){return Th(e)||function(e){var t,r;if("undefined"==typeof document)return;try{var i=encodeURIComponent(e)+"=",n=document.cookie?document.cookie.split(";"):[];try{for(var a=F(n),s=a.next();!s.done;s=a.next()){var o=s.value.trim();if(o.startsWith(i))return decodeURIComponent(o.slice(i.length))||void 0}}catch(e){t={error:e}}finally{try{s&&!s.done&&(r=a.return)&&r.call(a)}finally{if(t)throw t.error}}}catch(e){}return}(e)}function ch(e,t){var r;try{null===(r=window.localStorage)||void 0===r||r.setItem(e,t)}catch(e){}!function(e,t){if("undefined"==typeof document)return;try{document.cookie=encodeURIComponent(e)+"="+encodeURIComponent(t)+";path=/;max-age="+dh+";SameSite=Lax"}catch(e){}}(e,t)}var dh=15768e4;function hh(){var e,t,r;if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return crypto.randomUUID();var i=new Uint8Array(16);if("undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues)crypto.getRandomValues(i);else for(var n=Date.now()^Math.floor(1e3*function(){try{if("undefined"!=typeof performance&&"function"==typeof performance.now)return performance.now()}catch(e){}return 0}()),a=0;a<16;a++)n=1103515245*n+12345&2147483647,i[a]=255&(n^Math.floor(256*Math.random()));i[6]=15&(null!==(e=i[6])&&void 0!==e?e:0)|64,i[8]=63&(null!==(t=i[8])&&void 0!==t?t:0)|128;var s="";for(a=0;a<16;a++)s+=(null!==(r=i[a])&&void 0!==r?r:0).toString(16).padStart(2,"0");return s.slice(0,8)+"-"+s.slice(8,12)+"-"+s.slice(12,16)+"-"+s.slice(16,20)+"-"+s.slice(20,32)}function fh(){var e,t;if("undefined"==typeof window)return{};try{var r=null===(e=window.webapis)||void 0===e?void 0:e.adinfo;if(r){var i="function"==typeof r.getTIFA?r.getTIFA():r.tifa;if("string"==typeof i&&i&&!gh(i)){var n="function"==typeof r.isLATEnabled?r.isLATEnabled():void 0;return _({deviceId:i,deviceIdType:"tifa"},"boolean"==typeof n?{limitAdTracking:n}:{})}}}catch(e){}try{var a=window.webOSDev;if(a){var s="function"==typeof a.LGUDID?a.LGUDID():null!==(t=a.lgudid)&&void 0!==t?t:a.LGUDID;if("string"==typeof s&&s){if(ph(s))return{deviceIdType:"lgudid",limitAdTracking:!0};if(!gh(s))return{deviceId:s,deviceIdType:"lgudid",limitAdTracking:!1}}}}catch(e){}try{var o=window.Roku;if(o){var l="function"==typeof o.getPublisherUniqueId?o.getPublisherUniqueId():o.rida;if("string"==typeof l&&l&&!gh(l))return{deviceId:l,deviceIdType:"rida",limitAdTracking:!1}}}catch(e){}return{}}var vh=new Set(["38400000-8cf0-11bd-b23e-10b96e40000d","00000000-0000-0000-0000-000000000000"]);function gh(e){var t=e.trim();return!t||/^(\[[^\]]*\]|\{[^}]*\}|%%[^%]*%%)$/.test(t)||/^(unknown|null|undefined|none|n\/a|\$\{[^}]+\})$/i.test(t)||vh.has(t.toLowerCase())}function ph(e){return vh.has(e.trim().toLowerCase())}function mh(){var e,t;try{for(var r=F(yh()),i=r.next();!i.done;i=r.next()){var n=i.value,a=kh(n,["contentUrl","url","videoUrl","canonicalUrl"])||void 0,s=kh(n,["appId","msid","applicationId","packageName"])||void 0,o=kh(n,["appName","an","applicationName"])||void 0,l=kh(n,["rdid","ifa","advertisingId","adId","deviceId","lgudid","LGUDID","tifa","rida","afai","aaid"])||void 0;if(a||l||s||o){var u=kh(n,["idtype","deviceIdType","advertisingIdType","idType"])||sh(),c=Eh(n,["is_lat","limitAdTracking","limitedAdTracking","lat"]);return _(_(_(_(_(_({},a?{contentUrl:a}:{}),s?{appId:s}:{}),o?{appName:o}:{}),l?{deviceId:l}:{}),l&&u?{deviceIdType:u}:{}),l&&null!=c?{limitAdTracking:c}:{})}}}catch(t){e={error:t}}finally{try{i&&!i.done&&(t=r.return)&&t.call(r)}finally{if(e)throw e.error}}return{}}function yh(){return"undefined"==typeof window?[]:[window.__STORMCLOUD_CTV_AD_INFO__,window.__STORMCLOUD_CTV__,window.stormcloudCtv,window.AiryTV,window.Android,window.webOS,window.tizen,window.amazon].filter(Boolean)}function kh(e,t){var r,i;try{for(var n=F(t),a=n.next();!a.done;a=n.next()){var s=a.value,o=null==e?void 0:e[s];if("string"==typeof o&&o)return o;if("function"==typeof o)try{var l=o.call(e);if("string"==typeof l&&l)return l}catch(e){}}}catch(e){r={error:e}}finally{try{a&&!a.done&&(i=n.return)&&i.call(n)}finally{if(r)throw r.error}}}function Eh(e,t){var r,i;try{for(var n=F(t),a=n.next();!a.done;a=n.next()){var s=a.value,o=null==e?void 0:e[s],l=bh(o);if(null!=l)return l;if("function"==typeof o)try{var u=bh(o.call(e));if(null!=u)return u}catch(e){}}}catch(e){r={error:e}}finally{try{a&&!a.done&&(i=n.return)&&i.call(n)}finally{if(r)throw r.error}}}function Sh(){var e,t;try{for(var r=F(Xd),i=r.next();!i.done;i=r.next()){var n=Th(i.value);if(n)return n}}catch(t){e={error:t}}finally{try{i&&!i.done&&(t=r.return)&&t.call(r)}finally{if(e)throw e.error}}}function Th(e){var t;if("undefined"!=typeof window)try{return(null===(t=window.localStorage)||void 0===t?void 0:t.getItem(e))||void 0}catch(e){return}}function Ah(){return bh(Th("limitAdTracking")||Th("limitedAdTracking")||Th("is_lat"))}function bh(e){if("boolean"==typeof e)return e;if("number"==typeof e)return 1===e;if("string"==typeof e){var t=e.toLowerCase();if("1"===t||"true"===t||"yes"===t)return!0;if("0"===t||"false"===t||"no"===t)return!1}}var Ih=null;function Rh(e){var t={};return e.debugAdTiming&&(t.debugAdTiming=!0),void 0!==e.isLiveStream&&(t.inputStreamType=e.isLiveStream?"live":"vod"),t}function Lh(){var e,t,r,i,n,a=navigator.userAgent,s=navigator.platform,o=navigator.vendor||"",l=navigator.maxTouchPoints||0,u=navigator.deviceMemory||null,c=navigator.hardwareConcurrency||1,d={width:null===screen||void 0===screen?void 0:screen.width,height:null===screen||void 0===screen?void 0:screen.height,availWidth:null===screen||void 0===screen?void 0:screen.availWidth,availHeight:null===screen||void 0===screen?void 0:screen.availHeight,orientation:(null===(e=null===screen||void 0===screen?void 0:screen.orientation)||void 0===e?void 0:e.type)||"",pixelDepth:null===screen||void 0===screen?void 0:screen.pixelDepth},h="desktop",f="Unknown",v="Unknown",g="",p=!1,m=!1,y=!1;if(a.includes("Web0S")){f="LG",v="webOS",p=!0,h="tv";var k=a.match(/Web0S\/([^\s]+)/);g=k?"webOS ".concat(k[1]):"webOS TV"}else if(a.includes("Tizen")){f="Samsung",v="Tizen",p=!0,h="tv";var E=a.match(/Tizen\/([^\s]+)/),S=a.match(/(?:Smart-TV|SMART-TV|TV)/i)?"Smart TV":"";g=E?"Tizen ".concat(E[1]," ").concat(S).trim():"Tizen TV"}else a.includes("Philips")?(f="Philips",v="Saphi",p=!0,h="tv"):a.includes("Sharp")||a.includes("AQUOS")?(f="Sharp",v="Android TV",p=!0,h="tv"):a.includes("Android")&&(a.includes("Sony")||o.includes("Sony"))?(f="Sony",v="Android TV",p=!0,h="tv"):a.includes("Android")&&(a.includes("NetCast")||a.includes("LG"))?(f="LG",v="Android TV",p=!0,h="tv"):a.includes(" Roku")||a.includes("Roku/")?(f="Roku",v="Roku OS",p=!0,h="tv"):a.includes("AppleTV")&&(f="Apple",v="tvOS",p=!0,h="tv");if(a.includes("Android")){m=!0,v="Android",h=/Mobile/.test(a)?"mobile":"tablet",a.includes("Android")&&(0===l||a.includes("Google TV")||a.includes("XiaoMi"))&&(h="tv",p=!0,f="Unknown"===f?"Android TV":f);var T=a.match(/\(([^)]*Android[^)]*)\)/);T&&T[1]&&(g=T[1])}return/iPad|iPhone|iPod/.test(a)&&(v="iOS",h="mobile",f="Apple",navigator.maxTouchPoints>1&&/iPad/.test(a)&&(h="tablet")),m||p||/Mobile/.test(a)||(a.includes("Windows")?(v="Windows",h="desktop"):a.includes("Mac")&&!/iPhone/.test(a)?(v="macOS",h="desktop",l>1&&(h="tablet")):a.includes("Linux")&&(v="Linux",h="desktop")),"Unknown"===f&&((o.includes("Google")||a.includes("Chrome"))&&(f="Google"),o.includes("Apple")&&(f="Apple"),(o.includes("Samsung")||a.includes("SM-"))&&(f="Samsung")),y=/wv|WebView|Linux; U;/.test(a),0===(null===window||void 0===window?void 0:window.outerHeight)&&0===(null===window||void 0===window?void 0:window.outerWidth)&&(y=!0),n=window.matchMedia("(display-mode: standalone)").matches||!0===window.navigator.standalone||void 0!==(null===(r=null===(t=window.screen)||void 0===t?void 0:t.orientation)||void 0===r?void 0:r.angle),{brand:f,os:v,model:g||a.substring(0,50)+"...",deviceType:h,isSmartTV:p,isAndroid:m,isWebView:y,isWebApp:n,domain:window.location.hostname,origin:window.location.origin,path:window.location.pathname,userAgent:a,vendor:o,platform:s,screen:d,hardwareConcurrency:c,deviceMemory:u,maxTouchPoints:l,language:navigator.language,languages:(null===(i=navigator.languages)||void 0===i?void 0:i.join(","))||"",cookieEnabled:navigator.cookieEnabled,doNotTrack:navigator.doNotTrack||"",referrer:document.referrer,visibilityState:document.visibilityState}}function Ph(e){return x(this,void 0,void 0,function(){var t,r,i,n,a,s,o,l,u,c,d;return O(this,function(h){switch(h.label){case 0:if("undefined"==typeof crypto||!(null===(d=crypto.subtle)||void 0===d?void 0:d.digest))return[3,5];h.label=1;case 1:return h.trys.push([1,4,,5]),[4,crypto.subtle.digest("SHA-256",new Uint8Array([1,2,3]))];case 2:if(h.sent(),t=void 0,"undefined"!=typeof TextEncoder)t=(new TextEncoder).encode(e);else{for(r=unescape(encodeURIComponent(e)),i=new Uint8Array(r.length),s=0;s<r.length;s++)i[s]=r.charCodeAt(s);t=i}return[4,crypto.subtle.digest("SHA-256",t)];case 3:return n=h.sent(),[2,Array.from(new Uint8Array(n)).map(function(e){return e.toString(16).padStart(2,"0")}).join("")];case 4:return h.sent(),console.warn("[StormcloudVideoPlayer] crypto.subtle not supported, using fallback hash"),[3,5];case 5:for(a=0,s=0;s<e.length;s++)o=e.charCodeAt(s),a=(a<<5)-a+o,a&=a;return l=Math.abs(a).toString(16).padStart(8,"0"),u=Date.now().toString(16).padStart(12,"0"),c=Math.random().toString(16).substring(2,14).padStart(12,"0"),[2,(l+u+c).padEnd(64,"0")]}})})}function wh(e){var t=function(e){void 0===e&&(e=!0);var t=mh(),r=fh(),i=t.deviceId||(e?Sh():void 0)||r.deviceId;if(i&&!gh(i)&&!ph(i))return i}(e.isSmartTV);if(t)return"device:".concat(t);var r=oh(zd);return r?"persisted:".concat(r):"fingerprint:".concat(JSON.stringify(e))}function Ch(e){return x(this,void 0,void 0,function(){return O(this,function(t){switch(t.label){case 0:return Ih?[2,Ih]:[4,Ph(wh(e))];case 1:return[2,Ih=t.sent()]}})})}function Dh(e){return Boolean(jd()&&e)}function _h(){return x(this,arguments,void 0,function(e,t){var r,i,n,a,s,o,l;return void 0===e&&(e={}),void 0===t&&(t={}),O(this,function(u){switch(u.label){case 0:return r=Lh(),(i=!!e.debugAdTiming)&&console.log("[StormcloudVideoPlayer] clientInfo: ",JSON.stringify(r,null,2)),[4,Ch(r)];case 1:return n=u.sent(),i&&console.log("[StormcloudVideoPlayer] playerId: ",n),a=null!==(s=t.captureAt)&&void 0!==s?s:(new Date).toISOString(),[2,_({player_id:n,device_type:r.deviceType,os:r.os.toLowerCase(),ad_loaded:null!==(o=t.adLoaded)&&void 0!==o&&o,ad_detect:null!==(l=t.adDetect)&&void 0!==l&&l,capture_at:a},e.inputStreamType?{input_stream_type:e.inputStreamType}:{})]}})})}function Mh(e){return x(this,arguments,void 0,function(e,t){var r,i;return void 0===t&&(t={}),O(this,function(n){switch(n.label){case 0:if(!Dh(e))return[2];n.label=1;case 1:return n.trys.push([1,4,,5]),[4,_h(t,{adLoaded:!1,adDetect:!1})];case 2:return r=n.sent(),[4,Wd(e,"metrics",{events:[r]})];case 3:return n.sent(),[3,5];case 4:return i=n.sent(),console.error("[StormcloudVideoPlayer] Error sending initial tracking data:",i),[3,5];case 5:return[2]}})})}function xh(e,t){return x(this,arguments,void 0,function(e,t,r){var i;return void 0===r&&(r={}),O(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,Nh(e,r,{adDetect:!0,captureAt:t.timestamp})];case 1:return n.sent(),[3,3];case 2:return i=n.sent(),console.error("[StormcloudVideoPlayer] Error sending ad detect tracking:",i),[3,3];case 3:return[2]}})})}function Oh(e,t){return x(this,arguments,void 0,function(e,t,r){var i;return void 0===r&&(r={}),O(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,Nh(e,r,{adLoaded:!0,captureAt:t.timestamp})];case 1:return n.sent(),[3,3];case 2:return i=n.sent(),console.error("[StormcloudVideoPlayer] Error sending ad loaded tracking:",i),[3,3];case 3:return[2]}})})}function Fh(e,t){return x(this,arguments,void 0,function(e,t,r){var i,n;return void 0===r&&(r={}),O(this,function(a){switch(a.label){case 0:if(!Dh(e))return[2];a.label=1;case 1:return a.trys.push([1,5,,6]),[4,_h(r,{captureAt:t.timestamp})];case 2:return i=a.sent(),[4,Wd(e,"metrics",{events:[i]})];case 3:return a.sent(),[4,Wd(e,"impressions",{events:[{player_id:i.player_id,ad_played_count:1,ad_url:t.adUrl,capture_at:t.timestamp}]})];case 4:return a.sent(),[3,6];case 5:return n=a.sent(),console.error("[StormcloudVideoPlayer] Error sending ad impression tracking:",n),[3,6];case 6:return[2]}})})}function Nh(e){return x(this,arguments,void 0,function(e,t,r){var i,n;return void 0===t&&(t={}),void 0===r&&(r={}),O(this,function(a){switch(a.label){case 0:if(!Dh(e))return[2];a.label=1;case 1:return a.trys.push([1,4,,5]),[4,_h(t,r)];case 2:return i=a.sent(),[4,Wd(e,"metrics",{events:[i]})];case 3:return a.sent(),[3,5];case 4:return n=a.sent(),console.error("[StormcloudVideoPlayer] Error sending heartbeat:",n),[3,5];case 5:return[2]}})})}function Bh(){"function"!=typeof Object.assign&&(Object.assign=function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(null==e)throw new TypeError("Cannot convert undefined or null to object");for(var i=Object(e),n=0;n<t.length;n++){var a=t[n];if(null!=a)for(var s in a)Object.prototype.hasOwnProperty.call(a,s)&&(i[s]=a[s])}return i}),Array.from||(Array.from=function(e,t,r){var i=Object(e);if(null==e)throw new TypeError("Array.from requires an array-like object");for(var n=i.length>>>0,a=new Array(n),s=0;s<n;s++)a[s]=t?t.call(r,i[s],s):i[s];return a}),String.prototype.startsWith||(String.prototype.startsWith=function(e,t){return t=!t||t<0?0:+t,this.substring(t,t+e.length)===e}),String.prototype.endsWith||(String.prototype.endsWith=function(e,t){return(void 0===t||t>this.length)&&(t=this.length),this.substring(t-e.length,t)===e}),String.prototype.includes||(String.prototype.includes=function(e,t){return"number"!=typeof t&&(t=0),!(t+e.length>this.length)&&-1!==this.indexOf(e,t)}),function(){if("undefined"==typeof URLSearchParams){var e=function(){function e(t){var r=this;this.params=new Map,"string"==typeof t?this.parseQueryString(t):t instanceof e&&t.forEach(function(e,t){r.append(t,e)})}return e.prototype.parseQueryString=function(e){var t=this,r=e.startsWith("?")?e.slice(1):e;r&&r.split("&").forEach(function(e){var r=N(e.split("="),2),i=r[0],n=r[1];if(i){var a=t.safeDecodeURIComponent(i),s=n?t.safeDecodeURIComponent(n):"";t.append(a,s)}})},e.prototype.safeDecodeURIComponent=function(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch(t){return e}},e.prototype.append=function(e,t){var r=this.params.get(e)||[];r.push(String(t)),this.params.set(e,r)},e.prototype.delete=function(e){this.params.delete(e)},e.prototype.get=function(e){var t=this.params.get(e);return t&&t.length>0&&void 0!==t[0]?t[0]:null},e.prototype.getAll=function(e){return this.params.get(e)||[]},e.prototype.has=function(e){return this.params.has(e)},e.prototype.set=function(e,t){this.params.set(e,[String(t)])},e.prototype.forEach=function(e){var t=this;this.params.forEach(function(r,i){r.forEach(function(r){e(r,i,t)})})},e.prototype.toString=function(){var e=[];return this.params.forEach(function(t,r){t.forEach(function(t){e.push("".concat(encodeURIComponent(r),"=").concat(encodeURIComponent(t)))})}),e.join("&")},e}();window.URLSearchParams=e}}(),function(){if("undefined"==typeof TextEncoder){var e=function(){function e(){this.encoding="utf-8"}return e.prototype.encode=function(e){for(var t=[],r=0;r<e.length;r++){var i=e.charCodeAt(r);i<128?t.push(i):i<2048?t.push(192|i>>6,128|63&i):i<55296||i>=57344?t.push(224|i>>12,128|i>>6&63,128|63&i):(r++,i=65536+((1023&i)<<10|1023&e.charCodeAt(r)),t.push(240|i>>18,128|i>>12&63,128|i>>6&63,128|63&i))}return new Uint8Array(t)},e}();window.TextEncoder=e}}(),"undefined"==typeof Promise||Promise.prototype.finally||(Promise.prototype.finally=function(e){var t=this.constructor;return this.then(function(r){return t.resolve(e()).then(function(){return r})},function(r){return t.resolve(e()).then(function(){throw r})})})}var Uh,Vh=/^(\[[^\]]*\]|\{[^}]*\}|%%[^%]*%%)$/,Gh=/^\s|\s$/,Hh=/example\.com/i,Kh=["tfcd","npa","min_ad_duration","max_ad_duration","unviewed_position_start","impl","vad_type","gdpr","gdpr_consent","us_privacy"],jh=[{pattern:/\[RDID\]/gi,getValue:function(e){return e.deviceId}},{pattern:/\[IFA\]/gi,getValue:function(e){return e.deviceId}},{pattern:/\[ADVERTISING[_-]?ID(?:ENTIFIER)?\]/gi,getValue:function(e){return e.deviceId}},{pattern:/\[DEVICE[_-]?ID\]/gi,getValue:function(e){return e.deviceId}},{pattern:/\[IDTYPE\]/gi,getValue:function(e){return e.deviceIdType}},{pattern:/\{rdid\}/gi,getValue:function(e){return e.deviceId}},{pattern:/\{device[_-]?id\}/gi,getValue:function(e){return e.deviceId}},{pattern:/\{idtype\}/gi,getValue:function(e){return e.deviceIdType}},{pattern:/%%ADVERTISING_IDENTIFIER_PLAIN%%/gi,getValue:function(e){return e.deviceId}},{pattern:/%%ADVERTISING_ID_OPT_OUT%%/gi,getValue:function(e){return null!=e.limitAdTracking?e.limitAdTracking?"1":"0":void 0}},{pattern:/%%ADVERTISING_ID_TYPE%%/gi,getValue:function(e){return e.deviceIdType}},{pattern:/%%ADVERTISING_ID%%/gi,getValue:function(e){return e.deviceId}},{pattern:/%%LIMIT_AD_TRACKING%%/gi,getValue:function(e){return null!=e.limitAdTracking?e.limitAdTracking?"1":"0":void 0}},{pattern:/%%SESSION_ID%%/gi,getValue:function(e){return e.sessionId}},{pattern:/%%CORRELATOR%%/gi,getValue:function(e){return e.correlator}}];function qh(e){if(null==e)return!0;var t=e.trim();return!t||(!!Vh.test(t)||/^(unknown|null|undefined|none|n\/a|\$\{[^}]+\})$/i.test(t))}function Wh(){var e,t;if("undefined"!=typeof crypto&&crypto.getRandomValues)try{var r=new Uint32Array(2);crypto.getRandomValues(r);var i=2097152*(null!==(e=r[0])&&void 0!==e?e:0)+(2097151&(null!==(t=r[1])&&void 0!==t?t:0));if(i>0)return String(i)}catch(e){}return String(Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)+1)}function Yh(e,t){var r,i,n=null===(r=t.deviceId)||void 0===r?void 0:r.trim(),a=(null===(i=t.deviceIdType)||void 0===i?void 0:i.trim())||sh(),s=e.get("rdid"),o=e.get("idtype"),l=e.get("is_lat"),u=null!=t.limitAdTracking?t.limitAdTracking?"1":"0":void 0;if(n)return e.set("rdid",n),e.set("idtype",a||o||"aaid"),void e.set("is_lat",null!=u?u:qh(l)?"0":l);if(!t.isCtv)return e.delete("rdid"),e.delete("idtype"),void e.delete("is_lat");var c=Boolean(s&&!qh(s)),d=Boolean(o&&!qh(o));return c&&d&&a&&!function(e,t){if(!e||!t)return!1;var r=e.toLowerCase(),i=t.toLowerCase();return r===i||Qd.has(r)&&Qd.has(i)}(o,a)?(e.delete("rdid"),e.delete("idtype"),void e.delete("is_lat")):c?(qh(o)&&a&&e.set("idtype",a),void(qh(l)&&e.set("is_lat",null!=u?u:"0"))):(e.delete("rdid"),e.delete("idtype"),void e.delete("is_lat"))}function zh(e,t){var r,i,n,a,s=[];if(e.forEach(function(e,t){t&&!Gh.test(t)||s.push(t)}),t&&t.includes("&"))try{for(var o=F(t.split("&").slice(1)),l=o.next();!l.done;l=o.next()){var u=l.value,c=u.replace(/^\s+/,"");c&&s.push(u," ".concat(c),c)}}catch(e){r={error:e}}finally{try{l&&!l.done&&(i=o.return)&&i.call(o)}finally{if(r)throw r.error}}try{for(var d=F(new Set(s)),h=d.next();!h.done;h=d.next()){var f=h.value;f&&e.delete(f)}}catch(e){n={error:e}}finally{try{h&&!h.done&&(a=d.return)&&a.call(d)}finally{if(n)throw n.error}}}function Xh(e){if(!e)return e;try{var t=new URL(e),r=t.searchParams.get("an");if(null!==r){var i=[];if(t.searchParams.forEach(function(e,t){t&&Gh.test(t)&&i.push(t.trim())}),i.length>0){var n=B([r.replace(/\s+$/,"")],N(i),!1).filter(Boolean).join(" & ");return t.searchParams.forEach(function(e,r){r&&Gh.test(r)&&t.searchParams.delete(r)}),t.searchParams.set("an",n),t.toString().replace(/([?&]an=)([^&]*)/,function(e,t,r){return t+r.replace(/\+/g,"%20")})}}return zh(t.searchParams),t.toString()}catch(t){return e}}function Qh(e,t){var r,i,n,a,s,o=function(e,t){var r,i,n=e;try{for(var a=F(jh),s=a.next();!s.done;s=a.next()){var o=s.value,l=o.pattern,u=(0,o.getValue)(t);null!=u&&""!==u&&(n=n.replace(l,encodeURIComponent(u)))}}catch(e){r={error:e}}finally{try{s&&!s.done&&(i=a.return)&&i.call(a)}finally{if(r)throw r.error}}return n}(e,t);try{s=new URL(Xh(o))}catch(e){return function(e,t){var r=/([?&])correlator=([^&]*)/;if(r.test(e))return e.replace(r,"$1correlator=".concat(t));var i=e.includes("?")?"&":"?";return"".concat(e).concat(i,"correlator=").concat(t)}(o,t.correlator)}var l=s.searchParams;if(zh(l),l.set("correlator",t.correlator),l.set("scor",t.streamCorrelator),t.isCtv)try{for(var u=F(Kh),c=u.next();!c.done;c=u.next()){var d=c.value;l.delete(d)}}catch(e){r={error:e}}finally{try{c&&!c.done&&(i=u.return)&&i.call(u)}finally{if(r)throw r.error}}else l.set("unviewed_position_start","1");null!=t.pod&&l.set("pod",String(t.pod)),l.delete("ppos"),l.delete("lip"),null!=t.podMinDurationMs&&l.set("pmnd",String(Math.max(0,Math.round(t.podMinDurationMs)))),null!=t.podMaxDurationMs&&l.set("pmxd",String(Math.max(0,Math.round(t.podMaxDurationMs)))),null!=t.podMaxAds&&l.set("pmad",String(Math.max(1,Math.round(t.podMaxAds))));var h=l.get("url")||"";if(Hh.test(h)&&(l.delete("url"),l.delete("description_url")),!t.isCtv&&t.pageUrl&&(qh(l.get("url"))&&l.set("url",t.pageUrl),qh(l.get("description_url"))&&l.set("description_url",l.get("url")||t.pageUrl)),t.isCtv||(l.delete("an"),l.delete("msid"),l.delete("sid")),null!=t.adWillPlayMuted&&l.set("vpmute",t.adWillPlayMuted?"1":"0"),null!=t.adWillAutoPlay&&l.set("vpa",t.adWillAutoPlay?"auto":"click"),t.sessionId&&l.set("sid",t.sessionId),null!=t.deviceTypeHint?l.set("dth",String(t.deviceTypeHint)):t.isCtv&&l.set("dth","5"),Yh(l,t),!t.isCtv){var f=t.consent;null!=(null==f?void 0:f.gdpr)&&l.set("gdpr",f.gdpr),null!=(null==f?void 0:f.gdprConsent)&&l.set("gdpr_consent",f.gdprConsent),null!=(null==f?void 0:f.usPrivacy)&&l.set("us_privacy",f.usPrivacy)}t.adTest&&l.set("adtest","on"),t.programTitle&&l.set("ct_ti",t.programTitle),t.channelName&&l.set("ct_ch",t.channelName);var v=[];l.forEach(function(e,t){qh(e)&&v.push(t)});try{for(var g=F(v),p=g.next();!p.done;p=g.next()){d=p.value;l.delete(d)}}catch(e){n={error:e}}finally{try{p&&!p.done&&(a=g.return)&&a.call(g)}finally{if(n)throw n.error}}return zh(l),s.toString()}function $h(e){var t=parseFloat(e.trim());if(!Number.isNaN(t))return t;var r=e.match(/(?:^|[,\s])DURATION\s*=\s*([0-9.]+)/i)||e.match(/Duration\s*=\s*([0-9.]+)/i);if(r&&null!=r[1]){var i=r[1],n=parseFloat(i);return Number.isNaN(n)?void 0:n}}function Jh(e){var t={},r=e.match(/Elapsed\s*=\s*([0-9.]+)/i),i=e.match(/Duration\s*=\s*([0-9.]+)/i);if(r&&null!=r[1]){var n=parseFloat(r[1]);Number.isNaN(n)||(t.elapsed=n)}if(i&&null!=i[1]){var a=parseFloat(i[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}function Zh(e){for(var t,r,i,n,a={},s=/([A-Z0-9-]+)=(("[^"]*")|([^",]*))(?:,|$)/gi;null!==(n=s.exec(e));){var o=null!==(t=n[1])&&void 0!==t?t:"",l=null!==(i=null!==(r=n[3])&&void 0!==r?r:n[4])&&void 0!==i?i:"";l.startsWith('"')&&l.endsWith('"')&&(l=l.slice(1,-1)),o&&(a[o]=l)}return a}function ef(e){if(null!=e){var t="string"==typeof e?parseFloat(e):Number(e);return Number.isNaN(t)?void 0:t}}function tf(e){var t,r,i=[null==e?void 0:e.start,null==e?void 0:e.startPTS];try{for(var n=F(i),a=n.next();!a.done;a=n.next()){var s=a.value;if("number"==typeof s&&Number.isFinite(s))return s}}catch(e){t={error:e}}finally{try{a&&!a.done&&(r=n.return)&&r.call(n)}finally{if(t)throw t.error}}}function rf(e){var t,r,i,n,a=function(e){try{if("string"==typeof e)return e;var t=new TextDecoder("utf-8",{fatal:!1}).decode(e);if(t&&/[\x20-\x7E]/.test(t))return t;for(var r="",i=0;i<e.length;i++)r+=String.fromCharCode(e[i]);return r}catch(e){return}}(e.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=$h((null!==(t=s[1])&&void 0!==t?t:"").trim());return _(_(_({type:"start"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),void 0!==o?{durationSeconds:o}:{}),{raw:{id3:a}})}var l=a.match(/EXT-X-CUE-OUT-CONT:([^\r\n]*)/i);if(l){var u=Jh((null!==(r=l[1])&&void 0!==r?r:"").trim());return _(_(_({type:"progress"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),void 0!==(null==u?void 0:u.duration)?{durationSeconds:u.duration}:{}),{raw:{id3:a}})}if(a.match(/EXT-X-CUE-IN\b/i)||a.match(/CUE-IN\b/i))return _(_({type:"end"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),{raw:{id3:a}});var c=a.match(/EXT-X-DATERANGE:([^\r\n]*)/i);if(c){var d=Zh(null!==(i=c[1])&&void 0!==i?i:""),h="SCTE35-OUT"in d||void 0!==d["SCTE35-OUT"],f="SCTE35-IN"in d||void 0!==d["SCTE35-IN"],v=String(null!==(n=d.CLASS)&&void 0!==n?n:""),g=ef(d.DURATION);if(h||/com\.apple\.hls\.cue/i.test(v))return _(_(_({type:"start"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),void 0!==g?{durationSeconds:g}:{}),{raw:{id3:a,attrs:d}});if(f)return _(_({type:"end"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),{raw:{id3:a,attrs:d}})}if(/SCTE35-OUT/i.test(a))return _(_({type:"start"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),{raw:{id3:a}});if(/SCTE35-IN/i.test(a))return _(_({type:"end"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),{raw:{id3:a}});if(e.value instanceof Uint8Array){var p=pf(e.value);if(p)return p}}}function nf(e,t){if(t){var r=e[0];if(null!=r){var i=1+r;return i<e.length?i:void 0}}}function af(e,t){var r,i;return(15&(null!==(r=e[t+1])&&void 0!==r?r:0))<<8|(null!==(i=e[t+2])&&void 0!==i?i:0)}function sf(e,t,r){var i,n,a,s,o=nf(e,t);if(!(null==o||o+8>=e.length)&&0===e[o])for(var l=af(e,o),u=Math.min(e.length,o+3+l),c=o+8;c+4<=u-4;c+=4){var d=(null!==(i=e[c])&&void 0!==i?i:0)<<8|(null!==(n=e[c+1])&&void 0!==n?n:0),h=(31&(null!==(a=e[c+2])&&void 0!==a?a:0))<<8|(null!==(s=e[c+3])&&void 0!==s?s:0);0!==d&&r.add(h)}}function of(e,t,r){for(var i,n,a,s,o,l,u=t;u+2<=r;){var c=null!==(i=e[u])&&void 0!==i?i:0,d=null!==(n=e[u+1])&&void 0!==n?n:0,h=u+2,f=h+d;if(f>r)return!1;var v=d>=4?String.fromCharCode(null!==(a=e[h])&&void 0!==a?a:0,null!==(s=e[h+1])&&void 0!==s?s:0,null!==(o=e[h+2])&&void 0!==o?o:0,null!==(l=e[h+3])&&void 0!==l?l:0):"";if(138===c||"CUEI"===v||"SCTE"===v)return!0;u=f}return!1}function lf(e,t,r){var i,n,a,s,o,l,u,c=nf(e,t);if(!(null==c||c+12>=e.length)&&2===e[c])for(var d=af(e,c),h=Math.min(e.length,c+3+d),f=c+12+((15&(null!==(i=e[c+10])&&void 0!==i?i:0))<<8|(null!==(n=e[c+11])&&void 0!==n?n:0));f+5<=h-4;){var v=null!==(a=e[f])&&void 0!==a?a:0,g=(31&(null!==(s=e[f+1])&&void 0!==s?s:0))<<8|(null!==(o=e[f+2])&&void 0!==o?o:0),p=(15&(null!==(l=e[f+3])&&void 0!==l?l:0))<<8|(null!==(u=e[f+4])&&void 0!==u?u:0),m=f+5,y=Math.min(m+p,h-4);(134===v||6===v&&of(e,m,y))&&r.add(g),f=m+p}}function uf(e,t,r){if(252===e[0]&&!function(e,t){for(var r,i=0,n=0;n<e.length;n++)i=31*i+(null!==(r=e[n])&&void 0!==r?r:0)>>>0;var a="".concat(e.length,":").concat(i);if(t.has(a))return!0;if(t.add(a),t.size>200){var s=t.values().next().value;s&&t.delete(s)}return!1}(e,r)){var i=pf(e);i&&(i.raw=_(_({},"object"===R(i.raw)&&i.raw?i.raw:{}),{source:"ts-packet"}),t.push(i))}}function cf(e,t,r,i,n){var a,s=r.get(e);if(s){for(var o=0;o<t.length&&s.bytes.length<s.expectedLength;o++)s.bytes.push(null!==(a=t[o])&&void 0!==a?a:0);s.bytes.length>=s.expectedLength&&(r.delete(e),uf(new Uint8Array(s.bytes),i,n))}}function df(e,t,r,i,n,a){var s;if(0!==t.length){var o=0;if(r){var l=null!==(s=t[0])&&void 0!==s?s:0;for(i.get(e)&&l>0&&cf(e,t.subarray(1,Math.min(1+l,t.length)),i,n,a),i.delete(e),o=1+l;o+3<=t.length;){var u=t[o];if(null==u||255===u)return;var c=af(t,o),d=3+c;if(c<=0||d<=3)return;if(!(o+d<=t.length))return void i.set(e,{bytes:Array.from(t.subarray(o)),expectedLength:d});uf(t.subarray(o,o+d),n,a),o+=d}}else cf(e,t,i,n,a)}}function hf(e,t,r,i){var n=function(e){var t,r;try{for(var i=F([188,192,204]),n=i.next();!n.done;n=i.next())for(var a=n.value,s=192===a?4:0,o=0;o<a;o++){for(var l=0,u=o;u+s<e.length&&l<5&&71===e[u+s];u+=a)l++;if(l>=2)return{offset:o,packetSize:a,tsPayloadOffset:s}}}catch(e){t={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}}(e);if(!n)return[];for(var a=[],s=new Map,o=n.offset;o+n.packetSize<=e.length;o+=n.packetSize){var l=o+n.tsPayloadOffset;if(71===e[l]){var u=e[l+1],c=e[l+2],d=e[l+3];if(!(null==u||null==c||null==d||128&u)){var h=!!(64&u),f=(31&u)<<8|c,v=d>>4&3;if(1===v||3===v){var g=l+4;if(3===v){var p=e[g];if(null==p)continue;g+=1+p}var m=Math.min(l+188,e.length);if(!(g>=m||g>=e.length)){var y=e.subarray(g,m);0===f?sf(y,h,r):r.has(f)?lf(y,h,t):t.has(f)&&df(f,y,h,s,a,i)}}}}}return a}var ff=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 r=8-this.bitPos,i=Math.min(e,r);t=t<<i|this.buf[this.bytePos]>>r-i&((1<<i)-1&255),this.bitPos+=i,this.bitPos>=8&&(this.bitPos=0,this.bytePos+=1),e-=i}return t>>>0},e.prototype.skipBits=function(e){this.readBits(e)},Object.defineProperty(e.prototype,"bytePosition",{get:function(){return 0===this.bitPos?this.bytePos:this.bytePos+1},enumerable:!1,configurable:!0}),e}();function vf(e,t){if(1===e.readBits(1))return e.readBits(6),(4294967296*e.readBits(1)+e.readBits(32)+t)%8589934592/9e4;e.readBits(7)}function gf(e){var t,r,i,n,a,s,o,l,u,c,d,h,f,v,g,p,m,y;if(!(e.length<11)&&"CUEI"===String.fromCharCode(null!==(t=e[0])&&void 0!==t?t:0,null!==(r=e[1])&&void 0!==r?r:0,null!==(i=e[2])&&void 0!==i?i:0,null!==(n=e[3])&&void 0!==n?n:0)){var k=16777216*(null!==(a=e[4])&&void 0!==a?a:0)+((null!==(s=e[5])&&void 0!==s?s:0)<<16)+((null!==(o=e[6])&&void 0!==o?o:0)<<8)+(null!==(l=e[7])&&void 0!==l?l:0);if(!!!(128&(null!==(u=e[8])&&void 0!==u?u:0))){var E=null!==(c=e[9])&&void 0!==c?c:0,S=!!(64&E),T=10;if(!!!(128&E))if((T+=1+6*(null!==(d=e[T])&&void 0!==d?d:0))>e.length)return;var A=void 0;if(S){if(T+5>e.length)return;A=(4294967296*(null!==(h=e[T])&&void 0!==h?h:0)+16777216*(null!==(f=e[T+1])&&void 0!==f?f:0)+((null!==(v=e[T+2])&&void 0!==v?v:0)<<16)+((null!==(g=e[T+3])&&void 0!==g?g:0)<<8)+(null!==(p=e[T+4])&&void 0!==p?p:0))/9e4,T+=5}if(!(T+2>e.length))if(T+=1,!((T+=1+(null!==(m=e[T])&&void 0!==m?m:0))>=e.length)){var b=function(e){switch(e){case 16:case 34:case 48:case 50:case 52:case 54:return"start";case 17:case 35:case 49:case 51:case 53:case 55:return"end";default:return}}(null!==(y=e[T])&&void 0!==y?y:0);if(b)return _(_({type:b},void 0!==A?{durationSeconds:A}:{}),{segmentationEventId:k})}}}}function pf(e){var t=new ff(e);if(252===t.readBits(8)){t.readBits(1),t.readBits(1),t.readBits(2);var r=t.readBits(12);if(!(r<=0||e.length<3+r)){t.readBits(8),t.readBits(1),t.readBits(6);var i=4294967296*t.readBits(1)+t.readBits(32);t.readBits(8),t.readBits(12);var n,a=t.readBits(12),s=t.readBits(8),o=void 0,l=void 0,u=void 0,c=t.bytePosition;if(5===s){u=t.readBits(32);var d=1===t.readBits(1);if(t.readBits(7),d)return;var h=1===t.readBits(1),f=1===t.readBits(1),v=1===t.readBits(1),g=1===t.readBits(1);if(t.readBits(4),n=h?"start":"end",f&&!g)l=vf(t,i);else if(!f)for(var p=t.readBits(8),m=0;m<p;m++)if(t.readBits(8),!g){var y=vf(t,i);void 0===l&&(l=y)}if(v)t.readBits(6),t.readBits(1),o=(4294967296*t.readBits(1)+t.readBits(32))/9e4;t.readBits(16),t.readBits(8),t.readBits(8)}else{if(6!==s)return;l=vf(t,i)}var k=function(e,t){var r,i,n,a;if(!(t+2>e.length))for(var s=(null!==(r=e[t])&&void 0!==r?r:0)<<8|(null!==(i=e[t+1])&&void 0!==i?i:0),o=t+2,l=Math.min(e.length,o+s);o+2<=l;){var u=null!==(n=e[o])&&void 0!==n?n:0,c=o+2,d=c+(null!==(a=e[o+1])&&void 0!==a?a:0);if(d>l)return;if(2===u){var h=gf(e.subarray(c,d));if(h)return h}o=d}}(e,4095===a?t.bytePosition:c+a);if(k&&(n=k.type,void 0===o&&(o=k.durationSeconds)),n)return _(_(_({type:n},void 0!==l?{ptsSeconds:l}:{}),void 0!==o?{durationSeconds:o}:{}),{raw:_(_({splice_command_type:s},void 0!==u?{splice_event_id:u}:{}),void 0!==(null==k?void 0:k.segmentationEventId)?{segmentation_event_id:k.segmentationEventId}:{})})}}}var mf=function(){function e(e,t){this.pendingScte35Cues=new Map,this.recentScte35CueKeys=new Map,this.recentScte35CueLimit=200,this.tsScte35Pids=new Set,this.pmtPids=new Set,this.processedTsScte35Sections=new Set,this.debug=e,this.callbacks=t}return Object.defineProperty(e.prototype,"pendingScte35CueKey",{get:function(){return this.pendingScte35CueKeyValue},set:function(e){this.pendingScte35CueKeyValue=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"activeScte35BreakKey",{get:function(){return this.activeScte35BreakKeyValue},set:function(e){this.activeScte35BreakKeyValue=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"scheduledScte35BreakKey",{get:function(){return this.scheduledScte35BreakKeyValue},set:function(e){this.scheduledScte35BreakKeyValue=e},enumerable:!1,configurable:!0}),e.prototype.createScte35CueContext=function(e,t,r){var i={source:e,readiness:t};"number"==typeof(null==r?void 0:r.sn)&&(i.fragmentSn=r.sn);var n=tf(r);return void 0!==n&&(i.fragmentStartSeconds=n),i},e.prototype.onScte35Cue=function(e,t){var r=this.createScte35Cue(e,t),i=this.getPendingScte35CueKey(r);if("early"===t.readiness)return this.pendingScte35Cues.set(i,r),this.trimRecentScte35CueMaps(),void("start"===e.type&&this.callbacks.onEarlyStartCue(e,t.fragmentSn,r.key));"end"!==e.type||this.shouldAcceptScte35EndCue(r)?"start"===e.type&&this.hasRecentlyHandledScte35Cue(r)?this.debug&&console.log("[StormcloudVideoPlayer] Ignoring duplicate SCTE-35 start cue",{key:r.key,source:r.source}):(this.pendingScte35Cues.delete(i),this.markScte35CueHandled(r),this.callbacks.onPlaybackCue(e,r.key)):this.debug&&console.log("[StormcloudVideoPlayer] Ignoring SCTE-35 end cue",{key:r.key,activeScte35BreakKey:this.activeScte35BreakKeyValue,inAdBreak:this.callbacks.isInAdBreak(),source:r.source})},e.prototype.activatePendingScte35CuesForFragment=function(e){var t=this,r="number"==typeof(null==e?void 0:e.sn)?e.sn:void 0;void 0!==r&&Array.from(this.pendingScte35Cues.entries()).filter(function(e){return N(e,2)[1].fragmentSn===r}).forEach(function(i){var n,a=N(i,2),s=a[0],o=a[1];t.pendingScte35Cues.delete(s);var l={source:o.source,readiness:"playback"};l.fragmentSn=r;var u=null!==(n=o.fragmentStartSeconds)&&void 0!==n?n:tf(e);void 0!==u&&(l.fragmentStartSeconds=u),t.onScte35Cue(o.marker,l)})},e.prototype.createScte35Cue=function(e,t){var r={marker:e,source:t.source,readiness:t.readiness,key:this.getScte35CueKey(e,t)};return void 0!==t.fragmentSn&&(r.fragmentSn=t.fragmentSn),void 0!==t.fragmentStartSeconds&&(r.fragmentStartSeconds=t.fragmentStartSeconds),r},e.prototype.getScte35CueKey=function(e,t){var r,i,n,a=this.getScte35MarkerRaw(e),s=this.toIdentityString(null==a?void 0:a.splice_event_id);if(s)return"splice:".concat(s);var o=this.toIdentityString(null==a?void 0:a.segmentation_event_id);if(o)return"segmentation:".concat(o);var l=this.toIdentityString(null===(r=null==a?void 0:a.attrs)||void 0===r?void 0:r.ID);if(l)return"daterange:".concat(l);var u=this.toIdentityString(null===(i=null==a?void 0:a.attrs)||void 0===i?void 0:i["SCTE35-OUT"])||this.toIdentityString(null===(n=null==a?void 0:a.attrs)||void 0===n?void 0:n["SCTE35-IN"]);return u?"daterange-scte:".concat(u):"number"==typeof e.ptsSeconds&&Number.isFinite(e.ptsSeconds)?"pts:".concat(Math.round(2*e.ptsSeconds)/2):void 0!==t.fragmentSn?"fragment:".concat(t.fragmentSn):"".concat(t.source,":wallclock:").concat(Math.floor(Date.now()/1e3))},e.prototype.getPendingScte35CueKey=function(e){return"".concat(e.marker.type,":").concat(e.key,":").concat(void 0!==e.fragmentSn?e.fragmentSn:"unknown")},e.prototype.getScte35MarkerRaw=function(e){return"object"===R(e.raw)&&null!==e.raw?e.raw:{}},e.prototype.toIdentityString=function(e){return"number"==typeof e&&Number.isFinite(e)?String(e):"string"==typeof e&&e.trim().length>0?e.trim():void 0},e.prototype.isStrongScte35CueKey=function(e){return!(!e||!(e.startsWith("splice:")||e.startsWith("segmentation:")||e.startsWith("daterange:")||e.startsWith("daterange-scte:")))},e.prototype.hasRecentlyHandledScte35Cue=function(e){if(this.activeScte35BreakKeyValue===e.key||this.scheduledScte35BreakKeyValue===e.key)return!0;var t="".concat(e.marker.type,":").concat(e.key);return this.recentScte35CueKeys.has(t)},e.prototype.markScte35CueHandled=function(e){this.recentScte35CueKeys.set("".concat(e.marker.type,":").concat(e.key),Date.now()),this.trimRecentScte35CueMaps()},e.prototype.trimRecentScte35CueMaps=function(){for(;this.recentScte35CueKeys.size>this.recentScte35CueLimit;){if(!(e=this.recentScte35CueKeys.keys().next().value))break;this.recentScte35CueKeys.delete(e)}for(;this.pendingScte35Cues.size>this.recentScte35CueLimit;){var e;if(!(e=this.pendingScte35Cues.keys().next().value))break;this.pendingScte35Cues.delete(e)}},e.prototype.shouldAcceptScte35EndCue=function(e){return!!this.callbacks.isInAdBreak()&&(!this.isStrongScte35CueKey(this.activeScte35BreakKeyValue)||!this.isStrongScte35CueKey(e.key)||this.activeScte35BreakKeyValue===e.key)},e}(),yf=function(){function e(e,t){this.vmapBreaks=[],this.consumedVmapBreakIds=new Set,this.streamCorrelator=Wh(),this.consentSignals={},this.podCounter=0,this.podAssignedByPrefetch=!1,this.lastHeartbeatTime=0,this.defaultPodMaxAds=6,this.defaultPodMaxDurationMs=12e4,this.config=e,this.video=t}return Object.defineProperty(e.prototype,"viewCorrelator",{get:function(){return e="undefined"!=typeof window?window.location.pathname+window.location.search:"",Uh&&Uh.key===e||(Uh={key:e,value:Wh()}),Uh.value;var e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"debug",{get:function(){return!!this.config.debugAdTiming},enumerable:!1,configurable:!0}),e.prototype.isVmapEnabled=function(){var e;return!(!this.config.isVmap||!(null===(e=this.config.vmapUrl)||void 0===e?void 0:e.trim()))},e.prototype.fetchAdConfiguration=function(){return x(this,void 0,void 0,function(){var e,t,r,i,n,a,s,o,l,u,c,d,h,f,v,g;return O(this,function(p){switch(p.label){case 0:return this.isVmapEnabled()?[4,this.fetchAndParseVmap(this.config.vmapUrl)]:[3,2];case 1:return p.sent(),this.debug&&console.log("[StormcloudVideoPlayer] VMAP mode enabled"),[2];case 2:return e=this.config.vastMode||"default",this.debug&&console.log("[StormcloudVideoPlayer] VAST mode:",e),"adstorm"===e?this.config.licenseKey?(t="https://adstorm.co/api-adstorm-dev/adstorm/vast/".concat(this.config.licenseKey),this.apiVastTagUrl=t,this.debug&&console.log("[StormcloudVideoPlayer] Using AdStorm VAST endpoint (adstorm mode):",t),[2]):(this.debug&&console.warn("[StormcloudVideoPlayer] AdStorm mode requires a license key"),[2]):this.config.vastTagUrl?(this.apiVastTagUrl=Xh(this.config.vastTagUrl),this.debug&&console.log("[StormcloudVideoPlayer] Using custom VAST tag URL:",this.apiVastTagUrl),[2]):(r="https://adstorm.co/api-adstorm-dev/adstorm/ads/web",this.debug&&console.log("[StormcloudVideoPlayer] Fetching ad configuration from:",r),i={},this.config.licenseKey&&(i.Authorization="Bearer ".concat(this.config.licenseKey)),[4,fetch(r,{headers:i})]);case 3:return(n=p.sent()).ok?[4,n.json()]:(this.debug&&console.warn("[StormcloudVideoPlayer] Failed to fetch ad configuration: ".concat(n.status)),[2]);case 4:if(a=p.sent(),s=null===(d=null===(c=null===(u=a.response)||void 0===u?void 0:u.ima)||void 0===c?void 0:c["publisherdesk.ima"])||void 0===d?void 0:d.payload){o=s;try{o=decodeURIComponent(s)}catch(e){console.warn("[StormcloudVideoPlayer] imaPayload was not URI-encoded; using as-is:",s)}console.log("[StormcloudVideoPlayer] Raw VAST tag URL (from API):",o),this.apiVastTagUrl=Xh(o),this.debug&&console.log("[StormcloudVideoPlayer] Normalized VAST tag URL:",this.apiVastTagUrl)}else this.debug&&console.warn("[StormcloudVideoPlayer] No VAST tag URL found in /ads/web response");return null!=(l=null===(g=null===(v=null===(f=null===(h=a.response)||void 0===h?void 0:h.options)||void 0===f?void 0:f.vast)||void 0===v?void 0:v.cue_tones)||void 0===g?void 0:g.number_ads)&&l>0&&(this.apiNumberAds=l,this.debug&&console.log("[StormcloudVideoPlayer] Number of ads per break from API:",this.apiNumberAds)),[2]}})})},e.prototype.fetchAndParseVmap=function(e){return x(this,void 0,void 0,function(){var t,r,i;return O(this,function(n){switch(n.label){case 0:if(!e.trim())return[2];n.label=1;case 1:return n.trys.push([1,4,,5]),[4,fetch(e)];case 2:if(!(t=n.sent()).ok)throw new Error("Failed to fetch VMAP (".concat(t.status,")"));return[4,t.text()];case 3:return r=n.sent(),this.vmapBreaks=this.parseVmapToBreaks(r),this.consumedVmapBreakIds.clear(),this.debug&&console.log("[StormcloudVideoPlayer] Loaded ".concat(this.vmapBreaks.length," VMAP ad break(s) from:"),e),[3,5];case 4:return i=n.sent(),this.vmapBreaks=[],this.consumedVmapBreakIds.clear(),this.debug&&console.warn("[StormcloudVideoPlayer] Failed to load VMAP:",i),[3,5];case 5:return[2]}})})},e.prototype.parseVmapToBreaks=function(e){var t=this;if("undefined"==typeof DOMParser)return[];var r=(new DOMParser).parseFromString(e,"application/xml");if(r.querySelector("parsererror"))return this.debug&&console.warn("[StormcloudVideoPlayer] Invalid VMAP XML received"),[];var i="http://www.iab.net/videosuite/vmap",n=Array.from(r.getElementsByTagNameNS(i,"AdBreak"));0===n.length&&(n=Array.from(r.querySelectorAll("AdBreak, vmap\\:AdBreak"))),0===n.length&&(n=Array.from(r.getElementsByTagName("*")).filter(function(e){return"AdBreak"===e.localName}));var a=[];return n.forEach(function(e,r){var n,s=(e.getAttribute("timeOffset")||"").trim(),o=t.parseVmapTimeOffsetToMs(s);if(null!=o){var l=e.getElementsByTagNameNS(i,"AdTagURI")[0];l||(l=null!==(n=e.querySelector("AdTagURI, vmap\\:AdTagURI"))&&void 0!==n?n:void 0);var u=((null==l?void 0:l.textContent)||"").trim();if(u){var c=e.getAttribute("breakId")||"vmap-break-".concat(r,"-").concat(s||"unknown");a.push({id:c,startTimeMs:o,vastTagUrl:u})}}}),a.sort(function(e,t){return(e.startTimeMs<0?Number.MAX_SAFE_INTEGER:e.startTimeMs)-(t.startTimeMs<0?Number.MAX_SAFE_INTEGER:t.startTimeMs)}),a},e.prototype.parseVmapTimeOffsetToMs=function(e){if(e){var t=e.trim().toLowerCase();if("start"===t)return 0;if("end"===t)return-1;var r=e.match(/^(\d{1,2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?$/);if(r){var i=N(r,5),n=i[1],a=i[2],s=i[3],o=i[4],l=void 0===o?"0":o;return 1e3*(3600*Number(n)+60*Number(a)+Number(s))+Number(l.padEnd(3,"0").slice(0,3))}var u=e.match(/^(\d+(?:\.\d+)?)%$/);if(u){var c=Number(u[1])/100,d=this.video.duration;return Number.isFinite(d)&&d>0?Math.floor(1e3*d*c):void 0}}},e.prototype.getAdBreakKey=function(e){return e.id?e.id:"".concat(e.startTimeMs,"-").concat(e.vastTagUrl||"")},e.prototype.resolveBreakStartMs=function(e){if(e.startTimeMs>=0)return e.startTimeMs;if(-1===e.startTimeMs){var t=this.video.duration;if(Number.isFinite(t)&&t>0)return Math.floor(1e3*t)}},e.prototype.findCurrentOrNextBreak=function(e){var t,r,i,n,a,s=this.vmapBreaks,o=null!==(i=this.config.driftToleranceMs)&&void 0!==i?i:1e3;try{for(var l=F(s),u=l.next();!u.done;u=l.next()){var c=u.value;if(!this.consumedVmapBreakIds.has(this.getAdBreakKey(c))){var d=this.resolveBreakStartMs(c);null!=d&&d<=e+o&&(null==a||d>(null!==(n=this.resolveBreakStartMs(a))&&void 0!==n?n:0))&&(a=c)}}}catch(e){t={error:e}}finally{try{u&&!u.done&&(r=l.return)&&r.call(l)}finally{if(t)throw t.error}}return a},e.prototype.findBreakForTime=function(e){var t,r,i=this.vmapBreaks;try{for(var n=F(i),a=n.next();!a.done;a=n.next()){var s=a.value;if(!this.consumedVmapBreakIds.has(this.getAdBreakKey(s))){var o=this.resolveBreakStartMs(s);if(null!=o)if(s.durationMs){var l=o+s.durationMs;if(e>=o&&e<l)return s}else if(e>=o)return s}}}catch(e){t={error:e}}finally{try{a&&!a.done&&(r=n.return)&&r.call(n)}finally{if(t)throw t.error}}},e.prototype.selectVastTagsForBreak=function(e){if(e&&e.vastTagUrl)return e.vastTagUrl.includes(",")?e.vastTagUrl.split(",").map(function(e){return e.trim()}).filter(function(e){return e.length>0}):[e.vastTagUrl]},e.prototype.beginNewAdPod=function(){this.podCounter++},e.prototype.resolvePodParams=function(e){var t=null!=e&&e>0?e:null!=this.config.podMaxDurationMs&&this.config.podMaxDurationMs>0?this.config.podMaxDurationMs:this.defaultPodMaxDurationMs;return{maxAds:this.config.podMaxAds&&this.config.podMaxAds>0?this.config.podMaxAds:this.apiNumberAds&&this.apiNumberAds>0?this.apiNumberAds:this.defaultPodMaxAds,minDurationMs:this.config.podExactDuration&&null!=t?t:0,maxDurationMs:t}},e.prototype.getPalDescriptionUrl=function(){if(this.apiVastTagUrl)try{var e=new URL(this.apiVastTagUrl).searchParams;return e.get("description_url")||e.get("url")||void 0}catch(e){return}},e.prototype.generatePodVastUrl=function(e,t,r,i,n){var a,s=n?r.getOriginalMutedState():this.video.muted,o=$d(!!this.config.ctvAdRequest),l=Qh(e,_(_(_({correlator:this.viewCorrelator,streamCorrelator:this.streamCorrelator,pod:this.podCounter>0?this.podCounter:void 0,podMaxAds:t.maxAds,podMinDurationMs:t.minDurationMs,podMaxDurationMs:t.maxDurationMs,isCtv:o.isCtv,pageUrl:o.isCtv||"undefined"==typeof window?void 0:Od(window.location.href),adWillPlayMuted:s,adWillAutoPlay:!!this.config.autoplay,sessionId:o.sessionId,deviceId:o.deviceId,deviceIdType:o.deviceIdType,limitAdTracking:o.limitAdTracking,deviceTypeHint:o.deviceTypeHint,adTest:this.config.adTest},this.config.programTitle?{programTitle:this.config.programTitle}:{}),this.config.channelName?{channelName:this.config.channelName}:{}),{consent:this.consentSignals})),u=i.injectNonce(l);return console.log("[StormcloudVideoPlayer] Resolved optimized-pod request URL (pod=".concat(this.podCounter,", pmad=").concat(t.maxAds,", pmnd=").concat(t.minDurationMs,", pmxd=").concat(null!==(a=t.maxDurationMs)&&void 0!==a?a:"?","):"),u),u},e.prototype.initializeTracking=function(){var e=this;Mh(this.config.licenseKey,Rh(this.config)).then(function(){e.heartbeatInterval=window.setInterval(function(){e.sendHeartbeatIfNeeded()},5e3)}).catch(function(t){e.debug&&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,Nh(this.config.licenseKey,Rh(this.config)).catch(function(t){e.debug&&console.warn("[StormcloudVideoPlayer] Failed to send heartbeat:",t)}))},e.prototype.destroyTracking=function(){this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=void 0)},e}(),kf=function(){function e(e,t,r){this.adRequestWatchdogToken=null,this.adFailsafeToken=null,this.ptsDriftEmaMs=0,this.adBreakPlayedDurationMs=0,this.adBreakEpoch=0,this.adRequestTokenCounter=0,this.activeAdRequestToken=null,this.currentAdIndex=0,this.totalAdsInBreak=0,this.totalAdRequestsInBreak=0,this.maxTotalAdRequestsPerBreak=10,this.lastAdRequestTime=0,this.consecutiveFailures=0,this.maxConsecutiveFailures=5,this.minAdRequestIntervalMs=3e3,this.backoffBaseMs=1e3,this.maxBackoffMs=15e3,this.defaultMinRemainingMsToStartAd=4e3,this.failedVastUrls=new Set,this.temporaryFailureUrls=new Map,this.temporaryFailureCooldownMs=3e4,this.globalConsecutiveNoFills=0,this.globalNoFillThreshold=3,this.globalNoFillCooldownUntil=0,this.globalNoFillBackoffBaseMs=5e3,this.globalNoFillBackoffMaxMs=6e4,this.globalLastGamRequestTime=0,this.globalMinGamIntervalMs=3e3,this.config=e,this.video=t,this.callbacks=r}return Object.defineProperty(e.prototype,"debug",{get:function(){return!!this.config.debugAdTiming},enumerable:!1,configurable:!0}),e.prototype.scheduleAdStopCountdown=function(e){var t=this;this.clearAdStopTimer();var r=Math.max(0,Math.floor(e));0!==r?this.adStopTimerId=window.setTimeout(function(){t.ensureAdStoppedByTimer()},r):this.ensureAdStoppedByTimer()},e.prototype.clearAdStopTimer=function(){null!=this.adStopTimerId&&(clearTimeout(this.adStopTimerId),this.adStopTimerId=void 0)},e.prototype.ensureAdStoppedByTimer=function(){this.adStopTimerId=void 0,this.callbacks.onAdStopTimerFired()},e.prototype.scheduleAdStartIn=function(e,t,r){var i=this;void 0===t&&(t={type:"start"}),this.clearAdStartTimer();var n=Math.max(0,Math.floor(e));0!==n?this.adStartTimerId=window.setTimeout(function(){i.callbacks.onAdStartTimerFired(t,r)},n):this.callbacks.onAdStartTimerFired(t,r)},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.resolveScteBreakStartWallClockMs=function(e){var t=Date.now();if("number"!=typeof e.ptsSeconds)return t;var r=1e3*this.video.currentTime-this.ptsDriftEmaMs,i=1e3*e.ptsSeconds-r;return Number.isFinite(i)?t+Math.floor(i):t},e.prototype.setAdBreakDurationBoundary=function(e){this.expectedAdBreakDurationMs=e,null!=e&&null!=this.currentAdBreakStartWallClockMs?this.scteAdBreakEndWallClockMs=this.currentAdBreakStartWallClockMs+e:this.scteAdBreakEndWallClockMs=void 0},e.prototype.scheduleAdStopAtBreakBoundary=function(){null!=this.expectedAdBreakDurationMs&&this.scheduleAdStopCountdown(this.getWallClockRemainingAdMs())},e.prototype.getWallClockRemainingAdMs=function(){var e=this.getAdBreakEndWallClockMs();return null!=e?Math.max(0,e-Date.now()):0},e.prototype.getAdBreakEndWallClockMs=function(){return null!=this.scteAdBreakEndWallClockMs?this.scteAdBreakEndWallClockMs:null!=this.expectedAdBreakDurationMs&&null!=this.currentAdBreakStartWallClockMs?this.currentAdBreakStartWallClockMs+this.expectedAdBreakDurationMs:void 0},e.prototype.getDurationBudgetRemainingMs=function(){return null==this.expectedAdBreakDurationMs?0:Math.max(0,this.expectedAdBreakDurationMs-this.adBreakPlayedDurationMs)},e.prototype.getLoadedAdDurationMs=function(e){var t,r=null===(t=e.getLoadedAdDuration)||void 0===t?void 0:t.call(e);return null==r||r<=0?0:Math.round(1e3*r)},e.prototype.adFitsRemainingBudget=function(e){return e<=0||e<=this.getDurationBudgetRemainingMs()},e.prototype.logAdDurationDecision=function(e,t,r){var i,n;if(this.debug){var a=this.getDurationBudgetRemainingMs(),s=null!==(n=null===(i=r.getLoadedAdId)||void 0===i?void 0:i.call(r))&&void 0!==n?n:"unknown";e?console.log("[AD-DURATION] Accepted ad id=".concat(s,", duration=").concat(t,"ms, budget remaining after play=").concat(Math.max(0,a-t),"ms")):console.log("[AD-DURATION] Rejected ad id=".concat(s,", duration=").concat(t,"ms exceeds remaining budget=").concat(a,"ms — requesting another ad"))}},e.prototype.recordPlayedAdDuration=function(e){var t,r=this.getLoadedAdDurationMs(e);r<=0||(this.adBreakPlayedDurationMs+=r,this.debug&&console.log("[AD-DURATION] Played ".concat(r,"ms — total played=").concat(this.adBreakPlayedDurationMs,"ms / ").concat(null!==(t=this.expectedAdBreakDurationMs)&&void 0!==t?t:"?","ms")))},e.prototype.ensureLoadedAdFitsBudget=function(e){var t=this.getLoadedAdDurationMs(e),r=this.adFitsRemainingBudget(t);return this.logAdDurationDecision(r,t,e),r},e.prototype.rejectLoadedAdForDuration=function(e){try{e.destroy()}catch(e){}},e.prototype.markAdStarted=function(){this.currentAdIndex++,this.totalAdsInBreak=this.currentAdIndex,this.totalAdRequestsInBreak++,this.lastAdRequestTime=Date.now()},e.prototype.notePodAdStarted=function(){this.currentAdIndex++,this.totalAdsInBreak=this.currentAdIndex},e.prototype.getRemainingAdMs=function(){var e=this.getWallClockRemainingAdMs(),t=this.getDurationBudgetRemainingMs();return null==this.expectedAdBreakDurationMs?e:Math.min(e,t)},e.prototype.getMinRemainingMsToStartAd=function(){var e=this.config.minRemainingMsToStartAd;return"number"==typeof e&&e>=0?e:this.defaultMinRemainingMsToStartAd},e.prototype.hasTimeToStartAnotherAd=function(){var e=this.getMinRemainingMsToStartAd();return this.getWallClockRemainingAdMs()>e&&this.getDurationBudgetRemainingMs()>e},e.prototype.isTemporaryAdError=function(e){var t,r=(null===(t=null==e?void 0:e.message)||void 0===t?void 0:t.toLowerCase())||"";return!!(r.includes("no ads available")||r.includes("no fill")||r.includes("nofill"))||(!!r.includes("timeout")||(!(!r.includes("rate limit")&&!r.includes("too many requests"))||!!r.includes("ad playback error")))},e.prototype.isUrlInCooldown=function(e){var t=this.temporaryFailureUrls.get(e);return null!=t&&(!(Date.now()-t>=this.temporaryFailureCooldownMs)||(this.temporaryFailureUrls.delete(e),!1))},e.prototype.cleanupTemporaryFailures=function(){var e,t,r=Date.now();try{for(var i=F(this.temporaryFailureUrls),n=i.next();!n.done;n=i.next()){var a=N(n.value,2),s=a[0];r-a[1]>=this.temporaryFailureCooldownMs&&this.temporaryFailureUrls.delete(s)}}catch(t){e={error:t}}finally{try{n&&!n.done&&(t=i.return)&&t.call(i)}finally{if(e)throw e.error}}},e.prototype.isGamInCooldown=function(){return Date.now()<this.globalNoFillCooldownUntil},e.prototype.recordGamNoFill=function(){if(this.globalConsecutiveNoFills++,this.globalConsecutiveNoFills>=this.globalNoFillThreshold){var e=this.globalConsecutiveNoFills-this.globalNoFillThreshold,t=Math.min(this.globalNoFillBackoffBaseMs*Math.pow(2,e),this.globalNoFillBackoffMaxMs);this.globalNoFillCooldownUntil=Date.now()+t,this.debug&&console.log("[CIRCUIT-BREAKER] GAM cooldown activated: ".concat(t,"ms (").concat(this.globalConsecutiveNoFills," consecutive no-fills)"))}},e.prototype.resetGamNoFillCounter=function(){this.globalConsecutiveNoFills>0&&this.debug&&console.log("[CIRCUIT-BREAKER] Resetting no-fill counter (was ".concat(this.globalConsecutiveNoFills,")")),this.globalConsecutiveNoFills=0,this.globalNoFillCooldownUntil=0},e.prototype.enforceGlobalRateLimit=function(){return x(this,void 0,void 0,function(){var e,t,r;return O(this,function(i){switch(i.label){case 0:return e=Date.now(),(t=e-this.globalLastGamRequestTime)<this.globalMinGamIntervalMs?(r=this.globalMinGamIntervalMs-t,this.debug&&console.log("[RATE-LIMIT] Waiting ".concat(r,"ms before next GAM request")),[4,new Promise(function(e){return setTimeout(e,r)})]):[3,2];case 1:i.sent(),i.label=2;case 2:return this.globalLastGamRequestTime=Date.now(),[2]}})})},e.prototype.startAdRequestWatchdog=function(e){var t,r=this;this.clearAdRequestWatchdog();var i=null!==(t=this.config.adFailsafeTimeoutMs)&&void 0!==t?t:1e4;this.adRequestWatchdogToken=e,this.adRequestWatchdogId=window.setTimeout(function(){r.adRequestWatchdogToken===e&&(r.adRequestWatchdogId=void 0,r.adRequestWatchdogToken=null,r.activeAdRequestToken===e&&(r.activeAdRequestToken=null),r.logAdState("ad_request_timeout",{token:e,timeoutMs:i}),r.callbacks.onWatchdogTimeout())},i),this.logAdState("ad_request_watchdog_started",{token:e,timeoutMs:i})},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,r=this;this.clearAdFailsafeTimer();var i=null!==(t=this.config.adFailsafeTimeoutMs)&&void 0!==t?t:1e4;this.adFailsafeToken=e,this.adFailsafeTimerId=window.setTimeout(function(){r.adFailsafeToken===e&&(r.adFailsafeTimerId=void 0,r.adFailsafeToken=null,r.activeAdRequestToken===e&&(r.activeAdRequestToken=null),r.logAdState("ad_failsafe_triggered",{token:e,failsafeMs:i,videoPaused:r.video.paused}),r.callbacks.onFailsafeTimeout())},i),this.logAdState("ad_failsafe_started",{token:e,failsafeMs:i})},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){if(void 0===t&&(t={}),this.debug){var r=this.callbacks.getAdState(),i=r.inAdBreak,n=r.showAds,a=r.adPlaying;console.log("[StormcloudVideoPlayer][AdState]",_({event:e,timestamp:(new Date).toISOString(),showAds:n,adPlaying:a,inAdBreak:i,activeAdRequestToken:this.activeAdRequestToken},t))}},e.prototype.resetForBreakEnd=function(){this.clearAdStopTimer(),this.clearAdStartTimer(),this.clearAdRequestWatchdog(),this.clearAdFailsafeTimer(),this.activeAdRequestToken=null,this.expectedAdBreakDurationMs=void 0,this.currentAdBreakStartWallClockMs=void 0,this.scteAdBreakEndWallClockMs=void 0,this.adBreakPlayedDurationMs=0,this.currentAdIndex=0,this.totalAdsInBreak=0,this.consecutiveFailures=0,this.globalConsecutiveNoFills=0,this.adBreakEpoch++},e.prototype.destroy=function(){this.clearAdStopTimer(),this.clearAdStartTimer(),this.clearAdFailsafeTimer(),this.clearAdRequestWatchdog()},e}(),Ef=function(){function e(e,t){this.video=e,this.debug=t}return e.prototype.ensureContainer=function(){if(!this.container){var e=document.createElement("div");e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.right="0",e.style.bottom="0",e.style.display="none",e.style.alignItems="center",e.style.justifyContent="center",e.style.pointerEvents="none",e.style.zIndex="5",e.style.backgroundColor="#000",e.style.transition="opacity 0.3s ease-in-out",e.style.opacity="0",this.video.parentElement?(this.video.parentElement.appendChild(e),this.container=e):this.debug&&console.warn("[StormcloudVideoPlayer] Video element has no parent for placeholder container")}},e.prototype.show=function(){var e=this;if(this.ensureContainer(),this.container){this.video.muted||(this.video.muted=!0,this.debug&&console.log("[StormcloudVideoPlayer] Muted video when showing placeholder"));var t="none"===this.container.style.display||"0"===this.container.style.opacity;this.container.style.transition=t?"none":"opacity 0.3s ease-in-out",this.container.style.backgroundColor="#000",this.container.style.display="flex",this.container.offsetHeight,this.container.style.opacity="1",this.container.style.pointerEvents="auto",t&&requestAnimationFrame(function(){e.container&&(e.container.style.transition="opacity 0.3s ease-in-out")}),this.debug&&console.log("[StormcloudVideoPlayer] Showing placeholder layer (between content and ad layer)")}},e.prototype.hide=function(){var e=this;this.container&&(this.container.style.opacity="0",setTimeout(function(){e.container&&(e.container.style.display="none",e.container.style.pointerEvents="none",e.container.style.backgroundColor="#000")},300),this.debug&&console.log("[StormcloudVideoPlayer] Hiding placeholder layer"))},e.prototype.destroy=function(){this.container&&(this.container.parentElement&&this.container.parentElement.removeChild(this.container),this.container=void 0)},e}(),Sf=function(){function e(e,t,r,i,n){this.isLiveStream=!1,this.nativeHlsMode=!1,this.videoSrcProtection=null,this.reloadingLiveStream=!1,this.bufferedSegmentsCount=0,this.shouldAutoplayAfterBuffering=!1,this.hasInitialBufferCompleted=!1,this.latencyProfileApplied=!1,this.config=e,this.video=t,this.cueManager=r,this.timing=i,this.callbacks=n}return Object.defineProperty(e.prototype,"debug",{get:function(){return!!this.config.debugAdTiming},enumerable:!1,configurable:!0}),e.prototype.shouldUseNativeHls=function(e){if("other"===e())return!0;var t=this.video.canPlayType("application/vnd.apple.mpegurl");return!(!this.config.allowNativeHls||!t)},e.prototype.setupNativeHls=function(){return x(this,void 0,void 0,function(){var e,t,r,i;return O(this,function(n){switch(n.label){case 0:return this.nativeHlsMode=!0,this.videoSrcProtection=this.config.src,this.video.src=this.config.src,this.isLiveStream=null!==(t=this.config.isLiveStream)&&void 0!==t?t:null!==(r=this.config.lowLatencyMode)&&void 0!==r&&r,this.debug&&(e=this.isLiveStream?"live (main video continues muted during ads)":"vod (main video pauses during ads)",console.log("[StormcloudVideoPlayer] Using native HLS playback:",{isLive:this.isLiveStream,allowNativeHls:this.config.allowNativeHls,adBehavior:e})),this.config.autoplay?[4,null===(i=this.video.play())||void 0===i?void 0:i.catch(function(){})]:[3,2];case 1:n.sent(),n.label=2;case 2:return[2]}})})},e.prototype.setupHls=function(){var e=this;this.hls=new md({enableWorker:!0,backBufferLength:30,liveDurationInfinity:!0,lowLatencyMode:!!this.config.lowLatencyMode,maxLiveSyncPlaybackRate:1.1,maxBufferLength:30,maxMaxBufferLength:600,maxBufferSize:6e7,maxBufferHole:1,highBufferWatchdogPeriod:2,nudgeOffset:.2,nudgeMaxRetry:5,startPosition:-1}),this.hls.on(md.Events.MEDIA_ATTACHED,function(){var t;null===(t=e.hls)||void 0===t||t.loadSource(e.config.src)}),this.hls.on(md.Events.MANIFEST_PARSED,function(t,r){return x(e,void 0,void 0,function(){var e,t,r,i,n,a,s;return O(this,function(o){switch(o.label){case 0:return this.isLiveStream=null!==(t=this.config.isLiveStream)&&void 0!==t?t:null!==(n=null===(i=null===(r=this.hls)||void 0===r?void 0:r.levels)||void 0===i?void 0:i.some(function(e){var t,r;return!0===(null===(t=null==e?void 0:e.details)||void 0===t?void 0:t.live)||"LIVE"===(null===(r=null==e?void 0:e.details)||void 0===r?void 0:r.type)}))&&void 0!==n&&n,[4,this.callbacks.onManifestParsed(this.isLiveStream)];case 1:return o.sent(),this.bufferedSegmentsCount=0,this.hasInitialBufferCompleted=!1,this.shouldAutoplayAfterBuffering=!!this.config.autoplay,this.latencyProfileApplied=!1,this.detectedLowLatencyStream=void 0,e=null!==(a=this.config.minSegmentsBeforePlay)&&void 0!==a?a:2,this.debug&&console.log("[StormcloudVideoPlayer] Waiting for",e,"segments to buffer before playback"),0!==e&&this.config.autoplay?[3,3]:(this.hasInitialBufferCompleted=!0,this.config.autoplay?[4,null===(s=this.video.play())||void 0===s?void 0:s.catch(function(){})]:[3,3]);case 2:o.sent(),o.label=3;case 3:return this.reloadingLiveStream=!1,[2]}})})}),this.hls.on(md.Events.LEVEL_LOADED,function(t,r){var i,n,a,s;if(e.applyStreamLatencyProfile(null==r?void 0:r.details),!e.callbacks.isInAdBreak()&&!e.callbacks.hasPendingAdBreak()){var o=null==r?void 0:r.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=(i=void 0,F(d)),f=h.next();!f.done;f=h.next()){var v=f.value,g="",p="";if(Array.isArray(v))g=String(null!==(a=v[0])&&void 0!==a?a:""),p=String(null!==(s=v[1])&&void 0!==s?s:"");else if("string"==typeof v){var m=v.indexOf(":");m>=0?(g=v.substring(0,m),p=v.substring(m+1)):g=v}if(g&&(g.includes("EXT-X-CUE-OUT")||g.includes("EXT-X-DATERANGE"))){var y=g.includes("EXT-X-DATERANGE")?Zh(p):{};if(g.includes("EXT-X-CUE-OUT")||"SCTE35-OUT"in y||void 0!==y["SCTE35-OUT"]){var k=$h(p),E=_(_({type:"start"},void 0!==k?{durationSeconds:k}:{}),{raw:{tag:g,value:p,earlyDetection:!0}});return e.debug&&console.log("[StormcloudVideoPlayer] EARLY SCTE-35 DETECTION: Ad break marker found in fragment",u,"- starting pre-fetch (NOT playing yet)"),void e.callbacks.onScte35Cue(E,_({},e.cueManager.createScte35CueContext("manifest","early",c)))}}}}catch(e){i={error:e}}finally{try{f&&!f.done&&(n=h.return)&&n.call(h)}finally{if(i)throw i.error}}}}}),this.hls.on(md.Events.FRAG_BUFFERED,function(t,r){return x(e,void 0,void 0,function(){var e,t,r,i=this;return O(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.debug&&console.log("[StormcloudVideoPlayer] Buffered segment ".concat(this.bufferedSegmentsCount,"/").concat(e)),this.bufferedSegmentsCount>=e?(this.hasInitialBufferCompleted=!0,this.shouldAutoplayAfterBuffering?(this.debug&&console.log("[StormcloudVideoPlayer] Initial buffer complete (".concat(this.bufferedSegmentsCount," segments). Starting playback.")),[4,null===(r=this.video.play())||void 0===r?void 0:r.catch(function(e){i.debug&&console.warn("[StormcloudVideoPlayer] Autoplay failed:",e)})]):[3,2]):[3,2]);case 1:n.sent(),n.label=2;case 2:return[2]}})})}),this.hls.on(md.Events.FRAG_PARSING_METADATA,function(t,r){((null==r?void 0:r.samples)||[]).map(function(e){return{key:"ID3",value:null==e?void 0:e.data,ptsSeconds:null==e?void 0:e.pts}}).forEach(function(t){return e.onId3Tag(t)})}),this.hls.on(md.Events.FRAG_LOADED,function(t,r){var i;e.processFragmentScte35Payload(null==r?void 0:r.payload,"number"==typeof(null===(i=null==r?void 0:r.frag)||void 0===i?void 0:i.sn)?r.frag.sn:void 0,tf(null==r?void 0:r.frag))}),this.hls.on(md.Events.FRAG_DECRYPTED,function(t,r){var i;e.processFragmentScte35Payload(null==r?void 0:r.payload,"number"==typeof(null===(i=null==r?void 0:r.frag)||void 0===i?void 0:i.sn)?r.frag.sn:void 0,tf(null==r?void 0:r.frag))}),this.hls.on(md.Events.FRAG_CHANGED,function(t,r){var i,n,a,s,o,l=null==r?void 0:r.frag,u=null==l?void 0:l.tagList;if(Array.isArray(u)){try{for(var c=F(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 p=Jh(v),m=_(_(_({type:"progress"},void 0!==(null==p?void 0:p.duration)?{durationSeconds:p.duration}:{}),void 0!==(null==p?void 0:p.elapsed)?{ptsSeconds:p.elapsed}:{}),{raw:{tag:f,value:v}});e.callbacks.onScte35Cue(m,_({},e.cueManager.createScte35CueContext("manifest","playback",l)))}else if(f.includes("EXT-X-CUE-OUT")){var y=$h(v);m=_(_({type:"start"},void 0!==y?{durationSeconds:y}:{}),{raw:{tag:f,value:v}});e.callbacks.onScte35Cue(m,_({},e.cueManager.createScte35CueContext("manifest","playback",l)))}else if(f.includes("EXT-X-CUE-IN"))e.callbacks.onScte35Cue({type:"end",raw:{tag:f,value:v}},_({},e.cueManager.createScte35CueContext("manifest","playback",l)));else if(f.includes("EXT-X-DATERANGE")){var k=Zh(v),E="SCTE35-OUT"in k||void 0!==k["SCTE35-OUT"],S="SCTE35-IN"in k||void 0!==k["SCTE35-IN"],T=String(null!==(o=k.CLASS)&&void 0!==o?o:""),A=ef(k.DURATION);if(E||/com\.apple\.hls\.cue/i.test(T)){m=_(_({type:"start"},void 0!==A?{durationSeconds:A}:{}),{raw:{tag:f,value:v,attrs:k}});e.callbacks.onScte35Cue(m,_({},e.cueManager.createScte35CueContext("manifest","playback",l)))}S&&e.callbacks.onScte35Cue({type:"end",raw:{tag:f,value:v,attrs:k}},_({},e.cueManager.createScte35CueContext("manifest","playback",l)))}}}catch(e){i={error:e}}finally{try{d&&!d.done&&(n=c.return)&&n.call(c)}finally{if(i)throw i.error}}e.callbacks.activatePendingCuesForFragment(l)}else e.callbacks.activatePendingCuesForFragment(l)}),this.hls.on(md.Events.ERROR,function(t,r){var i,n;if(null==r?void 0:r.fatal)switch(r.type){case md.ErrorTypes.NETWORK_ERROR:null===(i=e.hls)||void 0===i||i.startLoad();break;case md.ErrorTypes.MEDIA_ERROR:null===(n=e.hls)||void 0===n||n.recoverMediaError();break;default:e.callbacks.onFatalDestroy()}}),this.hls.attachMedia(this.video)},e.prototype.isLowLatencyStream=function(){return this.detectedLowLatencyStream},e.prototype.applyStreamLatencyProfile=function(e){var t;if(!this.latencyProfileApplied&&this.hls&&e){if(!0!==e.live)return this.latencyProfileApplied=!0,void(this.detectedLowLatencyStream=!1);var r=this.isLowLatencyManifest(e),i=r&&!!this.config.lowLatencyMode;this.detectedLowLatencyStream=i,this.latencyProfileApplied=!0;var n=this.hls.config;i?(n.maxLiveSyncPlaybackRate=1.5,n.maxBufferHole=.5,delete n.liveSyncDuration):(n.maxLiveSyncPlaybackRate=1.1,n.maxBufferHole=1,delete n.liveSyncDuration,n.liveSyncDurationCount=3),this.debug&&console.log("[StormcloudVideoPlayer] Live latency profile: ".concat(i?"LL-HLS (low latency)":"standard live (stability)"),{isLowLatencyManifest:r,lowLatencyModeRequested:!!this.config.lowLatencyMode,canBlockReload:e.canBlockReload,partTarget:e.partTarget,partHoldBack:e.partHoldBack,partListLength:Array.isArray(e.partList)?e.partList.length:0,targetDuration:null!==(t=e.targetduration)&&void 0!==t?t:e.targetDuration,maxLiveSyncPlaybackRate:n.maxLiveSyncPlaybackRate,maxBufferHole:n.maxBufferHole})}},e.prototype.isLowLatencyManifest=function(e){if(!e)return!1;var t=Array.isArray(e.partList)&&e.partList.length>0,r="number"==typeof e.partTarget&&e.partTarget>0,i="number"==typeof e.partHoldBack&&e.partHoldBack>0,n=!0===e.canBlockReload;return t||r||i||n},e.prototype.onId3Tag=function(e){"number"==typeof e.ptsSeconds&&this.timing.updatePtsDrift(e.ptsSeconds);var t=rf(e);t&&this.callbacks.onScte35Cue(t,{source:"id3",readiness:"playback"})},e.prototype.processFragmentScte35Payload=function(e,t,r){var i=this,n=function(e){if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e)){var t=e;return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}}(e);n&&hf(n,this.cueManager.tsScte35Pids,this.cueManager.pmtPids,this.cueManager.processedTsScte35Sections).forEach(function(e){var n={source:"ts",readiness:"early"};void 0!==t&&(n.fragmentSn=t),void 0!==r&&(n.fragmentStartSeconds=r),i.callbacks.onScte35Cue(e,n)})},e.prototype.getLiveSyncPosition=function(){var e,t=null===(e=this.hls)||void 0===e?void 0:e.liveSyncPosition;return"number"==typeof t&&Number.isFinite(t)?t:void 0},e.prototype.restartLoadAt=function(e){if(this.hls)try{this.hls.stopLoad(),this.hls.startLoad(e)}catch(e){this.debug&&console.warn("[StormcloudVideoPlayer] Failed to restart HLS load at live edge:",e)}},e.prototype.recoverMediaError=function(){if(this.hls)try{this.hls.recoverMediaError()}catch(e){this.debug&&console.warn("[StormcloudVideoPlayer] recoverMediaError() failed:",e)}},e.prototype.reloadLiveStream=function(){var e=this,t=this.hls;if(t){this.debug&&console.log("[StormcloudVideoPlayer] Hard-reloading live stream (destroy hls → reset video → fresh setupHls)");try{this.reloadingLiveStream=!0,t.stopLoad(),t.detachMedia(),t.destroy(),this.hls=void 0;try{this.video.removeAttribute("src"),this.video.load()}catch(e){console.warn("[StormcloudVideoPlayer] video.load() threw after src removal:",e)}}catch(e){return this.reloadingLiveStream=!1,this.hls=void 0,void(this.debug&&console.warn("[StormcloudVideoPlayer] Failed to tear down during hard-reload:",e))}window.setTimeout(function(){if(e.hls)e.reloadingLiveStream=!1;else try{e.setupHls()}catch(t){e.reloadingLiveStream=!1,e.debug&&console.warn("[StormcloudVideoPlayer] Failed to rebuild pipeline during hard-reload:",t)}},600)}},e.prototype.destroy=function(){var e;null===(e=this.hls)||void 0===e||e.destroy(),this.hls=void 0},e}();function Tf(e){return e.getOriginalMutedState()?0:e.getOriginalVolume()}var Af=function(){function e(e,t,r,i,n){this.inAdBreak=!1,this.showAds=!1,this.isShowingPlaceholder=!1,this.adDetectSentForCurrentBreak=!1,this.continuousFetchingActive=!1,this.continuousFetchLoopRunning=!1,this.adRequestQueue=[],this.adPodQueue=[],this.maxPlaceholderDurationMs=5e3,this.pendingAdBreak=null,this.host=e,this.timing=t,this.adConfig=r,this.cueManager=i,this.placeholder=n}return Object.defineProperty(e.prototype,"debug",{get:function(){return!!this.host.config.debugAdTiming},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"analyticsContext",{get:function(){return Rh(this.host.config)},enumerable:!1,configurable:!0}),e.prototype.nextAdRequestUrl=function(e){var t=Math.min(this.timing.getWallClockRemainingAdMs(),this.timing.getDurationBudgetRemainingMs()),r=t>0?t:void 0;return this.host.generatePodVastUrl(e,r)},e.prototype.attachImaEventListeners=function(){var e=this,t=this.host.getAdPlayer();t.on("pod_ad_started",function(t){var r;e.timing.notePodAdStarted(),e.debug&&console.log("[POD] Playing pod ad ".concat(null!=(null==t?void 0:t.index)?t.index+1:"?","/").concat(null!==(r=null==t?void 0:t.total)&&void 0!==r?r:"?"))}),t.on("ad_click",function(){e.host.onAdClick()}),t.on("ad_interaction",function(t){t&&e.host.onAdInteraction(t)}),t.on("all_ads_completed",function(){Fh(e.host.config.licenseKey,{source:"hls",adIndex:e.timing.currentAdIndex,timestamp:(new Date).toISOString()},e.analyticsContext).catch(function(){}),e.timing.recordPlayedAdDuration(e.host.getAdPlayer());var t=e.timing.getRemainingAdMs();e.timing.consecutiveFailures=0,e.debug&&console.log("[StormcloudVideoPlayer] all_ads_completed event received - remaining=".concat(t,"ms, queued ads=").concat(e.adRequestQueue.length),e.adRequestQueue.length>0?{queuedUrls:B([],N(e.adRequestQueue),!1)}:{}),e.inAdBreak&&(e.timing.hasTimeToStartAnotherAd()?e.tryNextAvailableAdWithRateLimit():e.handleAdPodComplete())}),t.on("ad_error",function(t){var r="Ad playback failed";if(t){var i=t.code||t.errorCode||"unknown",n=t.vastErrorCode,a=t.message||t.errorMessage||"Unknown error",s=t.cause||t.innerError||t.error;if(r="Ad error: AdError ".concat(i,": ").concat(a),n&&"N/A"!==n&&n!==i&&(r+=" (VAST Error Code: ".concat(n,")")),s){var o="string"==typeof s?s:s.message||String(s);r+=". Caused by: ".concat(o)}}console.error("[AD-ERROR]",r,t||""),e.handleAdFailure()}),t.on("content_pause",function(){e.timing.clearAdFailsafeTimer(),e.timing.clearAdRequestWatchdog(),e.timing.activeAdRequestToken=null,e.showAds=!0,e.timing.resetGamNoFillCounter(),e.inAdBreak&&null!=e.timing.expectedAdBreakDurationMs&&null==e.timing.getAdBreakEndWallClockMs()&&(e.timing.scheduleAdStopAtBreakBoundary(),e.debug&&console.log("[StormcloudVideoPlayer] Starting ad break timer on content_pause (first ad starting)")),e.host.getAdPlayer().setAdVolume(Tf(e.host.getAdPlayer())),e.isShowingPlaceholder&&(e.debug&&console.log("[StormcloudVideoPlayer] Hiding placeholder - new ads starting"),e.host.getAdPlayer().hidePlaceholder(),e.isShowingPlaceholder=!1)}),t.on("content_resume",function(){if(Fh(e.host.config.licenseKey,{source:"hls",adIndex:e.timing.currentAdIndex,timestamp:(new Date).toISOString()},e.analyticsContext).catch(function(){}),e.host.video.muted||(e.host.video.muted=!0,e.debug&&console.log("[StormcloudVideoPlayer] Muted video on content_resume (ad ended, gap between ads)")),e.timing.clearAdFailsafeTimer(),e.timing.clearAdRequestWatchdog(),e.timing.activeAdRequestToken=null,e.showAds=!1,e.inAdBreak){e.timing.consecutiveFailures=0,e.timing.recordPlayedAdDuration(e.host.getAdPlayer());var t=e.timing.getRemainingAdMs();e.debug&&console.log("[CONTINUOUS-FETCH] content_resume event: remaining=".concat(t,"ms, queued ads=").concat(e.adRequestQueue.length),e.adRequestQueue.length>0?{queuedUrls:B([],N(e.adRequestQueue),!1)}:{}),e.timing.hasTimeToStartAnotherAd()?e.tryNextAvailableAdWithRateLimit():e.handleAdPodComplete()}})},e.prototype.recreateAdController=function(){this.debug&&console.log("[StormcloudVideoPlayer] Recreating AdController for new ad");var e=this.inAdBreak&&this.showAds,t=this.host.getAdPlayer();e&&t&&(this.debug&&console.log("[StormcloudVideoPlayer] Showing placeholder before destroying old AdController"),this.placeholder.show(),t.showPlaceholder(),this.isShowingPlaceholder=!0);var r=t.getOriginalMutedState(),i=t.getOriginalVolume();if(t)try{t.destroy(),this.host.video.muted=!0}catch(e){this.debug&&console.warn("[StormcloudVideoPlayer] Error destroying old AdController:",e)}var n=this.host.shouldContinueLiveStreamDuringAds(),a=this.host.createAdPlayer(n);this.host.setAdPlayer(a),a.initialize(),a.updateOriginalMutedState(r,i),this.attachImaEventListeners(),e&&(this.placeholder.show(),a.showPlaceholder(),this.isShowingPlaceholder=!0)},e.prototype.clearPendingAdBreak=function(){null!=this.prefetchTimerId&&(clearTimeout(this.prefetchTimerId),this.prefetchTimerId=void 0),this.pendingAdBreak=null,this.cueManager.pendingScte35CueKey=void 0,this.adConfig.podAssignedByPrefetch=!1},e.prototype.handleAdStart=function(e){return x(this,void 0,void 0,function(){var t,r,i,n,a,s,o;return O(this,function(l){switch(l.label){case 0:if((t=this.adConfig.findCurrentOrNextBreak(1e3*this.host.video.currentTime))&&this.adConfig.consumedVmapBreakIds.add(this.adConfig.getAdBreakKey(t)),(r=this.adConfig.selectVastTagsForBreak(t))&&r.length>0&&r[0])i=r[0];else{if(!this.adConfig.apiVastTagUrl)return this.clearPendingAdBreak(),[2];i=this.adConfig.apiVastTagUrl}return n=null!=e.durationSeconds?1e3*e.durationSeconds:null==t?void 0:t.durationMs,this.debug&&(a=this.host.config.isLiveStream?"LIVE":"VOD",console.log("[CONTINUOUS-FETCH] ".concat(a," MODE: Target duration=").concat(n,"ms"))),this.timing.failedVastUrls.clear(),this.timing.temporaryFailureUrls.clear(),this.timing.consecutiveFailures=0,this.continuousFetchingActive=!0,this.isShowingPlaceholder=!1,this.timing.totalAdRequestsInBreak=0,this.adConfig.podAssignedByPrefetch?this.adConfig.podAssignedByPrefetch=!1:this.adConfig.beginNewAdPod(),s=this.host.video.muted,o=this.host.video.volume,this.host.getAdPlayer().updateOriginalMutedState(s,o),this.inAdBreak=!0,this.timing.adBreakPlayedDurationMs=0,this.timing.currentAdIndex=0,this.timing.totalAdsInBreak=0,this.adPodQueue=[],this.showAds=!1,null==this.timing.expectedAdBreakDurationMs&&null!=n&&(this.timing.expectedAdBreakDurationMs=n),[4,this.startOptimizedPod(i,n,s,o)];case 1:return l.sent()?[3,3]:(this.debug&&console.log("[POD] Initial pod request did not fill; attempting top-up pod request"),this.continuousFetchingActive=!0,this.startContinuousFetching(i),[4,this.tryNextAvailableAdWithRateLimit()]);case 2:l.sent(),l.label=3;case 3:return[2]}})})},e.prototype.startOptimizedPod=function(e,t,r,i){return x(this,void 0,void 0,function(){var n,a,s,o,l,u,c;return O(this,function(d){switch(d.label){case 0:if(this.pendingAdBreak&&this.pendingAdBreak.vastUrls.length>0?(n=this.pendingAdBreak.vastUrls[0],this.clearPendingAdBreak()):n=this.host.generatePodVastUrl(e,t),!n)return[2,!1];this.continuousFetchingActive=!1,this.recreateAdController(),a=this.host.getAdPlayer(),s=++this.timing.adRequestTokenCounter,this.timing.activeAdRequestToken=s,this.timing.startAdRequestWatchdog(s),d.label=1;case 1:return d.trys.push([1,5,,6]),[4,this.timing.enforceGlobalRateLimit()];case 2:return d.sent(),this.timing.lastAdRequestTime=Date.now(),[4,a.requestAds(n)];case 3:return d.sent(),this.timing.clearAdRequestWatchdog(),this.timing.activeAdRequestToken!==s?[2,!0]:(o=null!==(c=null===(u=a.getPodAdCount)||void 0===u?void 0:u.call(a))&&void 0!==c?c:1)<1?[2,!1]:(this.debug&&console.log(1===o?"[POD] Response contained a single ad; playing it and enabling pod top-up":"[POD] Optimized pod returned ".concat(o," ads; playing pod in one controller")),Oh(this.host.config.licenseKey,{source:"hls",vastUrl:n,timestamp:(new Date).toISOString()},this.analyticsContext).catch(function(){}),this.timing.startAdFailsafeTimer(s),[4,a.play()]);case 4:return d.sent(),this.timing.markAdStarted(),null!=this.timing.expectedAdBreakDurationMs&&null==this.timing.getAdBreakEndWallClockMs()&&this.timing.scheduleAdStopAtBreakBoundary(),a.setAdVolume(r?0:i),this.timing.consecutiveFailures=0,this.continuousFetchingActive=!0,this.startContinuousFetching(e),[2,!0];case 5:return l=d.sent(),this.timing.clearAdRequestWatchdog(),this.timing.clearAdFailsafeTimer(),this.timing.activeAdRequestToken===s&&(this.timing.activeAdRequestToken=null),this.debug&&console.warn("[POD] Optimized pod request/play failed:",l),this.timing.isTemporaryAdError(l)&&this.timing.temporaryFailureUrls.set(n,Date.now()),this.continuousFetchingActive=!0,this.recreateAdController(),[2,!1];case 6:return[2]}})})},e.prototype.startContinuousFetching=function(e){this.continuousFetchingActive&&(this.continuousFetchLoopRunning?this.debug&&console.log("[CONTINUOUS-FETCH] Fetch loop already running, skipping duplicate start"):(this.debug&&console.log("[CONTINUOUS-FETCH] Starting continuous ad fetching loop"),this.continuousFetchLoopRunning=!0,this.continuousFetchLoop(e)))},e.prototype.continuousFetchLoop=function(e){return x(this,void 0,void 0,function(){var t,r,i;return O(this,function(n){switch(n.label){case 0:t=this.timing.adBreakEpoch,r=function(){var t,r,n;return O(this,function(a){switch(a.label){case 0:return Math.min(i.timing.getWallClockRemainingAdMs(),i.timing.getDurationBudgetRemainingMs())<=i.timing.getMinRemainingMsToStartAd()?(i.debug&&console.log("[CONTINUOUS-FETCH] Not enough ad break time left (wall=".concat(i.timing.getWallClockRemainingAdMs(),"ms, budget=").concat(i.timing.getDurationBudgetRemainingMs(),"ms), stopping URL generation")),[2,"break"]):i.timing.isGamInCooldown()?(i.debug&&console.log("[CIRCUIT-BREAKER] GAM in cooldown, stopping URL generation"),[2,"break"]):i.timing.consecutiveFailures>=i.timing.maxConsecutiveFailures?(i.debug&&console.log("[CONTINUOUS-FETCH] Too many consecutive failures (".concat(i.timing.consecutiveFailures,"), stopping URL generation")),[2,"break"]):i.timing.totalAdRequestsInBreak>=i.timing.maxTotalAdRequestsPerBreak?(i.debug&&console.log("[CONTINUOUS-FETCH] Maximum ad requests reached (".concat(i.timing.maxTotalAdRequestsPerBreak,"), stopping")),[2,"break"]):i.adRequestQueue.length>=5?(i.debug&&console.log("[CONTINUOUS-FETCH] URL queue full (".concat(i.adRequestQueue.length,"), waiting...")),[4,new Promise(function(e){return setTimeout(e,1e3)})]):[3,2];case 1:case 3:return a.sent(),[2,"continue"];case 2:return!(t=i.nextAdRequestUrl(e))||i.timing.failedVastUrls.has(t)||i.timing.isUrlInCooldown(t)?[4,new Promise(function(e){return setTimeout(e,500)})]:[3,4];case 4:return i.debug&&(r=B(B([],N(i.adRequestQueue),!1),[t],!1),console.log("[CONTINUOUS-FETCH] Queued VAST URL (queue size: ".concat(r.length,")"),{queuedUrls:r})),i.adRequestQueue.push(t),n=i.timing.consecutiveFailures>0?Math.min(1e3*Math.pow(2,i.timing.consecutiveFailures),5e3):500,[4,new Promise(function(e){return setTimeout(e,n)})];case 5:return a.sent(),[2]}})},i=this,n.label=1;case 1:return this.continuousFetchingActive&&this.inAdBreak&&t===this.timing.adBreakEpoch?[5,r()]:[3,3];case 2:return"break"===n.sent()?[3,3]:[3,1];case 3:return this.continuousFetchLoopRunning=!1,this.debug&&console.log("[CONTINUOUS-FETCH] URL generation loop ended (queued: ".concat(this.adRequestQueue.length,")"),this.adRequestQueue.length>0?{queuedUrls:B([],N(this.adRequestQueue),!1)}:{}),[2]}})})},e.prototype.stopContinuousFetching=function(){this.continuousFetchingActive=!1,this.continuousFetchLoopRunning=!1,this.placeholder.hide(),this.debug&&console.log("[CONTINUOUS-FETCH] Stopping continuous ad fetching")},e.prototype.tryNextAvailableAdWithRateLimit=function(){return x(this,void 0,void 0,function(){var e,t,r,i,n,a;return O(this,function(s){switch(s.label){case 0:return this.inAdBreak?(e=this.timing.adBreakEpoch,this.timing.consecutiveFailures>=this.timing.maxConsecutiveFailures?(this.debug&&console.log("[CONTINUOUS-FETCH] Too many consecutive failures (".concat(this.timing.consecutiveFailures,"), ending ad break gracefully")),this.handleAdPodComplete(),[2]):(t=Math.pow(2,this.timing.consecutiveFailures),r=Math.min(this.timing.backoffBaseMs*t,this.timing.maxBackoffMs),i=this.timing.minAdRequestIntervalMs+(this.timing.consecutiveFailures>0?r:0),(n=Date.now()-this.timing.lastAdRequestTime)<i?(a=i-n,this.debug&&console.log("[CONTINUOUS-FETCH] Rate limiting: waiting ".concat(a,"ms before next request (backoff: ").concat(this.timing.consecutiveFailures," failures)")),[4,new Promise(function(e){return setTimeout(e,a)})]):[3,2])):[2];case 1:s.sent(),s.label=2;case 2:return this.inAdBreak&&e===this.timing.adBreakEpoch?[2,this.tryNextAvailableAd(0)]:[2]}})})},e.prototype.tryNextAvailableAd=function(){return x(this,arguments,void 0,function(e){var t,r,i,n;return void 0===e&&(e=0),O(this,function(a){switch(a.label){case 0:if(!this.inAdBreak)return[2];if(t=this.timing.getRemainingAdMs(),!this.timing.hasTimeToStartAnotherAd())return this.debug&&console.log("[CONTINUOUS-FETCH] Not enough time remaining (".concat(t,"ms) to start another ad, ending ad break")),this.handleAdPodComplete(),[2];if(this.timing.isGamInCooldown())return this.debug&&console.log("[CIRCUIT-BREAKER] GAM in cooldown, ending ad break gracefully"),this.handleAdPodComplete(),[2];if(this.timing.consecutiveFailures>=this.timing.maxConsecutiveFailures)return this.debug&&console.log("[CONTINUOUS-FETCH] Too many consecutive failures (".concat(this.timing.consecutiveFailures,"), ending ad break")),this.handleAdPodComplete(),[2];this.timing.cleanupTemporaryFailures(),a.label=1;case 1:if(!(this.adRequestQueue.length>0))return[3,9];if(!(r=this.adRequestQueue.shift()))return[3,1];if(this.timing.failedVastUrls.has(r))return this.debug&&console.log("[CONTINUOUS-FETCH] Skipping permanently-failed URL, trying next..."),[3,1];if(this.timing.isUrlInCooldown(r))return this.debug&&console.log("[CONTINUOUS-FETCH] Skipping URL in cooldown (recent no-fill), trying next..."),[3,1];this.debug&&console.log("[CONTINUOUS-FETCH] Requesting next ad via HLS ad player (".concat(this.timing.currentAdIndex+1,", ").concat(this.adRequestQueue.length," remaining in queue)")),a.label=2;case 2:return a.trys.push([2,4,,8]),[4,this.playSingleAd(r)];case 3:return a.sent(),this.timing.consecutiveFailures=0,[3,8];case 4:return i=a.sent(),n=i.message,this.debug&&console.log("[CONTINUOUS-FETCH] Ad request failed:",n),n.includes("ad_duration_exceeds_budget")?[4,this.tryNextAvailableAdWithRateLimit()]:[3,6];case 5:return a.sent(),[2];case 6:return n.includes("permanently failed")||n.includes("in cooldown")||this.timing.consecutiveFailures++,[4,this.tryNextAvailableAdWithRateLimit()];case 7:return a.sent(),[3,8];case 8:return[2];case 9:return this.continuousFetchingActive&&e<3&&t>2e3?(this.debug&&console.log("[CONTINUOUS-FETCH] Queue empty, waiting for URLs... (".concat(e+1,"/").concat(3,")")),[4,new Promise(function(e){return setTimeout(e,500)})]):[3,12];case 10:return a.sent(),[4,this.tryNextAvailableAd(e+1)];case 11:return a.sent(),[2];case 12:return!this.isShowingPlaceholder&&t>1e3?this.showPlaceholderAndWaitForAds():(this.debug&&console.log("[CONTINUOUS-FETCH] No more ads available, ending ad break"),this.handleAdPodComplete()),[2]}})})},e.prototype.playSingleAd=function(e){return x(this,void 0,void 0,function(){var t,r,i,n,a;return O(this,function(s){switch(s.label){case 0:if(this.host.getAdPlayer().isAdPlaying())return[2];if(this.timing.failedVastUrls.has(e))throw this.debug&&console.warn("[AD-ERROR] Skipping permanently-failed VAST URL:",e),new Error("VAST URL permanently failed");if(this.timing.isUrlInCooldown(e))throw this.debug&&console.warn("[AD-ERROR] Skipping URL in cooldown (recent no-fill):",e),new Error("VAST URL in cooldown after no-fill");if(this.timing.consecutiveFailures>=this.timing.maxConsecutiveFailures)throw this.debug&&console.warn("[AD-ERROR] Too many consecutive failures, not requesting more ads"),new Error("Too many consecutive failures");if(this.timing.isGamInCooldown())throw this.debug&&console.warn("[CIRCUIT-BREAKER] GAM in cooldown, skipping ad request"),new Error("GAM in cooldown");this.recreateAdController(),t=++this.timing.adRequestTokenCounter,this.timing.activeAdRequestToken=t,this.timing.startAdRequestWatchdog(t),s.label=1;case 1:return s.trys.push([1,8,,9]),[4,this.timing.enforceGlobalRateLimit()];case 2:return s.sent(),this.timing.lastAdRequestTime=Date.now(),[4,(r=this.host.getAdPlayer()).requestAds(e)];case 3:if(s.sent(),Oh(this.host.config.licenseKey,{source:"hls",vastUrl:e,timestamp:(new Date).toISOString()},this.analyticsContext).catch(function(){}),this.timing.clearAdRequestWatchdog(),this.timing.activeAdRequestToken!==t)return[2];if(!this.timing.ensureLoadedAdFitsBudget(r))throw this.timing.rejectLoadedAdForDuration(r),this.recreateAdController(),new Error("ad_duration_exceeds_budget");s.label=4;case 4:return s.trys.push([4,6,,7]),this.timing.startAdFailsafeTimer(t),[4,r.play()];case 5:return s.sent(),this.timing.markAdStarted(),null!=this.timing.expectedAdBreakDurationMs&&null==this.timing.getAdBreakEndWallClockMs()&&this.timing.scheduleAdStopAtBreakBoundary(),r.setAdVolume(Tf(r)),this.timing.consecutiveFailures=0,this.timing.temporaryFailureUrls.delete(e),[3,7];case 6:throw i=s.sent(),this.debug&&console.error("[AD-ERROR] Failed to play ad:",i),this.timing.isTemporaryAdError(i)?(this.timing.temporaryFailureUrls.set(e,Date.now()),this.debug&&console.log("[AD-ERROR] Temporary play error - URL can be retried after cooldown")):(this.timing.failedVastUrls.add(e),this.debug&&console.log("[AD-ERROR] Permanent play error - URL blacklisted")),this.timing.clearAdFailsafeTimer(),this.timing.activeAdRequestToken===t&&(this.timing.activeAdRequestToken=null),i;case 7:return[3,9];case 8:throw n=s.sent(),a=(null==n?void 0:n.message)||"",this.debug&&console.error("[AD-ERROR] Ad request failed:",a),this.timing.isTemporaryAdError(n)?(this.timing.temporaryFailureUrls.set(e,Date.now()),this.debug&&console.log("[AD-ERROR] Temporary error (no-fill/timeout) - URL can be retried after cooldown")):(this.timing.failedVastUrls.add(e),this.debug&&console.log("[AD-ERROR] Permanent error - URL blacklisted:",a)),this.timing.clearAdRequestWatchdog(),this.timing.clearAdFailsafeTimer(),this.timing.activeAdRequestToken===t&&(this.timing.activeAdRequestToken=null),n;case 9:return[2]}})})},e.prototype.showPlaceholderAndWaitForAds=function(){return x(this,void 0,void 0,function(){var e,t,r,i,n,a,s,o;return O(this,function(l){switch(l.label){case 0:if(e=this.timing.getRemainingAdMs(),t=Math.min(this.maxPlaceholderDurationMs,e),this.timing.isGamInCooldown())return this.debug&&console.log("[CIRCUIT-BREAKER] GAM in cooldown, skipping placeholder wait"),this.handleAdPodComplete(),[2];if(this.timing.consecutiveFailures>=this.timing.maxConsecutiveFailures)return this.debug&&console.log("[CONTINUOUS-FETCH] Skipping placeholder - too many consecutive failures"),this.handleAdPodComplete(),[2];if(t<1e3)return this.handleAdPodComplete(),[2];this.debug&&console.log("[CONTINUOUS-FETCH] Showing placeholder for ".concat(t,"ms while waiting for ad URLs")),this.isShowingPlaceholder=!0,this.host.getAdPlayer().showPlaceholder(),r=300,i=Math.floor(t/r),n=0,l.label=1;case 1:return n<i?[4,new Promise(function(e){return setTimeout(e,r)})]:[3,12];case 2:if(l.sent(),!this.inAdBreak)return[2];if(this.timing.consecutiveFailures>=this.timing.maxConsecutiveFailures)return this.debug&&console.log("[CONTINUOUS-FETCH] Too many failures during placeholder wait"),[3,12];if(!this.timing.hasTimeToStartAnotherAd())return this.debug&&console.log("[CONTINUOUS-FETCH] Not enough time remaining during placeholder wait, ending ad break"),[3,12];l.label=3;case 3:if(!(this.adRequestQueue.length>0))return[3,11];if(!this.timing.hasTimeToStartAnotherAd())return[3,11];if(!(a=this.adRequestQueue.shift()))return[3,3];if(this.timing.failedVastUrls.has(a))return[3,3];if(this.timing.isUrlInCooldown(a))return[3,3];this.debug&&console.log("[CONTINUOUS-FETCH] Ad URL available, requesting via HLS ad player"),this.isShowingPlaceholder=!1,this.host.getAdPlayer().hidePlaceholder(),l.label=4;case 4:return l.trys.push([4,6,,10]),[4,this.playSingleAd(a)];case 5:return l.sent(),this.timing.consecutiveFailures=0,[3,10];case 6:return s=l.sent(),(o=s.message).includes("ad_duration_exceeds_budget")?[4,this.tryNextAvailableAdWithRateLimit()]:[3,8];case 7:return l.sent(),[2];case 8:return o.includes("permanently failed")||o.includes("in cooldown")||this.timing.consecutiveFailures++,[4,this.tryNextAvailableAdWithRateLimit()];case 9:return l.sent(),[3,10];case 10:return[2];case 11:return n++,[3,1];case 12:return this.debug&&console.log("[CONTINUOUS-FETCH] Placeholder timeout, ending ad break"),this.isShowingPlaceholder=!1,this.host.getAdPlayer().hidePlaceholder(),this.handleAdPodComplete(),[2]}})})},e.prototype.handleAdPodComplete=function(){this.debug&&console.log("[StormcloudVideoPlayer] Ad pod complete - cleaning up"),this.timing.resetForBreakEnd(),this.stopContinuousFetching(),this.clearPendingAdBreak(),this.isShowingPlaceholder&&(this.host.getAdPlayer().hidePlaceholder(),this.isShowingPlaceholder=!1),this.adRequestQueue=[],this.inAdBreak=!1,this.adDetectSentForCurrentBreak=!1,this.cueManager.activeScte35BreakKey=void 0,this.cueManager.scheduledScte35BreakKey=void 0,this.adPodQueue=[],this.showAds=!1,this.host.getAdPlayer().stop().catch(function(){});var e=this.host.getAdPlayer().getOriginalMutedState(),t=this.host.getAdPlayer().getOriginalVolume();if(this.host.video.muted!==e&&(this.host.video.muted=e),Math.abs(this.host.video.volume-t)>.01&&(this.host.video.volume=t),this.host.video.style.visibility="visible",this.host.video.style.opacity="1",this.host.isLiveStream()){if(this.host.requiresMediaPipelineResetAfterAds())return this.debug&&console.log("[StormcloudVideoPlayer] Live break end — hard-reloading stream to reacquire decoder (single-decoder platform)"),this.host.reloadLiveStream(),void this.monitorLiveResumeStall(this.host.video.currentTime);var r=this.host.getLiveSyncPosition();return null!=r&&r>this.host.video.currentTime&&(this.debug&&console.log("[StormcloudVideoPlayer] Live break end — snapping to live edge: ".concat(this.host.video.currentTime.toFixed(2),"s → ").concat(r.toFixed(2),"s")),this.host.video.currentTime=r,this.host.restartHlsLoad(r)),this.resumeContentPlayback(),void this.monitorLiveResumeStall(this.host.video.currentTime)}this.resumeContentPlayback()},e.prototype.getBufferedAhead=function(){for(var e=this.host.video,t=e.currentTime,r=e.buffered,i=0;i<r.length;i++)if(t>=r.start(i)-.5&&t<=r.end(i))return r.end(i)-t;return 0},e.prototype.describeVideoState=function(){for(var e,t,r=this.host.video,i=null!==(e=["EMPTY","IDLE","LOADING","NO_SOURCE"][r.networkState])&&void 0!==e?e:String(r.networkState),n=null!==(t=["HAVE_NOTHING","HAVE_METADATA","HAVE_CURRENT_DATA","HAVE_FUTURE_DATA","HAVE_ENOUGH_DATA"][r.readyState])&&void 0!==t?t:String(r.readyState),a=r.error?"code=".concat(r.error.code).concat(r.error.message?" (".concat(r.error.message,")"):""):"none",s=[],o=0;o<r.buffered.length;o++)s.push("[".concat(r.buffered.start(o).toFixed(2),"–").concat(r.buffered.end(o).toFixed(2),"]"));return"t=".concat(r.currentTime.toFixed(2),"s paused=").concat(r.paused," ended=").concat(r.ended," seeking=").concat(r.seeking," ")+"readyState=".concat(n," networkState=").concat(i," error=").concat(a," ")+"buffered=".concat(s.length?s.join(","):"none")},e.prototype.monitorLiveResumeStall=function(e){var t,r,i,n=this,a=this.host.requiresMediaPipelineResetAfterAds(),s=a?8e3:5e3,o=a?7e3:5e3,l=Date.now(),u=e,c=0,d=0,h=this.host.video,f=!1,v=["loadstart","loadedmetadata","loadeddata","canplay","canplaythrough","play","playing","pause","waiting","stalled","suspend","seeking","seeked","emptied","error","ended"];if(this.debug){i=function(e){var t=((Date.now()-l)/1e3).toFixed(1);console.log("[ResumeDiag] +".concat(t,"s event=").concat(e.type," — ").concat(n.describeVideoState()))};try{for(var g=F(v),p=g.next();!p.done;p=g.next()){var m=p.value;h.addEventListener(m,i)}}catch(e){t={error:e}}finally{try{p&&!p.done&&(r=g.return)&&r.call(g)}finally{if(t)throw t.error}}f=!0,console.log("[ResumeDiag] +0.0s monitor start — ".concat(this.describeVideoState()))}var y=function(){var e,t;if(f&&i){try{for(var r=F(v),n=r.next();!n.done;n=r.next()){var a=n.value;h.removeEventListener(a,i)}}catch(t){e={error:t}}finally{try{n&&!n.done&&(t=r.return)&&t.call(r)}finally{if(e)throw e.error}}f=!1}},k=function(){var e,t;if(n.inAdBreak)y();else{var r=h.currentTime,i=r>u+.5,f=!h.paused&&h.readyState>=3;if(i&&f)return n.debug&&console.log("[StormcloudVideoPlayer] Live stream resumed successfully after ad break — ".concat(n.describeVideoState())),void y();h.paused&&(null===(e=h.play())||void 0===e||e.catch(function(){}));var v=Date.now()-l,g=n.getBufferedAhead()<.5&&!i;if(v>=45e3)return n.debug&&!i&&console.warn("[StormcloudVideoPlayer] Live stream failed to resume after ".concat(45..toFixed(0),"s — ").concat(n.describeVideoState())),void y();if(g&&v>=s&&Date.now()-d>=o&&c<3){if(c++,d=Date.now(),a)n.debug&&console.warn("[StormcloudVideoPlayer] Content still wedged after ad break — hard-reloading live stream (recovery ".concat(c,"/").concat(3,") — ").concat(n.describeVideoState())),n.host.reloadLiveStream();else if(1===c)n.debug&&console.warn("[StormcloudVideoPlayer] Content wedged after ad break — calling recoverMediaError() (recovery ".concat(c,"/").concat(3,") — ").concat(n.describeVideoState())),n.host.recoverMediaError();else if(2===c){var p=n.host.getLiveSyncPosition(),m=null!=p&&p>r?p:r;n.debug&&console.warn("[StormcloudVideoPlayer] Content wedged after ad break — restarting HLS load at ".concat(m.toFixed(2),"s (recovery ").concat(c,"/").concat(3,") — ").concat(n.describeVideoState())),null!=p&&p>r&&(h.currentTime=p),n.host.restartHlsLoad(m)}else n.debug&&console.warn("[StormcloudVideoPlayer] Content still wedged after ad break — hard-reloading live stream (recovery ".concat(c,"/").concat(3,") — ").concat(n.describeVideoState())),n.host.reloadLiveStream();u=h.currentTime,h.paused&&(null===(t=h.play())||void 0===t||t.catch(function(){}))}window.setTimeout(k,1e3)}};window.setTimeout(k,1e3)},e.prototype.resumeContentPlayback=function(e){var t,r=this;void 0===e&&(e=0);var i=this.host.video;if(i.paused)if(this.debug&&console.log("[StormcloudVideoPlayer] Resuming content playback after ads (attempt ".concat(e+1,"/").concat(5,", readyState=").concat(i.readyState,")")),i.readyState<3){if(e+1>=5)return this.debug&&console.warn("[StormcloudVideoPlayer] readyState never reached HAVE_FUTURE_DATA, forcing play()"),void(null===(t=i.play())||void 0===t||t.catch(function(){}));var n=function(){i.removeEventListener("canplay",n),r.resumeContentPlayback(e+1)};i.addEventListener("canplay",n);var a=500*(e+1);window.setTimeout(function(){i.removeEventListener("canplay",n),i.paused&&r.resumeContentPlayback(e+1)},a)}else{var s=i.play();s&&"function"==typeof s.catch&&s.catch(function(t){if(e+1>=5)r.debug&&console.warn("[StormcloudVideoPlayer] Failed to resume content playback after ads:",t);else{var i=250*(e+1);window.setTimeout(function(){r.resumeContentPlayback(e+1)},i)}})}else this.debug&&0===e&&console.log("[StormcloudVideoPlayer] Content video already playing after ads")},e.prototype.handleAdFailure=function(){this.timing.consecutiveFailures++,this.timing.recordGamNoFill();var e=this.timing.getRemainingAdMs();if(this.debug&&console.log("[CONTINUOUS-FETCH] Ad failure: remaining=".concat(e,"ms, queued ads=").concat(this.adRequestQueue.length,", consecutiveFailures=").concat(this.timing.consecutiveFailures),this.adRequestQueue.length>0?{queuedUrls:B([],N(this.adRequestQueue),!1)}:{}),this.timing.consecutiveFailures>=this.timing.maxConsecutiveFailures)return this.debug&&console.log("[CONTINUOUS-FETCH] Max consecutive failures reached (".concat(this.timing.consecutiveFailures,"), ending ad break gracefully")),void this.handleAdPodComplete();this.timing.hasTimeToStartAnotherAd()?this.tryNextAvailableAdWithRateLimit():(this.debug&&console.log("[AD-ERROR] Ad failed and not enough time remaining for another ad. Failed URLs:",this.timing.failedVastUrls.size),this.handleAdPodComplete())},e}(),bf=function(){function e(e){var t=this;this.attached=!1,this.palPlaybackStarted=!1,Bh();var r=Ed();this.config=_(_({},r),e),this.video=e.videoElement,Sd(e.debugAdTiming),this.adPlayer=this.createAdPlayer(!1),this.palNonce=Vd(),this.cueManager=new mf(!!this.config.debugAdTiming,{onEarlyStartCue:function(e,r,i){t.startAdPrefetch(e,r,i)},onPlaybackCue:function(e,r){t.onScte35Marker(e,r)},isInAdBreak:function(){return t.adBreak.inAdBreak}}),this.adConfig=new yf(this.config,this.video),this.timing=new kf(this.config,this.video,{onAdStopTimerFired:function(){return t.onAdStopTimerFired()},onAdStartTimerFired:function(e,r){t.startScte35AdBreak(e,r,null!=e.durationSeconds?1e3*e.durationSeconds:t.timing.expectedAdBreakDurationMs)},onWatchdogTimeout:function(){return t.adBreak.handleAdFailure()},onFailsafeTimeout:function(){return t.adBreak.handleAdFailure()},getAdState:function(){return{inAdBreak:t.adBreak.inAdBreak,showAds:t.adBreak.showAds,adPlaying:t.adPlayer.isAdPlaying()}}}),this.placeholder=new Ef(this.video,!!this.config.debugAdTiming),this.hlsEngine=new Sf(this.config,this.video,this.cueManager,this.timing,{onManifestParsed:function(e){return x(t,void 0,void 0,function(){return O(this,function(t){return[2,this.onManifestParsed(e)]})})},onScte35Cue:function(e,r){return t.cueManager.onScte35Cue(e,r)},activatePendingCuesForFragment:function(e){return t.cueManager.activatePendingScte35CuesForFragment(e)},onFatalDestroy:function(){return t.destroy()},isInAdBreak:function(){return t.adBreak.inAdBreak},hasPendingAdBreak:function(){return null!==t.adBreak.pendingAdBreak}}),this.adBreak=new Af({config:this.config,video:this.video,getAdPlayer:function(){return t.adPlayer},setAdPlayer:function(e){t.adPlayer=e},createAdPlayer:function(e){return t.createAdPlayer(e)},shouldContinueLiveStreamDuringAds:function(){return t.shouldContinueLiveStreamDuringAds()},isLiveStream:function(){return t.hlsEngine.isLiveStream},getLiveSyncPosition:function(){return t.hlsEngine.getLiveSyncPosition()},restartHlsLoad:function(e){return t.hlsEngine.restartLoadAt(e)},reloadLiveStream:function(){return t.hlsEngine.reloadLiveStream()},recoverMediaError:function(){return t.hlsEngine.recoverMediaError()},requiresMediaPipelineResetAfterAds:function(){return kd()},generatePodVastUrl:function(e,r){return t.generatePodVastUrl(e,r)},onAdClick:function(){return t.palNonce.sendAdClick()},onAdInteraction:function(e){return t.palNonce.sendAdTouch(e)}},this.timing,this.adConfig,this.cueManager,this.placeholder)}return Object.defineProperty(e.prototype,"debug",{get:function(){return!!this.config.debugAdTiming},enumerable:!1,configurable:!0}),e.prototype.createAdPlayer=function(e){var t;return this.debug&&console.log("[StormcloudVideoPlayer] Creating HLS ad player"),Md(this.video,_(_({continueLiveStreamDuringAds:e},this.config.licenseKey?{licenseKey:this.config.licenseKey}:{}),(null===(t=this.hlsEngine)||void 0===t?void 0:t.hls)?{mainHlsInstance:this.hlsEngine.hls}:{}))},e.prototype.generatePodVastUrl=function(e,t){var r=this.adConfig.resolvePodParams(t);return this.adConfig.generatePodVastUrl(e,r,this.adPlayer,this.palNonce,this.adBreak.inAdBreak)},e.prototype.load=function(){return x(this,void 0,void 0,function(){var e,t,r,i=this;return O(this,function(n){switch(n.label){case 0:this.attached||this.attach(),n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this.adConfig.fetchAdConfiguration()];case 2:return n.sent(),[3,4];case 3:return e=n.sent(),this.debug&&console.warn("[StormcloudVideoPlayer] Failed to fetch ad configuration:",e),[3,4];case 4:return t=this.config.ctvAdRequest?this.adConfig.getPalDescriptionUrl():void 0,function(e){void 0===e&&(e=1500);var t={};if("undefined"==typeof window)return Promise.resolve(t);var r=[],i=window.__tcfapi;"function"==typeof i&&r.push(new Promise(function(r){var n=!1;try{i("addEventListener",2,function(e,a){var s,o;if(!n&&a&&e&&("tcloaded"===e.eventStatus||"useractioncomplete"===e.eventStatus)){n=!0,t.gdpr=e.gdprApplies?"1":"0",t.storageAllowed=!e.gdprApplies||!0===(null===(o=null===(s=e.purpose)||void 0===s?void 0:s.consents)||void 0===o?void 0:o[1]),"string"==typeof e.tcString&&e.tcString&&(t.gdprConsent=e.tcString);try{i("removeEventListener",2,function(){},e.listenerId)}catch(e){}r()}})}catch(e){r()}setTimeout(function(){n||(n=!0,r())},e)}));var n=window.__uspapi;return"function"==typeof n&&r.push(new Promise(function(r){try{n("getUSPData",1,function(e,i){i&&"string"==typeof(null==e?void 0:e.uspString)&&e.uspString&&(t.usPrivacy=e.uspString),r()})}catch(e){r()}setTimeout(r,e)})),0===r.length?Promise.resolve(t):Promise.all(r).then(function(){return t})}().catch(function(){return{}}).then(function(e){var r;i.adConfig.consentSignals=e;var n=i.video.muted;return i.palNonce.generateNonce(_(_({videoWidth:i.video.offsetWidth||i.video.clientWidth||640,videoHeight:i.video.offsetHeight||i.video.clientHeight||480,adWillAutoPlay:!!i.config.autoplay,adWillPlayMuted:n,playerVolume:n?0:i.video.volume,continuousPlayback:null!==(r=i.config.lowLatencyMode)&&void 0!==r&&r},t?{descriptionUrl:t}:{}),null!=e.storageAllowed?{allowStorage:e.storageAllowed}:{}))}).catch(function(){}),this.adConfig.initializeTracking(),this.hlsEngine.shouldUseNativeHls(function(){return i.getStreamType()})?[4,this.hlsEngine.setupNativeHls()]:[3,6];case 5:return n.sent(),r=this.shouldContinueLiveStreamDuringAds(),this.debug&&console.log("[StormcloudVideoPlayer] Native HLS ad behavior:",{isLive:this.hlsEngine.isLiveStream,continueLiveStreamDuringAds:r}),this.adPlayer.destroy(),this.adPlayer=this.createAdPlayer(r),this.adPlayer.initialize(),[2];case 6:return this.hlsEngine.setupHls(),[2]}})})},e.prototype.onManifestParsed=function(e){return x(this,void 0,void 0,function(){var t,r;return O(this,function(i){return this.hlsEngine.reloadingLiveStream?(this.debug&&console.log("[StormcloudVideoPlayer] Manifest re-parsed after hard reload — skipping ad-player setup"),[2]):(this.adConfig.isVmapEnabled()||e||0!==this.adConfig.vmapBreaks.length||!this.adConfig.apiVastTagUrl||(t="synthetic-vod-preroll",this.adConfig.consumedVmapBreakIds.has(t)||(this.adConfig.vmapBreaks=[{id:t,startTimeMs:0,vastTagUrl:this.adConfig.apiVastTagUrl}],this.debug&&console.log("[StormcloudVideoPlayer] Injected synthetic VOD preroll from apiVastTagUrl"))),this.debug&&(r=this.shouldContinueLiveStreamDuringAds()?"live (main video continues muted during ads)":"vod (main video pauses during ads)",console.log("[StormcloudVideoPlayer] Stream type detected:",{isLive:e,allowNativeHls:this.config.allowNativeHls,adBehavior:r})),this.adPlayer.destroy(),this.adPlayer=this.createAdPlayer(this.shouldContinueLiveStreamDuringAds()),this.adPlayer.initialize(),[2])})})},e.prototype.attach=function(){var e=this;this.attached||(this.attached=!0,this.video.autoplay=!!this.config.autoplay,this.video.muted=!!this.config.muted,this.adPlayer.initialize(),this.adPlayer.updateOriginalMutedState(this.video.muted,this.video.volume),this.adBreak.attachImaEventListeners(),this.video.addEventListener("play",function(){e.palPlaybackStarted||e.adPlayer.isAdPlaying()||(e.palPlaybackStarted=!0,e.palNonce.sendPlaybackStart())}),this.endedHandler=function(){e.palPlaybackStarted&&(e.palPlaybackStarted=!1,e.palNonce.sendPlaybackEnd()),e.onVideoEnded()},this.video.addEventListener("ended",this.endedHandler),this.video.addEventListener("mousedown",function(t){e.palNonce.sendAdTouch(t)}),this.video.addEventListener("touchstart",function(t){e.palNonce.sendAdTouch(t)}),this.timeUpdateHandler=function(){e.onTimeUpdate(e.video.currentTime)},this.video.addEventListener("timeupdate",this.timeUpdateHandler),this.emptiedHandler=function(){if(e.hlsEngine.nativeHlsMode&&e.hlsEngine.videoSrcProtection&&!e.adPlayer.isAdPlaying()){e.debug&&console.log("[StormcloudVideoPlayer] Video src was cleared, restoring:",e.hlsEngine.videoSrcProtection);var t=e.video.currentTime,r=e.video.paused;e.video.src=e.hlsEngine.videoSrcProtection,e.video.currentTime=t,r||e.video.play().catch(function(){})}},this.video.addEventListener("emptied",this.emptiedHandler))},e.prototype.shouldContinueLiveStreamDuringAds=function(){if(this.config.pauseContentDuringAds)return!1;if(this.hlsEngine.isLiveStream)return!0;var e=this.video.duration;return!Number.isFinite(e)||e===1/0},e.prototype.onScte35Marker=function(e,t){var r,i,n;if(this.debug&&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.adBreak.pendingAdBreak}),"start"!==e.type){if("progress"===e.type&&this.adBreak.inAdBreak)return null!=e.durationSeconds&&this.timing.setAdBreakDurationBoundary(1e3*e.durationSeconds),this.timing.scheduleAdStopAtBreakBoundary(),void(!this.adPlayer.isAdPlaying()&&null===this.timing.activeAdRequestToken&&this.adBreak.adRequestQueue.length>0&&this.timing.hasTimeToStartAnotherAd()&&this.adBreak.tryNextAvailableAdWithRateLimit());if("end"===e.type){this.video.muted||(this.video.muted=!0,this.debug&&console.log("[StormcloudVideoPlayer] Muted video on SCTE end marker"));var a=this.timing.getRemainingAdMs(),s=this.adPlayer.isAdPlaying(),o=this.adBreak.adRequestQueue.length>0;return this.debug&&console.log("[StormcloudVideoPlayer] SCTE-35 end marker received:",{remaining:a,adPlaying:s,hasQueuedAds:o,activeAdRequest:null!==this.timing.activeAdRequestToken}),this.timing.scteAdBreakEndWallClockMs=Date.now(),this.timing.clearAdStartTimer(),this.timing.clearAdStopTimer(),s&&this.adPlayer.stop().catch(function(){}),void this.adBreak.handleAdPodComplete()}}else{if(this.adBreak.inAdBreak){if(null!=e.durationSeconds){var l=1e3*e.durationSeconds;(null==this.timing.expectedAdBreakDurationMs||l>this.timing.expectedAdBreakDurationMs)&&(this.timing.setAdBreakDurationBoundary(l),this.timing.scheduleAdStopAtBreakBoundary(),this.debug&&console.log("[StormcloudVideoPlayer] Updated ad break duration from subsequent marker: ".concat(l,"ms, remaining: ").concat(this.timing.getWallClockRemainingAdMs(),"ms")))}return}if(!this.adBreak.adDetectSentForCurrentBreak){this.adBreak.adDetectSentForCurrentBreak=!0;var u={};null!=e.durationSeconds&&(u.durationSeconds=e.durationSeconds),null!=e.ptsSeconds&&(u.ptsSeconds=e.ptsSeconds),xh(this.config.licenseKey,_({source:"scte35",timestamp:(new Date).toISOString()},u),Rh(this.config)).catch(function(){})}var c=this.adBreak.pendingAdBreak&&this.adBreak.pendingAdBreak.vastUrls.length>0,d=null!=e.durationSeconds?1e3*e.durationSeconds:null!=(null===(r=this.adBreak.pendingAdBreak)||void 0===r?void 0:r.marker.durationSeconds)?1e3*this.adBreak.pendingAdBreak.marker.durationSeconds:void 0,h=function(e){var t=e.raw;if(!t)return!1;if(t.tag){var r=String(t.tag);return r.includes("EXT-X-CUE-OUT")||r.includes("EXT-X-CUE-IN")||r.includes("EXT-X-DATERANGE")}return t.id3||t.splice_command_type,!1}(e),f=null===(i=this.config.immediateManifestAds)||void 0===i||i;if(this.debug&&console.log("[StormcloudVideoPlayer] Ad start decision:",{isManifestMarker:h,forceImmediate:f,hasPts:"number"==typeof e.ptsSeconds,hasPrefetchedAds:c}),h&&f)this.debug&&console.log("[StormcloudVideoPlayer] Starting ad immediately (manifest-based)".concat(c?" with prefetched ads":"")),this.timing.clearAdStartTimer(),this.startScte35AdBreak(e,t,d);else if("number"==typeof e.ptsSeconds){var v=null!==(n=this.config.driftToleranceMs)&&void 0!==n?n:1e3,g=1e3*this.video.currentTime,p=g-this.timing.ptsDriftEmaMs,m=Math.floor(1e3*e.ptsSeconds-p);this.debug&&console.log("[StormcloudVideoPlayer] PTS-based timing calculation:",{nowMs:g,estCurrentPtsMs:p,markerPtsMs:1e3*e.ptsSeconds,deltaMs:m,tolerance:v}),m>v?(this.debug&&console.log("[StormcloudVideoPlayer] Scheduling ad start in ".concat(m,"ms")),this.timing.expectedAdBreakDurationMs=d,this.cueManager.scheduledScte35BreakKey=t,this.timing.scheduleAdStartIn(m,e,t)):(this.debug&&console.log("[StormcloudVideoPlayer] Starting ad immediately (within tolerance)"),this.timing.clearAdStartTimer(),this.startScte35AdBreak(e,t,d))}else this.debug&&console.log("[StormcloudVideoPlayer] Starting ad immediately (fallback)"),this.timing.clearAdStartTimer(),this.startScte35AdBreak(e,t,d)}},e.prototype.startScte35AdBreak=function(e,t,r){this.adBreak.inAdBreak=!0,this.cueManager.activeScte35BreakKey=null!=t?t:this.cueManager.pendingScte35CueKey,this.cueManager.scheduledScte35BreakKey=void 0,this.timing.currentAdBreakStartWallClockMs=this.timing.resolveScteBreakStartWallClockMs(e),this.timing.setAdBreakDurationBoundary(r),this.adBreak.handleAdStart(e),this.timing.scheduleAdStopAtBreakBoundary()},e.prototype.onAdStopTimerFired=function(){var e,t;if(this.adBreak.inAdBreak){var r=this.adPlayer.isAdPlaying(),i=Math.max(250,Math.floor(null!==(e=this.config.adBreakCheckIntervalMs)&&void 0!==e?e:1e3)),n=this.config.maxAdBreakExtensionMs,a="number"==typeof n&&n>0?n:0,s=null!==(t=this.timing.getAdBreakEndWallClockMs())&&void 0!==t?t:Date.now(),o=Math.max(0,Date.now()-s);r&&o<a?this.timing.scheduleAdStopCountdown(i):(this.debug&&console.log("[StormcloudVideoPlayer] Ad break boundary reached (overrun=".concat(o,"ms) - hard-stopping ads and resuming stream")),r&&this.adPlayer.stop().catch(function(){}),this.adBreak.handleAdPodComplete())}},e.prototype.startAdPrefetch=function(e,t,r){if(!this.adBreak.pendingAdBreak&&!this.adBreak.inAdBreak){var i,n=this.adConfig.findCurrentOrNextBreak(1e3*this.video.currentTime),a=this.adConfig.selectVastTagsForBreak(n);if(a&&a.length>0&&a[0])i=a[0];else{if(!this.adConfig.apiVastTagUrl)return void(this.debug&&console.warn("[StormcloudVideoPlayer] No VAST URL available for prefetch"));i=this.adConfig.apiVastTagUrl}this.adConfig.beginNewAdPod(),this.adConfig.podAssignedByPrefetch=!0;var s=null!=e.durationSeconds?1e3*e.durationSeconds:void 0,o=[this.generatePodVastUrl(i,s)];this.adBreak.pendingAdBreak=_(_({marker:e},void 0!==t?{detectedAtFragmentSn:t}:{}),{vastUrls:o,isFetching:!1,fetchStartTime:Date.now()}),this.cueManager.pendingScte35CueKey=r,this.adBreak.adDetectSentForCurrentBreak=!0;var l={};null!=e.durationSeconds&&(l.durationSeconds=e.durationSeconds),null!=e.ptsSeconds&&(l.ptsSeconds=e.ptsSeconds),void 0!==t&&(l.detectedAtFragmentSn=t),xh(this.config.licenseKey,_({source:"scte35",timestamp:(new Date).toISOString()},l),Rh(this.config)).catch(function(){}),this.debug&&(console.log("[PREFETCH] Starting ad prefetch for upcoming ad break"),console.log("[PREFETCH] Pre-generated pod request URL"))}},e.prototype.onTimeUpdate=function(e){var t=this;if(this.adConfig.isVmapEnabled()&&0!==this.adConfig.vmapBreaks.length&&!this.adPlayer.isAdPlaying()&&!this.adBreak.inAdBreak){var r=1e3*e,i=this.adConfig.findBreakForTime(r);i&&this.handleVmapAdBreak(i,r).catch(function(e){t.debug&&console.warn("[StormcloudVideoPlayer] VMAP ad break failed gracefully:",e)})}},e.prototype.onVideoEnded=function(){var e=this;if(this.adConfig.isVmapEnabled()&&0!==this.adConfig.vmapBreaks.length&&!this.adPlayer.isAdPlaying()&&!this.adBreak.inAdBreak){var t=Number.isFinite(this.video.duration)?Math.floor(1e3*this.video.duration):0,r=this.adConfig.vmapBreaks.find(function(t){return-1===t.startTimeMs&&!e.adConfig.consumedVmapBreakIds.has(e.adConfig.getAdBreakKey(t))});r&&this.handleVmapAdBreak(r,t).catch(function(t){e.debug&&console.warn("[StormcloudVideoPlayer] VMAP post-roll failed gracefully:",t)})}},e.prototype.handleVmapAdBreak=function(e,t){return x(this,void 0,void 0,function(){var r,i,n,a,s,o,l,u,c;return O(this,function(d){switch(d.label){case 0:if(r=this.adConfig.getAdBreakKey(e),this.adConfig.consumedVmapBreakIds.has(r))return[2];if(null==(i=this.adConfig.resolveBreakStartMs(e)))return[2];if(n=null!==(c=e.durationMs)&&void 0!==c?c:0,a=i+n,!(n>0?t>=i&&t<a:t>=i))return[3,4];if(this.adConfig.consumedVmapBreakIds.add(r),!(s=this.adConfig.selectVastTagsForBreak(e))||0===s.length)return[2];o=s[0],l=s.slice(1),this.adBreak.adPodQueue=l,this.adPlayer.updateOriginalMutedState(this.video.muted,this.video.volume),this.adBreak.showAds=!0,this.adBreak.inAdBreak=!0,this.timing.currentAdBreakStartWallClockMs=Date.now(),d.label=1;case 1:return d.trys.push([1,3,,4]),[4,this.adBreak.playSingleAd(o)];case 2:return d.sent(),[3,4];case 3:return u=d.sent(),this.debug&&console.warn("[StormcloudVideoPlayer] VMAP ad request failed:",u),this.adBreak.handleAdPodComplete(),[3,4];case 4:return[2]}})})},e.prototype.getCurrentAdIndex=function(){return this.timing.currentAdIndex},e.prototype.getTotalAdsInBreak=function(){return this.timing.totalAdsInBreak},e.prototype.getAdRemainingMs=function(){return this.timing.getRemainingAdMs()},e.prototype.isAdPlaying=function(){return this.adBreak.inAdBreak&&this.adPlayer.isAdPlaying()},e.prototype.isShowingAds=function(){return this.adBreak.showAds},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.isLive=function(){return this.hlsEngine.isLiveStream},e.prototype.isLowLatencyStream=function(){return this.hlsEngine.isLowLatencyStream()},Object.defineProperty(e.prototype,"videoElement",{get:function(){return this.video},enumerable:!1,configurable:!0}),e.prototype.toggleMute=function(){!function(e,t,r){if(t.isAdPlaying()){var i=!t.getOriginalMutedState(),n=t.getOriginalVolume()||1;t.updateOriginalMutedState(i,e.volume),t.setAdVolume(i?0:n),r&&console.log("[StormcloudVideoPlayer] Mute toggle during ad - immediately applied:",i)}else e.muted=!e.muted,t.updateOriginalMutedState(e.muted,e.volume),r&&console.log("[StormcloudVideoPlayer] Muted:",e.muted)}(this.video,this.adPlayer,this.debug)},e.prototype.toggleFullscreen=function(){return e=this.video,t=this.debug,new Promise(function(r,i){if(document.fullscreenElement)document.exitFullscreen().then(function(){t&&console.log("[StormcloudVideoPlayer] Exited fullscreen"),r()}).catch(function(e){t&&console.error("[StormcloudVideoPlayer] Exit fullscreen error:",e),i(e)});else{var n=e.parentElement;if(!n)return void i(new Error("No parent container found for fullscreen"));n.requestFullscreen().then(function(){t&&console.log("[StormcloudVideoPlayer] Entered fullscreen"),r()}).catch(function(e){t&&console.error("[StormcloudVideoPlayer] Fullscreen error:",e),i(e)})}});var e,t},e.prototype.isMuted=function(){return e=this.video,(t=this.adPlayer).isAdPlaying()?t.getOriginalMutedState():e.muted;var e,t},e.prototype.setMuted=function(e){!function(e,t,r,i){var n=t.isAdPlaying();if(n&&r===e.muted)i&&console.log("[StormcloudVideoPlayer] setMuted reflective update during ad ignored",{muted:r});else{if(e.muted=r,n)return t.updateOriginalMutedState(r,e.volume),t.setAdVolume(r?0:1),void(i&&console.log("[StormcloudVideoPlayer] setMuted applied during ad",{muted:r}));t.updateOriginalMutedState(r,e.volume),i&&console.log("[StormcloudVideoPlayer] setMuted called:",r)}}(this.video,this.adPlayer,e,this.debug)},e.prototype.setVolume=function(e){!function(e,t,r,i){var n=Math.max(0,Math.min(1,r));t.isAdPlaying()?(t.setAdVolume(n),t.updateOriginalMutedState(0===n,n),i&&console.log("[StormcloudVideoPlayer] setVolume applied during ad",{volume:n})):(e.volume=n,e.muted=0===n,t.updateOriginalMutedState(0===n,n),i&&console.log("[StormcloudVideoPlayer] setVolume called:",n))}(this.video,this.adPlayer,e,this.debug)},e.prototype.getVolume=function(){return e=this.video,(t=this.adPlayer).isAdPlaying()?t.getAdVolume():e.volume;var e,t},e.prototype.isFullscreen=function(){return!!document.fullscreenElement},e.prototype.resize=function(){!function(e,t,r){if(r&&console.log("[StormcloudVideoPlayer] Resizing player"),t&&t.isAdPlaying()){var i=e.clientWidth||640,n=e.clientHeight||480;r&&console.log("[StormcloudVideoPlayer] Resizing ads manager to ".concat(i,"x").concat(n)),t.resize(i,n)}}(this.video,this.adPlayer,this.debug)},e.prototype.destroy=function(){var e;this.adBreak.stopContinuousFetching(),this.timing.destroy(),this.adBreak.clearPendingAdBreak(),this.placeholder.destroy(),this.timeUpdateHandler&&(this.video.removeEventListener("timeupdate",this.timeUpdateHandler),delete this.timeUpdateHandler),this.endedHandler&&(this.video.removeEventListener("ended",this.endedHandler),delete this.endedHandler),this.emptiedHandler&&(this.video.removeEventListener("emptied",this.emptiedHandler),delete this.emptiedHandler),this.adConfig.destroyTracking(),this.hlsEngine.destroy(),null===(e=this.adPlayer)||void 0===e||e.destroy(),this.palPlaybackStarted&&(this.palPlaybackStarted=!1,this.palNonce.sendPlaybackEnd()),this.palNonce.reset(),this.adBreak.adRequestQueue=[],this.timing.consecutiveFailures=0},e}(),If={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},Rf=J.createContext&&J.createContext(If),Lf=["attr","size","title"];function Pf(){return Pf=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var i in r)({}).hasOwnProperty.call(r,i)&&(e[i]=r[i])}return e},Pf.apply(null,arguments)}function wf(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,i)}return r}function Cf(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?wf(Object(r),!0).forEach(function(t){Df(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):wf(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function Df(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=R(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var i=r.call(e,t||"default");if("object"!=R(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==R(t)?t:t+""}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function _f(e){return e&&e.map(function(e,t){return J.createElement(e.tag,Cf({key:t},e.attr),_f(e.child))})}function Mf(e){return function(t){return J.createElement(xf,Pf({attr:Cf({},e.attr)},t),_f(e.child))}}function xf(e){var t=function(t){var r,i=e.attr,n=e.size,a=e.title,s=function(e,t){if(null==e)return{};var r,i,n=function(e,t){if(null==e)return{};var r={};for(var i in e)if({}.hasOwnProperty.call(e,i)){if(-1!==t.indexOf(i))continue;r[i]=e[i]}return r}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)r=a[i],-1===t.indexOf(r)&&{}.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}(e,Lf),o=n||t.size||"1em";return t.className&&(r=t.className),e.className&&(r=(r?r+" ":"")+e.className),J.createElement("svg",Pf({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},t.attr,i,s,{className:r,style:Cf(Cf({color:e.color||t.color},t.style),e.style),height:o,width:o,xmlns:"http://www.w3.org/2000/svg"}),a&&J.createElement("title",null,a),e.children)};return void 0!==Rf?J.createElement(Rf.Consumer,null,function(e){return t(e)}):t(If)}function Of(e){return Mf({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)}function Ff(e){return Mf({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 Nf(e){return Mf({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 Bf(e){return Mf({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 Uf(e){return Mf({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)}var Vf=function(e){var t=e.size,r=void 0===t?18:t;return Q.jsxs("svg",{width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",children:[Q.jsx("path",{d:"M9 4H4v5"}),Q.jsx("path",{d:"M20 9V4h-5"}),Q.jsx("path",{d:"M15 20h5v-5"}),Q.jsx("path",{d:"M4 15v5h5"})]})},Gf=function(e){var t=e.size,r=void 0===t?18:t;return Q.jsxs("svg",{width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",children:[Q.jsx("path",{d:"M4 9h5V4"}),Q.jsx("path",{d:"M15 4v5h5"}),Q.jsx("path",{d:"M20 15h-5v5"}),Q.jsx("path",{d:"M9 20v-5H4"})]})},Hf=["src","allowNativeHls","isLiveStream","licenseKey","isVmap","vmapUrl","lowLatencyMode","driftToleranceMs","vastMode","ctvAdRequest"],Kf=16/9,jf=J.memo(function(e){var t=e.src,r=e.autoplay,i=e.muted,n=e.lowLatencyMode,a=e.allowNativeHls,s=e.isLiveStream,o=e.driftToleranceMs,l=e.immediateManifestAds,u=e.debugAdTiming,c=e.showCustomControls,d=e.hideLoadingIndicator,h=e.onVolumeToggle,f=e.onFullscreenToggle,v=e.onControlClick,g=e.onReady,p=e.wrapperClassName,m=e.wrapperStyle,y=e.className,k=e.style,E=e.controls,S=e.playsInline,T=e.preload,A=e.poster,b=e.children,I=e.licenseKey,R=e.vastMode,L=e.vastTagUrl,P=e.isVmap,w=e.vmapUrl,C=e.minSegmentsBeforePlay,D=e.ctvAdRequest,x=e.programTitle,O=e.channelName,F=M(e,["src","autoplay","muted","lowLatencyMode","allowNativeHls","isLiveStream","driftToleranceMs","immediateManifestAds","debugAdTiming","showCustomControls","hideLoadingIndicator","onVolumeToggle","onFullscreenToggle","onControlClick","onReady","wrapperClassName","wrapperStyle","className","style","controls","playsInline","preload","poster","children","licenseKey","vastMode","vastTagUrl","isVmap","vmapUrl","minSegmentsBeforePlay","ctvAdRequest","programTitle","channelName"]),B=$.useRef(null),U=$.useRef(null),V=$.useRef(null),G=$.useRef(null),H=$.useRef(null),K=N(J.useState({showAds:!1,currentIndex:0,totalAds:0,remainingSeconds:0}),2),j=K[0],q=K[1],W=N(J.useState(!0),2),Y=W[0],z=W[1],X=N(J.useState(!1),2),Z=X[0],ee=X[1],te=N(J.useState(!1),2),re=te[0],ie=te[1],ne=N(J.useState(!1),2),ae=ne[0],se=ne[1],oe=N(J.useState(0),2),le=oe[0],ue=oe[1],ce=N(J.useState(0),2),de=ce[0],he=ce[1],fe=N(J.useState(1),2),ve=fe[0],ge=fe[1],pe=N(J.useState(1),2),me=pe[0],ye=pe[1],ke=N(J.useState(!1),2),Ee=ke[0],Se=ke[1],Te=N(J.useState(!1),2),Ae=Te[0],be=Te[1],Ie=N(J.useState(!0),2),Re=Ie[0],Le=Ie[1],Pe=N(J.useState(!1),2),we=Pe[0],Ce=Pe[1],De=N(J.useState(!1),2),_e=De[0],Me=De[1],xe=N(J.useState(!1),2),Oe=xe[0],Fe=xe[1],Ne=N(J.useState(!0),2),Be=Ne[0],Ue=Ne[1],Ve=N(J.useState("undefined"!=typeof window?window.innerWidth:1920),2),Ge=Ve[0],He=Ve[1],Ke=N(J.useState("undefined"!=typeof window&&window.innerHeight>window.innerWidth),2),je=Ke[0],qe=Ke[1],We=N(J.useState(Kf),2),Ye=We[0],ze=We[1],Xe=Ge<480?.7:Ge<768?.8:Ge<1024?.9:1,Qe=$.useCallback(function(){G.current&&clearTimeout(G.current),Ue(!0),G.current=window.setTimeout(function(){Ee||Ae||Ue(!1)},3e3)},[Ee,Ae]),$e=$.useCallback(function(){Qe()},[Qe]),Je=$.useCallback(function(){Ee||Ae||Ue(!1)},[Ee,Ae]),Ze=function(e){if(!isFinite(e))return"0:00:00";var t=Math.floor(e/3600),r=Math.floor(e%3600/60),i=Math.floor(e%60);return"".concat(t,":").concat(r.toString().padStart(2,"0"),":").concat(i.toString().padStart(2,"0"))},et=function(e){if(U.current&&isFinite(e)){var t=Math.max(0,Math.min(1,e));U.current.setVolume(t)}},tt=(null==t?void 0:t.toLowerCase().includes(".m3u8"))||(null==t?void 0:t.toLowerCase().includes("/hls/")),rt=c&&(!tt||!(!0===s)),it=$.useMemo(function(){return Hf.map(function(t){return"".concat(t,":").concat(e[t])}).join("|")},[t,a,s,I,P,w,n,o,R]);$.useEffect(function(){if("undefined"!=typeof window){var e=B.current;if(e&&t){if(!I)return Fe(!0),Le(!1),void console.warn("StormcloudVideoPlayer: License key is required but not provided. Please set the licenseKey prop to use the player.");if(Fe(!1),u&&console.log("[StormcloudUI] Initializing player, isLoading=true"),U.current){try{U.current.destroy()}catch(e){}U.current=null}var d={src:t,videoElement:e};void 0!==r&&(d.autoplay=r),void 0!==i&&(d.muted=i),void 0!==n&&(d.lowLatencyMode=n),void 0!==a&&(d.allowNativeHls=a),void 0!==s&&(d.isLiveStream=s),void 0!==o&&(d.driftToleranceMs=o),void 0!==l&&(d.immediateManifestAds=l),void 0!==u&&(d.debugAdTiming=u),void 0!==c&&(d.showCustomControls=c),void 0!==h&&(d.onVolumeToggle=h),void 0!==f&&(d.onFullscreenToggle=f),void 0!==v&&(d.onControlClick=v),void 0!==I&&(d.licenseKey=I),void 0!==R&&(d.vastMode=R),void 0!==L&&(d.vastTagUrl=L),void 0!==P&&(d.isVmap=P),void 0!==w&&(d.vmapUrl=w),void 0!==C&&(d.minSegmentsBeforePlay=C),void 0!==D&&(d.ctvAdRequest=D),void 0!==x&&(d.programTitle=x),void 0!==O&&(d.channelName=O);var p=new bf(d);return U.current=p,p.load().then(function(){var e=p.shouldShowNativeControls();z(e),u&&console.log("[StormcloudUI] Player loaded successfully, waiting for video ready"),null==g||g(p)}).catch(function(e){console.error("StormcloudVideoPlayer: Failed to load player:",e),Le(!1),null==g||g(p)}),function(){try{p.destroy()}catch(e){}U.current=null}}}},[it]),$.useEffect(function(){if(U.current)try{void 0!==r&&U.current.videoElement&&(U.current.videoElement.autoplay=r),void 0===i||U.current.isShowingAds()||U.current.setMuted(i)}catch(e){console.warn("Failed to update player properties:",e)}},[r,i]),$.useEffect(function(){if(U.current){var e=setInterval(function(){var e,t;if(U.current){var r=U.current.isShowingAds(),i="true"===(null===(t=null===(e=B.current)||void 0===e?void 0:e.dataset)||void 0===t?void 0:t.stormcloudAdPlaying),n=r||i,a=U.current.getCurrentAdIndex(),s=U.current.getTotalAdsInBreak(),o=U.current.getAdRemainingMs(),l=n?Math.max(0,Math.ceil(o/1e3)):0;q(function(e){return e.showAds!==n||e.currentIndex!==a||e.totalAds!==s||e.remainingSeconds!==l?(n&&!e.showAds&&Me(!1),{showAds:n,currentIndex:a,totalAds:s,remainingSeconds:l}):e})}},50);return function(){return clearInterval(e)}}},[]),$.useEffect(function(){if("undefined"!=typeof window&&U.current){var e=function(){U.current&&B.current&&"function"==typeof U.current.resize&&U.current.resize(),He(window.innerWidth),qe(window.innerHeight>window.innerWidth)};return window.addEventListener("resize",e),function(){return window.removeEventListener("resize",e)}}},[]),$.useEffect(function(){if(U.current&&B.current){var e=setInterval(function(){if(U.current&&B.current){ee(U.current.isMuted()),se(!B.current.paused);var e=B.current.currentTime;ue(isFinite(e)?e:0);var t=B.current.duration;he(isFinite(t)?t:0);var r=U.current.getVolume();ge(isFinite(r)?Math.max(0,Math.min(1,r)):1);var i=B.current.playbackRate;ye(isFinite(i)&&i>0?i:1)}ie(document.fullscreenElement===H.current)},200),t=function(){ie(document.fullscreenElement===H.current)};return document.addEventListener("fullscreenchange",t),function(){clearInterval(e),document.removeEventListener("fullscreenchange",t)}}},[]),$.useEffect(function(){if(B.current){var e=function(){var e,t=B.current;t&&(t.videoWidth>0&&t.videoHeight>0&&ze(t.videoWidth/t.videoHeight),t.offsetHeight),u&&console.log("[StormcloudUI] Video event: loadedmetadata, readyState:",null===(e=B.current)||void 0===e?void 0:e.readyState)},t=function(){var e;u&&console.log("[StormcloudUI] Video event: loadeddata, readyState:",null===(e=B.current)||void 0===e?void 0:e.readyState)},r=function(){var e;u&&console.log("[StormcloudUI] Video event: loadstart, readyState:",null===(e=B.current)||void 0===e?void 0:e.readyState)},i=function(){var e;Le(!1),V.current&&(clearTimeout(V.current),V.current=null),Ce(!1),u&&console.log("[StormcloudUI] Video event: canplay, readyState:",null===(e=B.current)||void 0===e?void 0:e.readyState,"- clearing loading state, isLoading=false")},n=function(){var e;Le(!1),V.current&&(clearTimeout(V.current),V.current=null),Ce(!1),u&&console.log("[StormcloudUI] Video event: canplaythrough, readyState:",null===(e=B.current)||void 0===e?void 0:e.readyState,"- clearing loading state, isLoading=false")},a=function(){var e;V.current&&clearTimeout(V.current),V.current=window.setTimeout(function(){var e;Ce(!0),u&&console.log("[StormcloudUI] Video buffering detected (after 300ms delay), readyState:",null===(e=B.current)||void 0===e?void 0:e.readyState,"- showing spinner, isBuffering=true")},300),u&&console.log("[StormcloudUI] Video event: waiting, readyState:",null===(e=B.current)||void 0===e?void 0:e.readyState,"- buffering delay started (300ms)")},s=function(){var e;Le(!1),V.current&&(clearTimeout(V.current),V.current=null),Ce(!1),Me(!1),u&&console.log("[StormcloudUI] Video event: playing, readyState:",null===(e=B.current)||void 0===e?void 0:e.readyState,"- playback started, isLoading=false, isBuffering=false")},o=function(){var e,t,r,i=(null===(e=U.current)||void 0===e?void 0:e.isShowingAds())||"true"===(null===(r=null===(t=B.current)||void 0===t?void 0:t.dataset)||void 0===r?void 0:r.stormcloudAdPlaying);U.current&&!i?Me(!0):Me(!1)},l=function(){Me(!0)},c=B.current;return c.addEventListener("loadstart",r),c.addEventListener("loadedmetadata",e),c.addEventListener("loadeddata",t),c.addEventListener("canplay",i),c.addEventListener("canplaythrough",n),c.addEventListener("waiting",a),c.addEventListener("playing",s),c.addEventListener("pause",o),c.addEventListener("ended",l),c.paused&&Me(!0),function(){V.current&&(clearTimeout(V.current),V.current=null),c.removeEventListener("loadstart",r),c.removeEventListener("loadedmetadata",e),c.removeEventListener("loadeddata",t),c.removeEventListener("canplay",i),c.removeEventListener("canplaythrough",n),c.removeEventListener("waiting",a),c.removeEventListener("playing",s),c.removeEventListener("pause",o),c.removeEventListener("ended",l)}}},[u]),$.useEffect(function(){ze(Kf)},[t]),$.useEffect(function(){return function(){G.current&&clearTimeout(G.current)}},[]);var nt=de>0?le/de*100:0,at=Z||0===ve?Ff:ve<.5?Nf:Of;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-loading-glow {\n 0%, 100% { opacity: 0.85; transform: scale(1); }\n 50% { opacity: 1; transform: scale(1.05); }\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:H,className:"sc-wrapper ".concat(p||""),onMouseMove:$e,onMouseLeave:Je,style:_({display:"flex",alignItems:"center",justifyContent:"center",position:re?"fixed":"relative",top:re?0:void 0,left:re?0:void 0,overflow:"hidden",width:re?"100vw":"100%",height:re?"100vh":"auto",minHeight:re?"100vh":"auto",aspectRatio:re?void 0:Ye,maxWidth:re?"100vw":"100%",maxHeight:re?"100vh":"none",zIndex:re?999999:void 0,backgroundColor:"#000",borderRadius:re?0:void 0,boxShadow:re?"none":void 0},m),children:[Q.jsx("video",_({ref:B,className:y,style:_({display:"block",width:"100%",height:"100%",maxWidth:"100%",maxHeight:re?"100%":"none",objectFit:re?"cover":"contain",backgroundColor:"#000",aspectRatio:re?"unset":void 0},k),controls:Y&&E&&!c,playsInline:S,preload:T,poster:A},F,{children:b})),(Re||we)&&!d&&Q.jsxs("div",{className:"sc-loading-indicator",style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",zIndex:20,width:"".concat(Math.max(34,38*Xe),"px"),height:"".concat(Math.max(34,38*Xe),"px"),display:"flex",alignItems:"center",justifyContent:"center",animation:"sc-loading-glow 1.4s ease-in-out infinite",filter:"drop-shadow(0 6px 14px rgba(0, 0, 0, 0.55))"},children:[Q.jsx("div",{style:{position:"absolute",inset:0,borderRadius:"50%",border:"3px solid rgba(255, 255, 255, 0.25)",borderTopColor:"#ff0000",borderRightColor:"rgba(255, 255, 255, 0.85)",animation:"sc-spin 0.8s linear infinite"}}),Q.jsx("div",{style:{width:"7px",height:"7px",borderRadius:"50%",background:"#ff0000",boxShadow:"0 0 10px rgba(255, 0, 0, 0.65)"}})]}),Oe&&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."]})]}),j.showAds&&Q.jsx("div",{style:{position:"absolute",top:"".concat(12*Xe,"px"),left:"".concat(12*Xe,"px"),zIndex:50,display:"flex",alignItems:"center",gap:"8px",pointerEvents:"none",animation:"sc-fade-in 0.3s ease"},children:Q.jsx("div",{style:{background:"rgba(234, 179, 8, 0.95)",color:"#111",padding:"".concat(4*Xe,"px ").concat(12*Xe,"px"),borderRadius:"6px",fontSize:"".concat(11*Xe,"px"),fontWeight:700,letterSpacing:"0.08em",textTransform:"uppercase",boxShadow:"0 2px 12px rgba(234, 179, 8, 0.35)"},children:"Ad ".concat(Math.max(1,j.currentIndex))})}),_e&&!Re&&!we&&!Oe&&!j.showAds&&Q.jsx("div",{onClick:function(){var e;B.current&&B.current.paused&&(B.current.src||B.current.currentSrc&&""!==B.current.currentSrc||B.current.readyState>=1?(null===(e=B.current.play())||void 0===e||e.catch(function(e){console.error("[StormcloudVideoPlayer] Failed to play:",e)}),Me(!1)):console.warn("[StormcloudVideoPlayer] Cannot play: video has no valid source"))},style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",zIndex:15,cursor:"pointer",background:"rgba(0, 0, 0, 0.55)",backdropFilter:"blur(8px)",borderRadius:"50%",width:"".concat(92*Xe,"px"),height:"".concat(92*Xe,"px"),display:"flex",alignItems:"center",justifyContent:"center",transition:"background 0.2s ease, transform 0.2s ease",animation:"sc-fade-in 0.2s ease"},onMouseEnter:function(e){e.currentTarget.style.background="rgba(0, 0, 0, 0.72)",e.currentTarget.style.transform="translate(-50%, -50%) scale(1.06)"},onMouseLeave:function(e){e.currentTarget.style.background="rgba(0, 0, 0, 0.55)",e.currentTarget.style.transform="translate(-50%, -50%) scale(1)"},title:"Play",children:Q.jsx(Bf,{size:Math.max(24,32*Xe),color:"white",style:{marginLeft:"4px"}})}),rt&&!Oe?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*Xe,"px ").concat(12*Xe,"px ").concat(8*Xe,"px"),zIndex:10,opacity:Be||j.showAds?1:0,transform:Be||j.showAds?"translateY(0)":"translateY(6px)",pointerEvents:Be||j.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*Xe,"px"),cursor:"pointer",position:"relative",transition:"height 0.1s ease"},onClick:function(e){if(B.current&&de>0&&isFinite(de)){var t=e.currentTarget.getBoundingClientRect(),r=e.clientX-t.left,i=Math.max(0,Math.min(1,r/t.width))*de;isFinite(i)&&i>=0&&i<=de&&(B.current.currentTime=i)}Qe()},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:j.showAds?"#f5c518":"#ff0000",borderRadius:"1.5px",width:"".concat(nt,"%"),transition:"width 0.15s linear"}}),Q.jsx("div",{className:"sc-progress-thumb",style:{position:"absolute",top:"50%",left:"".concat(nt,"%"),transform:"translate(-50%, -50%) scale(0)",width:"13px",height:"13px",background:j.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*Xe,"px")},children:[Q.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"".concat(8*Xe,"px")},children:[Q.jsx("button",{className:"sc-ctrl-btn",onClick:function(){var e;B.current&&(B.current.paused?B.current.src||B.current.currentSrc&&""!==B.current.currentSrc||B.current.readyState>=1?(null===(e=B.current.play())||void 0===e||e.catch(function(e){console.error("[StormcloudVideoPlayer] Failed to play:",e)}),Me(!1)):console.warn("[StormcloudVideoPlayer] Cannot play: video has no valid source"):(B.current.pause(),Me(!0)));Qe()},style:{padding:"".concat(8*Xe,"px"),borderRadius:"50%",minWidth:"".concat(36*Xe,"px"),minHeight:"".concat(36*Xe,"px")},title:ae?"Pause":"Play",children:ae?Q.jsx(Uf,{size:Math.max(14,18*Xe)}):Q.jsx(Bf,{size:Math.max(14,18*Xe),style:{marginLeft:"2px"}})}),Q.jsxs("div",{style:{display:"flex",alignItems:"center",paddingRight:"".concat(6*Xe,"px")},onMouseEnter:function(){return Se(!0)},onMouseLeave:function(){return Se(!1)},children:[Q.jsx("button",{className:"sc-ctrl-btn",onClick:function(){U.current&&U.current.toggleMute(),null==h||h(),Qe()},style:{padding:"".concat(8*Xe,"px"),borderRadius:"50%",minWidth:"".concat(36*Xe,"px"),minHeight:"".concat(36*Xe,"px")},title:Z?"Unmute":"Mute",children:Q.jsx(at,{size:Math.max(14,18*Xe)})}),Q.jsx("div",{style:{width:Ee?"".concat(68*Xe,"px"):"0px",overflow:"hidden",transition:"width 0.2s cubic-bezier(0.4, 0, 0.2, 1)",display:"flex",alignItems:"center",paddingLeft:Ee?"".concat(3*Xe,"px"):"0",paddingRight:Ee?"".concat(8*Xe,"px"):"0"},children:Q.jsxs("div",{style:{position:"relative",width:"".concat(56*Xe,"px"),height:"3px",cursor:"pointer",borderRadius:"1.5px"},onMouseDown:function(e){e.preventDefault();var t=e.currentTarget,r=function(e){var r=t.getBoundingClientRect();et(Math.max(0,Math.min(1,(e.clientX-r.left)/r.width)))},i=function(){document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",i)};document.addEventListener("mousemove",r),document.addEventListener("mouseup",i);var n=t.getBoundingClientRect();et(Math.max(0,Math.min(1,(e.clientX-n.left)/n.width)))},onClick:function(e){e.stopPropagation();var t=e.currentTarget.getBoundingClientRect();et(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*(Z?0:ve),"%"),background:"#fff",borderRadius:"1.5px",transition:"width 0.1s ease-out"}}),Q.jsx("div",{style:{position:"absolute",top:"50%",left:"".concat(100*(Z?0:ve),"%"),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*Xe,"px"),fontFamily:"Roboto, 'Segoe UI', Arial, sans-serif",color:"rgba(255, 255, 255, 0.9)",display:Ge<480?"none":"block",fontVariantNumeric:"tabular-nums",userSelect:"none",marginLeft:"".concat(4*Xe,"px")},children:[Ze(le)," ",Q.jsx("span",{style:{color:"rgba(255,255,255,0.5)"},children:"/"})," ",Ze(de)]})]}),Q.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"".concat(8*Xe,"px")},children:[Q.jsxs("div",{style:{position:"relative",display:Ge<600?"none":"block"},children:[Q.jsxs("button",{className:"sc-ctrl-btn",onClick:function(){be(!Ae),Qe()},style:{padding:"".concat(6*Xe,"px ").concat(10*Xe,"px"),borderRadius:"".concat(6*Xe,"px"),fontSize:"".concat(13*Xe,"px"),fontFamily:"'SF Mono', 'Cascadia Code', monospace",fontWeight:"600",minHeight:"".concat(32*Xe,"px")},title:"Playback Speed",children:[me,"x"]}),Ae&&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,B.current&&isFinite(t)&&t>0&&(B.current.playbackRate=t),void be(!1);var t},style:{display:"block",width:"100%",padding:"".concat(8*Xe,"px ").concat(14*Xe,"px"),background:me===e?"rgba(255, 255, 255, 0.12)":"transparent",border:"none",color:me===e?"#fff":"rgba(255, 255, 255, 0.7)",cursor:"pointer",fontSize:"".concat(12*Xe,"px"),fontFamily:"'SF Mono', monospace",fontWeight:me===e?"700":"500",textAlign:"center",transition:"background 0.15s ease, color 0.15s ease"},onMouseEnter:function(t){me!==e&&(t.target.style.background="rgba(255, 255, 255, 0.08)",t.target.style.color="#fff")},onMouseLeave:function(t){me!==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(){f?f():H.current&&(document.fullscreenElement?document.exitFullscreen().catch(function(){}):H.current.requestFullscreen().catch(function(){})),Qe()},style:{padding:"".concat(8*Xe,"px"),borderRadius:"50%",minWidth:"".concat(36*Xe,"px"),minHeight:"".concat(36*Xe,"px")},title:re?"Exit Fullscreen":"Enter Fullscreen",children:re?Q.jsx(Gf,{size:Math.max(14,18*Xe)}):Q.jsx(Vf,{size:Math.max(14,18*Xe)})})]})]})]}):c&&!Oe&&Q.jsxs(Q.Fragment,{children:[Q.jsxs("div",{style:{position:"absolute",top:"".concat(10*Xe,"px"),left:"".concat(10*Xe,"px"),display:"flex",alignItems:"center",gap:"6px",zIndex:10,opacity:Be?1:0,transition:"opacity 0.35s ease"},children:[Q.jsx("div",{style:{width:"8px",height:"8px",borderRadius:"50%",background:"#ff3b30",animation:"sc-pulse 1.5s ease-in-out infinite",flexShrink:0}}),Q.jsx("span",{style:{fontSize:"".concat(12*Xe,"px"),fontFamily:"'SF Pro Display', 'Segoe UI', Arial, sans-serif",fontWeight:700,letterSpacing:"0.08em",color:"#fff",textShadow:"0 1px 3px rgba(0,0,0,0.6)",userSelect:"none"},children:"LIVE"})]}),Q.jsxs("div",{className:"sc-controls-bar",style:{position:"absolute",bottom:"".concat(10*Xe,"px"),right:"".concat(10*Xe,"px"),display:"flex",flexDirection:je?"column":"row",alignItems:je?"flex-end":"center",gap:"".concat(8*Xe,"px"),zIndex:10,opacity:Be?1:0,transform:Be?"translateY(0)":"translateY(4px)",pointerEvents:Be?"auto":"none"},children:[Q.jsxs("div",{style:{display:"flex",alignItems:"center",background:"rgba(0, 0, 0, 0.6)",borderRadius:"".concat(18*Xe,"px"),padding:"2px",paddingRight:"".concat(8*Xe,"px")},onMouseEnter:function(){return Se(!0)},onMouseLeave:function(){return Se(!1)},children:[Q.jsx("button",{className:"sc-ctrl-btn",onClick:function(){U.current&&U.current.toggleMute(),null==h||h(),Qe()},style:{padding:"".concat(8*Xe,"px"),borderRadius:"50%",minWidth:"".concat(36*Xe,"px"),minHeight:"".concat(36*Xe,"px")},title:Z?"Unmute":"Mute",children:Q.jsx(at,{size:Math.max(14,18*Xe)})}),Q.jsx("div",{style:{width:Ee?"".concat(68*Xe,"px"):"0px",overflow:"hidden",transition:"width 0.2s cubic-bezier(0.4, 0, 0.2, 1)",display:"flex",alignItems:"center",paddingLeft:Ee?"".concat(3*Xe,"px"):"0",paddingRight:Ee?"".concat(10*Xe,"px"):"0"},children:Q.jsxs("div",{style:{position:"relative",width:"".concat(56*Xe,"px"),height:"3px",cursor:"pointer",borderRadius:"1.5px"},onMouseDown:function(e){e.preventDefault();var t=e.currentTarget,r=function(e){var r=t.getBoundingClientRect();et(Math.max(0,Math.min(1,(e.clientX-r.left)/r.width)))},i=function(){document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",i)};document.addEventListener("mousemove",r),document.addEventListener("mouseup",i);var n=t.getBoundingClientRect();et(Math.max(0,Math.min(1,(e.clientX-n.left)/n.width)))},onClick:function(e){e.stopPropagation();var t=e.currentTarget.getBoundingClientRect();et(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*(Z?0:ve),"%"),background:"#fff",borderRadius:"1.5px",transition:"width 0.1s ease-out"}}),Q.jsx("div",{style:{position:"absolute",top:"50%",left:"".concat(100*(Z?0:ve),"%"),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(){f?f():H.current&&(document.fullscreenElement?document.exitFullscreen().catch(function(){}):H.current.requestFullscreen().catch(function(){})),Qe()},style:{padding:"".concat(8*Xe,"px"),borderRadius:"50%",minWidth:"".concat(36*Xe,"px"),minHeight:"".concat(36*Xe,"px"),background:"rgba(0, 0, 0, 0.6)"},title:re?"Exit Fullscreen":"Enter Fullscreen",children:re?Q.jsx(Gf,{size:Math.max(14,18*Xe)}):Q.jsx(Vf,{size:Math.max(14,18*Xe)})})]})]}),v&&Q.jsx("div",{onClick:v,style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:1,cursor:"pointer"}})]})]})},function(e,t){var r,i,n,a,s,o;try{for(var l=F(Hf),u=l.next();!u.done;u=l.next()){if(e[v=u.value]!==t[v])return!1}}catch(e){r={error:e}}finally{try{u&&!u.done&&(i=l.return)&&i.call(l)}finally{if(r)throw r.error}}try{for(var c=F(["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=F(["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}),qf=function(){},Wf={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:"",isVmap:!1,vmapUrl:"",adFailsafeTimeoutMs:1e4,minSegmentsBeforePlay:2,onStart:qf,onPlay:qf,onPause:qf,onBuffer:qf,onBufferEnd:qf,onEnded:qf,onError:qf,onDuration:qf,onSeek:qf,onProgress:qf,onVolumeToggle:qf,onFullscreenToggle:qf,onControlClick:qf},Yf=$.lazy,zf=function(e,t){var r=_({},e);return t.forEach(function(e){delete r[e]}),r},Xf=function(e){return"undefined"!=typeof window&&window.MediaStream&&e instanceof window.MediaStream},Qf=function(e){for(var t,r,i=[],n=1;n<arguments.length;n++)i[n-1]=arguments[n];if(!i.length)return e;var a=i.shift();if($f(e)&&$f(a))for(var s in a)$f(a[s])?(e[s]||Object.assign(e,((t={})[s]={},t)),Qf(e[s],a[s])):Object.assign(e,((r={})[s]=a[s],r));return Qf.apply(void 0,B([e],N(i),!1))},$f=function(e){return e&&"object"===R(e)&&!Array.isArray(e)},Jf="undefined"!=typeof window&&window.document,Zf="undefined"!=typeof self&&self.window&&self.window.document,ev=Jf&&/iPad|iPhone|iPod/.test(navigator.userAgent),tv=Jf&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent),rv=/\.(m3u8)($|\?)/i,iv=/\/hls\//i,nv=/\.(mpd)($|\?)/i,av=/\.(mp4|webm|ogg|avi|mov|wmv|flv|mkv)($|\?)/i,sv=/\.(mp3|wav|ogg|aac|wma|flac|m4a)($|\?)/i,ov={hls:function(e){return!(!e||"string"!=typeof e)&&(rv.test(e)||iv.test(e))},dash:function(e){return!(!e||"string"!=typeof e)&&nv.test(e)},video:function(e){return!(!e||"string"!=typeof e)&&av.test(e)},audio:function(e){return!(!e||"string"!=typeof e)&&sv.test(e)},file:function(e){return!(!e||"string"!=typeof e)&&(av.test(e)||sv.test(e))}},lv=function(e){function t(){var t=e.apply(this,B([],N(arguments),!1))||this;return t.player=null,t.mounted=!1,t.load=function(){return x(t,void 0,void 0,function(){var e,t,r,i,n,a,s,o;return O(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.isLiveStream&&(e.isLiveStream=this.props.isLiveStream),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),void 0!==this.props.ctvAdRequest&&(e.ctvAdRequest=this.props.ctvAdRequest),this.player=new bf(e),null===(i=(r=this.props).onMount)||void 0===i||i.call(r,this),[4,this.player.load()];case 2:return l.sent(),this.mounted&&(null===(a=(n=this.props).onReady)||void 0===a||a.call(n)),[3,4];case 3:return t=l.sent(),this.mounted&&(null===(o=(s=this.props).onError)||void 0===o||o.call(s,t)),[3,4];case 4:return[2]}})})},t.play=function(){var e,r,i;if(t.props.videoElement){var n=t.props.videoElement;n.src||n.currentSrc&&""!==n.currentSrc||n.readyState>=1?(null===(e=n.play())||void 0===e||e.catch(function(e){var r,i;console.error("[HlsPlayer] Failed to play:",e),null===(i=(r=t.props).onError)||void 0===i||i.call(r,e)}),null===(i=(r=t.props).onPlay)||void 0===i||i.call(r)):console.warn("[HlsPlayer] Cannot play: video has no valid source")}},t.pause=function(){var e,r;t.props.videoElement&&(t.props.videoElement.pause(),null===(r=(e=t.props).onPause)||void 0===r||r.call(e))},t.stop=function(){t.pause(),t.props.videoElement&&(t.props.videoElement.currentTime=0)},t.seekTo=function(e,r){t.props.videoElement&&(t.props.videoElement.currentTime=e,r||t.pause())},t.setVolume=function(e){t.props.videoElement&&(t.props.videoElement.volume=Math.max(0,Math.min(1,e)))},t.mute=function(){t.props.videoElement&&(t.props.videoElement.muted=!0)},t.unmute=function(){t.props.videoElement&&(t.props.videoElement.muted=!1)},t.setPlaybackRate=function(e){t.props.videoElement&&e>0&&(t.props.videoElement.playbackRate=e)},t.getDuration=function(){return t.props.videoElement&&isFinite(t.props.videoElement.duration)?t.props.videoElement.duration:null},t.getCurrentTime=function(){return t.props.videoElement&&isFinite(t.props.videoElement.currentTime)?t.props.videoElement.currentTime:null},t.getSecondsLoaded=function(){return t.props.videoElement&&t.props.videoElement.buffered.length>0?t.props.videoElement.buffered.end(t.props.videoElement.buffered.length-1):null},t.getInternalPlayer=function(e){return void 0===e&&(e="player"),"player"===e?t.player:"video"===e?t.props.videoElement:"hls"===e&&t.player?t.player.hls:null},t}return D(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=ov.hls,t}($.Component),uv=function(e){function t(){var t=e.apply(this,B([],N(arguments),!1))||this;return t.mounted=!1,t.ready=!1,t.load=function(){var e,r;if(t.props.videoElement&&t.props.src){var i=t.props.videoElement,n=function(){var e,r;t.mounted&&!t.ready&&(t.ready=!0,null===(r=(e=t.props).onReady)||void 0===r||r.call(e))},a=function(){var e,r;t.mounted&&(null===(r=(e=t.props).onPlay)||void 0===r||r.call(e))},s=function(){var e,r;t.mounted&&(null===(r=(e=t.props).onPause)||void 0===r||r.call(e))},o=function(){var e,r;t.mounted&&(null===(r=(e=t.props).onEnded)||void 0===r||r.call(e))},l=function(e){var r,i;t.mounted&&(null===(i=(r=t.props).onError)||void 0===i||i.call(r,e))},u=function(){var e,r;t.mounted&&(null===(r=(e=t.props).onLoaded)||void 0===r||r.call(e))};return i.addEventListener("loadedmetadata",n),i.addEventListener("play",a),i.addEventListener("pause",s),i.addEventListener("ended",o),i.addEventListener("error",l),i.addEventListener("loadeddata",u),i.src=t.props.src,void 0!==t.props.autoplay&&(i.autoplay=t.props.autoplay),void 0!==t.props.muted&&(i.muted=t.props.muted),void 0!==t.props.loop&&(i.loop=t.props.loop),void 0!==t.props.controls&&(i.controls=t.props.controls),void 0!==t.props.playsInline&&(i.playsInline=t.props.playsInline),void 0!==t.props.preload&&(i.preload=t.props.preload),void 0!==t.props.poster&&(i.poster=t.props.poster),null===(r=(e=t.props).onMount)||void 0===r||r.call(e,t),function(){i.removeEventListener("loadedmetadata",n),i.removeEventListener("play",a),i.removeEventListener("pause",s),i.removeEventListener("ended",o),i.removeEventListener("error",l),i.removeEventListener("loadeddata",u)}}},t.play=function(){var e;if(t.props.videoElement){var r=t.props.videoElement;r.src||r.currentSrc&&""!==r.currentSrc||r.readyState>=1?null===(e=r.play())||void 0===e||e.catch(function(e){var r,i;console.error("[FilePlayer] Failed to play:",e),null===(i=(r=t.props).onError)||void 0===i||i.call(r,e)}):console.warn("[FilePlayer] Cannot play: video has no valid source")}},t.pause=function(){t.props.videoElement&&t.props.videoElement.pause()},t.stop=function(){t.pause(),t.props.videoElement&&(t.props.videoElement.currentTime=0)},t.seekTo=function(e,r){t.props.videoElement&&(t.props.videoElement.currentTime=e,r||t.pause())},t.setVolume=function(e){t.props.videoElement&&(t.props.videoElement.volume=Math.max(0,Math.min(1,e)))},t.mute=function(){t.props.videoElement&&(t.props.videoElement.muted=!0)},t.unmute=function(){t.props.videoElement&&(t.props.videoElement.muted=!1)},t.setPlaybackRate=function(e){t.props.videoElement&&e>0&&(t.props.videoElement.playbackRate=e)},t.setLoop=function(e){t.props.videoElement&&(t.props.videoElement.loop=e)},t.getDuration=function(){return t.props.videoElement&&isFinite(t.props.videoElement.duration)?t.props.videoElement.duration:null},t.getCurrentTime=function(){return t.props.videoElement&&isFinite(t.props.videoElement.currentTime)?t.props.videoElement.currentTime:null},t.getSecondsLoaded=function(){return t.props.videoElement&&t.props.videoElement.buffered.length>0?t.props.videoElement.buffered.end(t.props.videoElement.buffered.length-1):null},t.getInternalPlayer=function(e){return void 0===e&&(e="player"),"video"===e?t.props.videoElement:null},t.enablePIP=function(){return x(t,void 0,void 0,function(){var e;return O(this,function(t){switch(t.label){case 0:if(!this.props.videoElement||!("requestPictureInPicture"in this.props.videoElement))return[3,4];t.label=1;case 1:return t.trys.push([1,3,,4]),[4,this.props.videoElement.requestPictureInPicture()];case 2:return t.sent(),[3,4];case 3:return e=t.sent(),console.warn("Picture-in-Picture failed:",e),[3,4];case 4:return[2]}})})},t.disablePIP=function(){return x(t,void 0,void 0,function(){var e;return O(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 D(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=ov.file,t}($.Component),cv=[{key:"hls",name:"HLS Player",canPlay:ov.hls,lazyPlayer:Yf(function(){return Promise.resolve({default:lv})})},{key:"file",name:"File Player",canPlay:ov.file,canEnablePIP:function(e){return ov.file(e)&&(document.pictureInPictureEnabled||"function"==typeof document.webkitSupportsPresentationMode)},lazyPlayer:Yf(function(){return Promise.resolve({default:uv})})}],dv=function(e){function t(){var t=e.apply(this,B([],N(arguments),!1))||this;return t.mounted=!1,t.isReady=!1,t.isPlaying=!1,t.isLoading=!0,t.loadOnReady=null,t.startOnPlay=!0,t.seekOnPlay=null,t.onDurationCalled=!1,t.handlePlayerMount=function(e){t.player||(t.player=e,t.player.load(t.props.src)),t.progress()},t.getInternalPlayer=function(e){return t.player?t.player.getInternalPlayer(e):null},t.progress=function(){var e,r;if(t.props.src&&t.player&&t.isReady){var i=t.getCurrentTime()||0,n=t.getSecondsLoaded(),a=t.getDuration();if(a){var s={playedSeconds:i,played:i/a,loaded:0,loadedSeconds:0};null!==n&&(s.loadedSeconds=n,s.loaded=n/a),s.playedSeconds===t.prevPlayed&&s.loadedSeconds===t.prevLoaded||null===(r=(e=t.props).onProgress)||void 0===r||r.call(e,s),t.prevPlayed=s.playedSeconds,t.prevLoaded=s.loadedSeconds}}t.progressTimeout=window.setTimeout(t.progress,t.props.progressInterval||1e3)},t.handleReady=function(){if(t.mounted){t.isReady=!0,t.isLoading=!1;var e=t.props,r=e.onReady,i=e.playing,n=e.volume,a=e.muted;r(),a||null===n||t.player.setVolume(n),t.loadOnReady?(t.player.load(t.loadOnReady,!0),t.loadOnReady=null):i&&t.player.play(),t.handleDurationCheck()}},t.handlePlay=function(){t.isPlaying=!0,t.isLoading=!1;var e=t.props,r=e.onStart,i=e.onPlay,n=e.playbackRate;t.startOnPlay&&(t.player.setPlaybackRate&&1!==n&&t.player.setPlaybackRate(n),null==r||r(),t.startOnPlay=!1),null==i||i(),t.seekOnPlay&&(t.seekTo(t.seekOnPlay),t.seekOnPlay=null),t.handleDurationCheck()},t.handlePause=function(e){var r,i;t.isPlaying=!1,t.isLoading||null===(i=(r=t.props).onPause)||void 0===i||i.call(r,e)},t.handleEnded=function(){var e=t.props,r=e.activePlayer,i=e.loop,n=e.onEnded;r.loopOnEnded&&i&&t.seekTo(0),i||(t.isPlaying=!1,null==n||n())},t.handleError=function(){for(var e,r,i=[],n=0;n<arguments.length;n++)i[n]=arguments[n];t.isLoading=!1,null===(r=(e=t.props).onError)||void 0===r||r.call(e,i[0],i[1],i[2],i[3])},t.handleDurationCheck=function(){var e,r;clearTimeout(t.durationCheckTimeout);var i=t.getDuration();i?t.onDurationCalled||(null===(r=(e=t.props).onDuration)||void 0===r||r.call(e,i),t.onDurationCalled=!0):t.durationCheckTimeout=window.setTimeout(t.handleDurationCheck,100)},t.handleLoaded=function(){t.isLoading=!1},t}return D(t,e),t.prototype.componentDidMount=function(){this.mounted=!0},t.prototype.componentWillUnmount=function(){clearTimeout(this.progressTimeout),clearTimeout(this.durationCheckTimeout),this.mounted=!1},t.prototype.componentDidUpdate=function(e){var t=this;if(this.player){var r=this.props,i=r.src,n=r.playing,a=r.volume,s=r.muted,o=r.playbackRate,l=r.loop,u=r.activePlayer;if(e.src!==i){if(this.isLoading&&!u.forceLoad&&!Xf(i))return console.warn("StormcloudPlayer: the attempt to load ".concat(i," is being deferred until the player has loaded")),void(this.loadOnReady=i||null);this.isLoading=!0,this.startOnPlay=!0,this.onDurationCalled=!1,this.player.load(i,this.isReady)}e.playing||!n||this.isPlaying||this.player.play(),e.playing&&!n&&this.isPlaying&&this.player.pause(),e.volume!==a&&null!==a&&this.player.setVolume(a),e.muted!==s&&(s?this.player.mute():(this.player.unmute(),null!==a&&setTimeout(function(){return t.player.setVolume(a)}))),e.playbackRate!==o&&this.player.setPlaybackRate&&this.player.setPlaybackRate(o),e.loop!==l&&this.player.setLoop&&this.player.setLoop(l)}},t.prototype.getDuration=function(){return this.isReady?this.player.getDuration():null},t.prototype.getCurrentTime=function(){return this.isReady?this.player.getCurrentTime():null},t.prototype.getSecondsLoaded=function(){return this.isReady?this.player.getSecondsLoaded():null},t.prototype.seekTo=function(e,t,r){var i=this;if(this.isReady){if(t?"fraction"===t:e>0&&e<1){var n=this.player.getDuration();return n?void this.player.seekTo(n*e,r):void console.warn("StormcloudPlayer: could not seek using fraction – duration not yet available")}this.player.seekTo(e,r)}else 0!==e&&(this.seekOnPlay=e,setTimeout(function(){i.seekOnPlay=null},5e3))},t.prototype.render=function(){var e=this.props.activePlayer;return e?J.createElement(e,_(_({},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=Wf,t}($.Component),hv="undefined"!=typeof window&&window.document,fv="undefined"!=typeof self&&self.window&&self.window.document,vv=hv||fv?$.Suspense:function(){return null},gv=["src","playing","loop","controls","volume","muted","playbackRate","width","height","style","progressInterval","playsInline","autoplay","preload","poster","className","wrapperClassName","wrapperStyle","allowNativeHls","lowLatencyMode","isLiveStream","driftToleranceMs","immediateManifestAds","debugAdTiming","showCustomControls","licenseKey","isVmap","vmapUrl","adFailsafeTimeoutMs","minSegmentsBeforePlay","ctvAdRequest","onReady","onStart","onPlay","onPause","onBuffer","onBufferEnd","onEnded","onError","onDuration","onSeek","onProgress","onVolumeToggle","onFullscreenToggle","onControlClick"],pv=[],mv=function(e,t){var r;return r=function(r){function i(){var i=r.apply(this,B([],N(arguments),!1))||this;return i.state={showPreview:!1},i.references={wrapper:function(e){i.wrapper=e},player:function(e){i.player=e}},i.getActivePlayer=function(r){var i,n;if(!r)return null;try{for(var a=F(B(B([],N(pv),!1),N(e),!1)),s=a.next();!s.done;s=a.next()){var o=s.value;if(o.canPlay(r))return o}}catch(e){i={error:e}}finally{try{s&&!s.done&&(n=a.return)&&n.call(a)}finally{if(i)throw i.error}}return t||null},i.getAttributes=function(e){return zf(i.props,gv)},i.handleReady=function(){var e,t;null===(t=(e=i.props).onReady)||void 0===t||t.call(e,i)},i.seekTo=function(e,t,r){if(!i.player)return null;i.player.seekTo(e,t,r)},i.getCurrentTime=function(){return i.player?i.player.getCurrentTime():null},i.getSecondsLoaded=function(){return i.player?i.player.getSecondsLoaded():null},i.getDuration=function(){return i.player?i.player.getDuration():null},i.getInternalPlayer=function(e){return void 0===e&&(e="player"),i.player?i.player.getInternalPlayer(e):null},i.renderActivePlayer=function(e){if(!e)return null;var t=i.getActivePlayer(e);return t?J.createElement(dv,_(_({},i.props),{key:t.key,ref:i.references.player,activePlayer:t.lazyPlayer||t,onReady:i.handleReady})):null},i}return D(i,r),i.prototype.render=function(){var e=this.props,t=e.src,r=e.style,i=e.width,n=e.height,a=e.fallback,s=e.wrapper,o=this.getAttributes(t),l="string"==typeof s?this.references.wrapper:void 0;return J.createElement(s,_({ref:l,style:_(_({},r),{width:i,height:n})},o),J.createElement(vv,{fallback:a},this.renderActivePlayer(t)))},i}($.Component),r.displayName="StormcloudPlayer",r.defaultProps=_(_({},Wf),{fallback:null,wrapper:"div"}),r.addCustomPlayer=function(e){pv.push(e)},r.removeCustomPlayers=function(){pv.length=0},r.canPlay=function(t){var r,i;try{for(var n=F(B(B([],N(pv),!1),N(e),!1)),a=n.next();!a.done;a=n.next()){if(a.value.canPlay(t))return!0}}catch(e){r={error:e}}finally{try{a&&!a.done&&(i=n.return)&&i.call(n)}finally{if(r)throw r.error}}return!1},r.canEnablePIP=function(t){var r,i;try{for(var n=F(B(B([],N(pv),!1),N(e),!1)),a=n.next();!a.done;a=n.next()){var s=a.value;if(s.canEnablePIP&&s.canEnablePIP(t))return!0}}catch(e){r={error:e}}finally{try{a&&!a.done&&(i=n.return)&&i.call(n)}finally{if(r)throw r.error}}return!1},r},yv=mv(cv,cv[cv.length-1]);e.DEFAULT_TRACKING_INGEST_CONFIG=Gd,e.IS_BROWSER=Jf,e.IS_GLOBAL=Zf,e.IS_IOS=ev,e.IS_SAFARI=tv,e.SUPPORTS_DASH=function(){if(!Jf)return!1;var e=document.createElement("video");return Boolean(e.canPlayType("application/dash+xml"))},e.SUPPORTS_HLS=function(){if(!Jf)return!1;var e=document.createElement("video");return Boolean(e.canPlayType("application/vnd.apple.mpegurl"))},e.StormcloudPlayer=yv,e.StormcloudVideoPlayer=bf,e.StormcloudVideoPlayerComponent=jf,e.applyTrackingIngestConfig=Kd,e.buildAnalyticsContext=Rh,e.canPlay=ov,e.configureTrackingIngest=function(e){Kd(e)},e.createHlsAdPlayer=Md,e.createPalNonceManager=Vd,e.createStormcloudPlayer=mv,e.default=jf,e.detectBrowser=yd,e.getBrowserConfigOverrides=Ed,e.getBrowserID=Ch,e.getClientInfo=Lh,e.ingestPlayerTracking=Wd,e.initializePolyfills=Bh,e.isMediaStream=Xf,e.isTrackingIngestEnabled=jd,e.lazy=Yf,e.logBrowserInfo=Sd,e.merge=Qf,e.omit=zf,e.parseQuery=function(e){var t={},r=e.split("?")[1]||"";if(!r)return t;var i=function(e){e.split("&").forEach(function(e){var r=N(e.split("="),2),i=r[0],n=r[1];if(i)try{t[decodeURIComponent(i)]=n?decodeURIComponent(n.replace(/\+/g," ")):""}catch(e){t[i]=n||""}})};if("undefined"!=typeof URLSearchParams)try{return new URLSearchParams(r).forEach(function(e,r){t[r]=e}),t}catch(e){i(r)}else i(r);return t},e.players=cv,e.randomString=function(){return Math.random().toString(36).substr(2,9)},e.requiresMediaPipelineResetAfterAds=kd,e.sendAdDetectTracking=xh,e.sendAdImpressionTracking=Fh,e.sendAdLoadedTracking=Oh,e.sendHeartbeat=Nh,e.sendInitialTracking=Mh,e.supportsFeature=function(e){switch(e){case"urlsearchparams":return"undefined"!=typeof URLSearchParams;case"textencoder":return"undefined"!=typeof TextEncoder;case"promises":return"undefined"!=typeof Promise;case"fetch":return"undefined"!=typeof fetch;case"crypto":return"undefined"!=typeof crypto&&void 0!==crypto.subtle;default:return!1}},e.supportsModernJS=function(){try{return"undefined"!=typeof Promise&&"undefined"!=typeof Map&&"undefined"!=typeof Set&&void 0!==Array.from&&void 0!==Object.assign&&void 0!==Array.prototype.forEach&&void 0!==String.prototype.includes}catch(e){return!1}},e.supportsWebKitPresentationMode=function(){return"undefined"!=typeof window&&"webkitSupportsPresentationMode"in document.createElement("video")},e.trackingIngestConfig=Hd,Object.defineProperty(e,"__esModule",{value:!0})});
|