stormcloud-video-player 0.3.16 → 0.3.18
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 -10
- package/lib/index.cjs +314 -142
- package/lib/index.cjs.map +1 -1
- package/lib/index.d.cts +7 -0
- package/lib/index.d.ts +7 -0
- package/lib/index.js +314 -142
- package/lib/index.js.map +1 -1
- package/lib/player/StormcloudVideoPlayer.cjs +303 -139
- package/lib/player/StormcloudVideoPlayer.cjs.map +1 -1
- package/lib/player/StormcloudVideoPlayer.d.cts +7 -0
- package/lib/players/FilePlayer.cjs.map +1 -1
- package/lib/players/HlsPlayer.cjs +303 -139
- package/lib/players/HlsPlayer.cjs.map +1 -1
- package/lib/players/index.cjs +303 -139
- package/lib/players/index.cjs.map +1 -1
- package/lib/sdk/hlsAdPlayer.cjs +6 -0
- package/lib/sdk/hlsAdPlayer.cjs.map +1 -1
- package/lib/sdk/ima.cjs +4 -0
- package/lib/sdk/ima.cjs.map +1 -1
- package/lib/ui/StormcloudVideoPlayer.cjs +314 -142
- package/lib/ui/StormcloudVideoPlayer.cjs.map +1 -1
- package/lib/utils/browserCompat.cjs.map +1 -1
- package/lib/utils/polyfills.cjs.map +1 -1
- package/lib/utils/tracking.cjs.map +1 -1
- package/package.json +5 -1
- package/rollup.config.js +22 -0
|
@@ -1,10 +1 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).StormcloudVP={})}(this,function(e){"use strict";var t=function(e,i){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},t(e,i)};function i(e,i){if("function"!=typeof i&&null!==i)throw new TypeError("Class extends value "+String(i)+" is not a constructor or null");function s(){this.constructor=e}t(e,i),e.prototype=null===i?Object.create(i):(s.prototype=i.prototype,new s)}var s=function(){return s=Object.assign||function(e){for(var t,i=1,s=arguments.length;i<s;i++)for(var r in t=arguments[i])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},s.apply(this,arguments)};function r(e,t){var i={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(i[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(s=Object.getOwnPropertySymbols(e);r<s.length;r++)t.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(e,s[r])&&(i[s[r]]=e[s[r]])}return i}function n(e,t,i,s){return new(i||(i=Promise))(function(r,n){function a(e){try{l(s.next(e))}catch(e){n(e)}}function o(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(a,o)}l((s=s.apply(e,t||[])).next())})}function a(e,t){var i,s,r,n={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=o(0),a.throw=o(1),a.return=o(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function o(o){return function(l){return function(o){if(i)throw new TypeError("Generator is already executing.");for(;a&&(a=0,o[0]&&(n=0)),n;)try{if(i=1,s&&(r=2&o[0]?s.return:o[0]?s.throw||((r=s.return)&&r.call(s),0):s.next)&&!(r=r.call(s,o[1])).done)return r;switch(s=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return n.label++,{value:o[1],done:!1};case 5:n.label++,s=o[1],o=[0];continue;case 7:o=n.ops.pop(),n.trys.pop();continue;default:if(!(r=n.trys,(r=r.length>0&&r[r.length-1])||6!==o[0]&&2!==o[0])){n=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]<r[3])){n.label=o[1];break}if(6===o[0]&&n.label<r[1]){n.label=r[1],r=o;break}if(r&&n.label<r[2]){n.label=r[2],n.ops.push(o);break}r[2]&&n.ops.pop(),n.trys.pop();continue}o=t.call(e,n)}catch(e){o=[6,e],s=0}finally{i=r=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}}Object.create;function o(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],s=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&s>=e.length&&(e=void 0),{value:e&&e[s++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function l(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var s,r,n=i.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(s=n.next()).done;)a.push(s.value)}catch(e){r={error:e}}finally{try{s&&!s.done&&(i=n.return)&&i.call(n)}finally{if(r)throw r.error}}return a}function d(e,t,i){if(i||2===arguments.length)for(var s,r=0,n=t.length;r<n;r++)!s&&r in t||(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))}Object.create;"function"==typeof SuppressedError&&SuppressedError;"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function c(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var u,h={exports:{}},f={};var g,p={exports:{}},m={};function v(){if(g)return m;g=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),i=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),r=Symbol.for("react.profiler"),n=Symbol.for("react.consumer"),a=Symbol.for("react.context"),o=Symbol.for("react.forward_ref"),l=Symbol.for("react.suspense"),d=Symbol.for("react.memo"),c=Symbol.for("react.lazy"),u=Symbol.for("react.activity"),h=Symbol.iterator;var f={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},p=Object.assign,v={};function y(e,t,i){this.props=e,this.context=t,this.refs=v,this.updater=i||f}function T(){}function E(e,t,i){this.props=e,this.context=t,this.refs=v,this.updater=i||f}y.prototype.isReactComponent={},y.prototype.setState=function(e,t){if("object"!=typeof 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")},y.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")},T.prototype=y.prototype;var S=E.prototype=new T;S.constructor=E,p(S,y.prototype),S.isPureReactComponent=!0;var A=Array.isArray;function b(){}var L={H:null,A:null,T:null,S:null},R=Object.prototype.hasOwnProperty;function I(t,i,s){var r=s.ref;return{$$typeof:e,type:t,key:i,ref:void 0!==r?r:null,props:s}}function k(t){return"object"==typeof t&&null!==t&&t.$$typeof===e}var w=/\/+/g;function P(e,t){return"object"==typeof e&&null!==e&&null!=e.key?(i=""+e.key,s={"=":"=0",":":"=2"},"$"+i.replace(/[=:]/g,function(e){return s[e]})):t.toString(36);var i,s}function D(i,s,r,n,a){var o=typeof i;"undefined"!==o&&"boolean"!==o||(i=null);var l,d,u=!1;if(null===i)u=!0;else switch(o){case"bigint":case"string":case"number":u=!0;break;case"object":switch(i.$$typeof){case e:case t:u=!0;break;case c:return D((u=i._init)(i._payload),s,r,n,a)}}if(u)return a=a(i),u=""===n?"."+P(i,0):n,A(a)?(r="",null!=u&&(r=u.replace(w,"$&/")+"/"),D(a,s,r,"",function(e){return e})):null!=a&&(k(a)&&(l=a,d=r+(null==a.key||i&&i.key===a.key?"":(""+a.key).replace(w,"$&/")+"/")+u,a=I(l.type,d,l.props)),s.push(a)),1;u=0;var f,g=""===n?".":n+":";if(A(i))for(var p=0;p<i.length;p++)u+=D(n=i[p],s,r,o=g+P(n,p),a);else if("function"==typeof(p=null===(f=i)||"object"!=typeof f?null:"function"==typeof(f=h&&f[h]||f["@@iterator"])?f:null))for(i=p.call(i),p=0;!(n=i.next()).done;)u+=D(n=n.value,s,r,o=g+P(n,p++),a);else if("object"===o){if("function"==typeof i.then)return D(function(e){switch(e.status){case"fulfilled":return e.value;case"rejected":throw e.reason;default:switch("string"==typeof e.status?e.then(b,b):(e.status="pending",e.then(function(t){"pending"===e.status&&(e.status="fulfilled",e.value=t)},function(t){"pending"===e.status&&(e.status="rejected",e.reason=t)})),e.status){case"fulfilled":return e.value;case"rejected":throw e.reason}}throw e}(i),s,r,n,a);throw s=String(i),Error("Objects are not valid as a React child (found: "+("[object Object]"===s?"object with keys {"+Object.keys(i).join(", ")+"}":s)+"). If you meant to render a collection of children, use an array instead.")}return u}function x(e,t,i){if(null==e)return e;var s=[],r=0;return D(e,s,"","",function(e){return t.call(i,e,r++)}),s}function C(e){if(-1===e._status){var t=e._result;(t=t()).then(function(t){0!==e._status&&-1!==e._status||(e._status=1,e._result=t)},function(t){0!==e._status&&-1!==e._status||(e._status=2,e._result=t)}),-1===e._status&&(e._status=0,e._result=t)}if(1===e._status)return e._result.default;throw e._result}var _="function"==typeof reportError?reportError:function(e){if("object"==typeof window&&"function"==typeof window.ErrorEvent){var t=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:"object"==typeof e&&null!==e&&"string"==typeof e.message?String(e.message):String(e),error:e});if(!window.dispatchEvent(t))return}else if("object"==typeof process&&"function"==typeof process.emit)return void process.emit("uncaughtException",e);console.error(e)},M={map:x,forEach:function(e,t,i){x(e,function(){t.apply(this,arguments)},i)},count:function(e){var t=0;return x(e,function(){t++}),t},toArray:function(e){return x(e,function(e){return e})||[]},only:function(e){if(!k(e))throw Error("React.Children.only expected to receive a single React element child.");return e}};return m.Activity=u,m.Children=M,m.Component=y,m.Fragment=i,m.Profiler=r,m.PureComponent=E,m.StrictMode=s,m.Suspense=l,m.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=L,m.__COMPILER_RUNTIME={__proto__:null,c:function(e){return L.H.useMemoCache(e)}},m.cache=function(e){return function(){return e.apply(null,arguments)}},m.cacheSignal=function(){return null},m.cloneElement=function(e,t,i){if(null==e)throw Error("The argument must be a React element, but you passed "+e+".");var s=p({},e.props),r=e.key;if(null!=t)for(n in void 0!==t.key&&(r=""+t.key),t)!R.call(t,n)||"key"===n||"__self"===n||"__source"===n||"ref"===n&&void 0===t.ref||(s[n]=t[n]);var n=arguments.length-2;if(1===n)s.children=i;else if(1<n){for(var a=Array(n),o=0;o<n;o++)a[o]=arguments[o+2];s.children=a}return I(e.type,r,s)},m.createContext=function(e){return(e={$$typeof:a,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null}).Provider=e,e.Consumer={$$typeof:n,_context:e},e},m.createElement=function(e,t,i){var s,r={},n=null;if(null!=t)for(s in void 0!==t.key&&(n=""+t.key),t)R.call(t,s)&&"key"!==s&&"__self"!==s&&"__source"!==s&&(r[s]=t[s]);var a=arguments.length-2;if(1===a)r.children=i;else if(1<a){for(var o=Array(a),l=0;l<a;l++)o[l]=arguments[l+2];r.children=o}if(e&&e.defaultProps)for(s in a=e.defaultProps)void 0===r[s]&&(r[s]=a[s]);return I(e,n,r)},m.createRef=function(){return{current:null}},m.forwardRef=function(e){return{$$typeof:o,render:e}},m.isValidElement=k,m.lazy=function(e){return{$$typeof:c,_payload:{_status:-1,_result:e},_init:C}},m.memo=function(e,t){return{$$typeof:d,type:e,compare:void 0===t?null:t}},m.startTransition=function(e){var t=L.T,i={};L.T=i;try{var s=e(),r=L.S;null!==r&&r(i,s),"object"==typeof s&&null!==s&&"function"==typeof s.then&&s.then(b,_)}catch(e){_(e)}finally{null!==t&&null!==i.types&&(t.types=i.types),L.T=t}},m.unstable_useCacheRefresh=function(){return L.H.useCacheRefresh()},m.use=function(e){return L.H.use(e)},m.useActionState=function(e,t,i){return L.H.useActionState(e,t,i)},m.useCallback=function(e,t){return L.H.useCallback(e,t)},m.useContext=function(e){return L.H.useContext(e)},m.useDebugValue=function(){},m.useDeferredValue=function(e,t){return L.H.useDeferredValue(e,t)},m.useEffect=function(e,t){return L.H.useEffect(e,t)},m.useEffectEvent=function(e){return L.H.useEffectEvent(e)},m.useId=function(){return L.H.useId()},m.useImperativeHandle=function(e,t,i){return L.H.useImperativeHandle(e,t,i)},m.useInsertionEffect=function(e,t){return L.H.useInsertionEffect(e,t)},m.useLayoutEffect=function(e,t){return L.H.useLayoutEffect(e,t)},m.useMemo=function(e,t){return L.H.useMemo(e,t)},m.useOptimistic=function(e,t){return L.H.useOptimistic(e,t)},m.useReducer=function(e,t,i){return L.H.useReducer(e,t,i)},m.useRef=function(e){return L.H.useRef(e)},m.useState=function(e){return L.H.useState(e)},m.useSyncExternalStore=function(e,t,i){return L.H.useSyncExternalStore(e,t,i)},m.useTransition=function(){return L.H.useTransition()},m.version="19.2.0",m}var y;p.exports;function T(){return y||(y=1,p.exports=v()),p.exports}
|
|
2
|
-
/**
|
|
3
|
-
* @license React
|
|
4
|
-
* react-jsx-runtime.development.js
|
|
5
|
-
*
|
|
6
|
-
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
7
|
-
*
|
|
8
|
-
* This source code is licensed under the MIT license found in the
|
|
9
|
-
* LICENSE file in the root directory of this source tree.
|
|
10
|
-
*/var E;h.exports;var S=(E||(E=1,h.exports=function(){if(u)return f;u=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function i(t,i,s){var r=null;if(void 0!==s&&(r=""+s),void 0!==i.key&&(r=""+i.key),"key"in i)for(var n in s={},i)"key"!==n&&(s[n]=i[n]);else s=i;return i=s.ref,{$$typeof:e,type:t,key:r,ref:void 0!==i?i:null,props:s}}return f.Fragment=t,f.jsx=i,f.jsxs=i,f}()),h.exports),A=T(),b=c(A);const L=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},R=Number.isSafeInteger||function(e){return"number"==typeof e&&Math.abs(e)<=I},I=Number.MAX_SAFE_INTEGER||9007199254740991;let k=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}({}),w=function(e){return e.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",e.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",e.KEY_SYSTEM_NO_SESSION="keySystemNoSession",e.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",e.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",e.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",e.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",e.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",e.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",e.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",e.MANIFEST_LOAD_ERROR="manifestLoadError",e.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",e.MANIFEST_PARSING_ERROR="manifestParsingError",e.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",e.LEVEL_EMPTY_ERROR="levelEmptyError",e.LEVEL_LOAD_ERROR="levelLoadError",e.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",e.LEVEL_PARSING_ERROR="levelParsingError",e.LEVEL_SWITCH_ERROR="levelSwitchError",e.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",e.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",e.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",e.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",e.FRAG_LOAD_ERROR="fragLoadError",e.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",e.FRAG_DECRYPT_ERROR="fragDecryptError",e.FRAG_PARSING_ERROR="fragParsingError",e.FRAG_GAP="fragGap",e.REMUX_ALLOC_ERROR="remuxAllocError",e.KEY_LOAD_ERROR="keyLoadError",e.KEY_LOAD_TIMEOUT="keyLoadTimeOut",e.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",e.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",e.BUFFER_APPEND_ERROR="bufferAppendError",e.BUFFER_APPENDING_ERROR="bufferAppendingError",e.BUFFER_STALLED_ERROR="bufferStalledError",e.BUFFER_FULL_ERROR="bufferFullError",e.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",e.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",e.ASSET_LIST_LOAD_ERROR="assetListLoadError",e.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",e.ASSET_LIST_PARSING_ERROR="assetListParsingError",e.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",e.INTERNAL_EXCEPTION="internalException",e.INTERNAL_ABORTED="aborted",e.ATTACH_MEDIA_ERROR="attachMediaError",e.UNKNOWN="unknown",e}({}),P=function(e){return e.MEDIA_ATTACHING="hlsMediaAttaching",e.MEDIA_ATTACHED="hlsMediaAttached",e.MEDIA_DETACHING="hlsMediaDetaching",e.MEDIA_DETACHED="hlsMediaDetached",e.MEDIA_ENDED="hlsMediaEnded",e.STALL_RESOLVED="hlsStallResolved",e.BUFFER_RESET="hlsBufferReset",e.BUFFER_CODECS="hlsBufferCodecs",e.BUFFER_CREATED="hlsBufferCreated",e.BUFFER_APPENDING="hlsBufferAppending",e.BUFFER_APPENDED="hlsBufferAppended",e.BUFFER_EOS="hlsBufferEos",e.BUFFERED_TO_END="hlsBufferedToEnd",e.BUFFER_FLUSHING="hlsBufferFlushing",e.BUFFER_FLUSHED="hlsBufferFlushed",e.MANIFEST_LOADING="hlsManifestLoading",e.MANIFEST_LOADED="hlsManifestLoaded",e.MANIFEST_PARSED="hlsManifestParsed",e.LEVEL_SWITCHING="hlsLevelSwitching",e.LEVEL_SWITCHED="hlsLevelSwitched",e.LEVEL_LOADING="hlsLevelLoading",e.LEVEL_LOADED="hlsLevelLoaded",e.LEVEL_UPDATED="hlsLevelUpdated",e.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",e.LEVELS_UPDATED="hlsLevelsUpdated",e.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",e.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",e.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",e.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",e.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",e.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",e.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",e.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",e.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",e.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",e.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",e.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",e.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",e.CUES_PARSED="hlsCuesParsed",e.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",e.INIT_PTS_FOUND="hlsInitPtsFound",e.FRAG_LOADING="hlsFragLoading",e.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",e.FRAG_LOADED="hlsFragLoaded",e.FRAG_DECRYPTED="hlsFragDecrypted",e.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",e.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",e.FRAG_PARSING_METADATA="hlsFragParsingMetadata",e.FRAG_PARSED="hlsFragParsed",e.FRAG_BUFFERED="hlsFragBuffered",e.FRAG_CHANGED="hlsFragChanged",e.FPS_DROP="hlsFpsDrop",e.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",e.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",e.ERROR="hlsError",e.DESTROYING="hlsDestroying",e.KEY_LOADING="hlsKeyLoading",e.KEY_LOADED="hlsKeyLoaded",e.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",e.BACK_BUFFER_REACHED="hlsBackBufferReached",e.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",e.ASSET_LIST_LOADING="hlsAssetListLoading",e.ASSET_LIST_LOADED="hlsAssetListLoaded",e.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",e.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",e.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",e.INTERSTITIAL_STARTED="hlsInterstitialStarted",e.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",e.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",e.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",e.INTERSTITIAL_ENDED="hlsInterstitialEnded",e.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",e.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",e.EVENT_CUE_ENTER="hlsEventCueEnter",e}({});var D="manifest",x="level",C="audioTrack",_="subtitleTrack",M="main",O="audio",F="subtitle";class U{constructor(e,t=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=i}sample(e,t){const i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class N{constructor(e,t,i,s=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new U(e),this.fast_=new U(t),this.defaultTTFB_=s,this.ttfb_=new U(e)}update(e,t){const{slow_:i,fast_:s,ttfb_:r}=this;i.halfLife!==e&&(this.slow_=new U(e,i.getEstimate(),i.getTotalWeight())),s.halfLife!==t&&(this.fast_=new U(t,s.getEstimate(),s.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new U(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){const i=(e=Math.max(e,this.minDelayMs_))/1e3,s=8*t/i;this.fast_.sample(i,s),this.slow_.sample(i,s)}sampleTTFB(e){const t=e/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(i,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function B(e,t,i){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var s=i.call(e,t);if("object"!=typeof s)return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function $(){return $=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var s in i)({}).hasOwnProperty.call(i,s)&&(e[s]=i[s])}return e},$.apply(null,arguments)}function V(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,s)}return i}function G(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?V(Object(i),!0).forEach(function(t){B(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):V(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}class H{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const i=`[${e}]:`;this.trace=K,this.debug=t.debug.bind(null,i),this.log=t.log.bind(null,i),this.warn=t.warn.bind(null,i),this.info=t.info.bind(null,i),this.error=t.error.bind(null,i)}}const K=function(){},j={trace:K,debug:K,log:K,warn:K,info:K,error:K};function W(){return $({},j)}function q(e,t,i){return t[e]?t[e].bind(t):function(e,t){const i=self.console[e];return i?i.bind(self.console,`${t?"["+t+"] ":""}[${e}] >`):K}(e,i)}const Y=W();const z=Y;function X(e=!0){if("undefined"==typeof self)return;return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Q(e,t){const i=Object.keys(e),s=Object.keys(t),r=i.length,n=s.length;return!r||!n||r===n&&!i.some(e=>-1===s.indexOf(e))}function J(e,t=!1){if("undefined"!=typeof TextDecoder){const i=new TextDecoder("utf-8").decode(e);if(t){const e=i.indexOf("\0");return-1!==e?i.substring(0,e):i}return i.replace(/\0/g,"")}const i=e.length;let s,r,n,a="",o=0;for(;o<i;){if(s=e[o++],0===s&&t)return a;if(0!==s&&3!==s)switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(s);break;case 12:case 13:r=e[o++],a+=String.fromCharCode((31&s)<<6|63&r);break;case 14:r=e[o++],n=e[o++],a+=String.fromCharCode((15&s)<<12|(63&r)<<6|63&n)}}return a}function Z(e){let t="";for(let i=0;i<e.length;i++){let s=e[i].toString(16);s.length<2&&(s="0"+s),t+=s}return t}function ee(e){return Uint8Array.from(e.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function te(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ie,se={exports:{}};var re=(ie||(ie=1,function(e){var t,i,s,r,n;t=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,s=/(?:\/|^)\.(?=\/)/g,r=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,n={buildAbsoluteURL:function(e,t,s){if(s=s||{},e=e.trim(),!(t=t.trim())){if(!s.alwaysNormalize)return e;var r=n.parseURL(e);if(!r)throw new Error("Error trying to parse base URL.");return r.path=n.normalizePath(r.path),n.buildURLFromParts(r)}var a=n.parseURL(t);if(!a)throw new Error("Error trying to parse relative URL.");if(a.scheme)return s.alwaysNormalize?(a.path=n.normalizePath(a.path),n.buildURLFromParts(a)):t;var o=n.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=i.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var d={scheme:o.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(d.netLoc=o.netLoc,"/"!==a.path[0]))if(a.path){var c=o.path,u=c.substring(0,c.lastIndexOf("/")+1)+a.path;d.path=n.normalizePath(u)}else d.path=o.path,a.params||(d.params=o.params,a.query||(d.query=o.query));return null===d.path&&(d.path=s.alwaysNormalize?n.normalizePath(a.path):a.path),n.buildURLFromParts(d)},parseURL:function(e){var i=t.exec(e);return i?{scheme:i[1]||"",netLoc:i[2]||"",path:i[3]||"",params:i[4]||"",query:i[5]||"",fragment:i[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(s,"");e.length!==(e=e.replace(r,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}},e.exports=n}(se)),se.exports);class ne{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var ae="audio",oe="video",le="audiovideo";class de{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof e&&(e={url:e}),this.base=e,function(e,t){const i=fe(e,t);i&&(i.enumerable=!0,Object.defineProperty(e,t,i))}(this,"stats")}setByteRange(e,t){const i=e.split("@",2);let s;s=1===i.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(i[1]),this._byteRange=[s,parseInt(i[0])+s]}get baseurl(){return this.base.url}get byteRange(){return null===this._byteRange?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return null===this._streams&&(this._streams={[ae]:null,[oe]:null,[le]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return null!==this._stats}get hasStreams(){return null!==this._streams}get stats(){return null===this._stats&&(this._stats=new ne),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=re.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[ae]=null,e[oe]=null,e[le]=null}}function ce(e){return"initSegment"!==e.sn}class ue extends de{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],t=this.byteRange[1];if(L(e)&&L(t))return t-e}return null}get bitrate(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(null==(e=this._decryptdata)||!e.keyId){const e=Object.keys(t);if(1===e.length){const i=this._decryptdata=t[e[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;const e=L(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){var t;const e=Object.keys(this.levelkeys),i=e.length;if(i>1||1===i&&null!=(t=this.levelkeys[e[0]])&&t.encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){L(e)?this._programDateTime=e:this._programDateTime=this.rawProgramDateTime=null}get ref(){return ce(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){const t=this.levelkeys;if(t){var i;const s=t[e];!s||null!=(i=this._decryptdata)&&i.keyId||(this._decryptdata=s.getDecryptData(this.sn,t))}}abortRequests(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()}setElementaryStreamInfo(e,t,i,s,r,n=!1){const{elementaryStreams:a}=this,o=a[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,i),o.startDTS=Math.min(o.startDTS,s),o.endDTS=Math.max(o.endDTS,r)):a[e]={startPTS:t,endPTS:i,startDTS:s,endDTS:r,partial:n}}}class he extends de{constructor(e,t,i,s,r){super(i),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=s;const n=e.enumeratedString("BYTERANGE");n&&this.setByteRange(n,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}function fe(e,t){const i=Object.getPrototypeOf(e);if(i){const e=Object.getOwnPropertyDescriptor(i,t);return e||fe(i,t)}}const ge=Math.pow(2,32)-1,pe=[].push,me={video:1,audio:2,id3:3,text:4};function ve(e){return String.fromCharCode.apply(null,e)}function ye(e,t){const i=e[t]<<8|e[t+1];return i<0?65536+i:i}function Te(e,t){const i=Se(e,t);return i<0?4294967296+i:i}function Ee(e,t){let i=Te(e,t);return i*=Math.pow(2,32),i+=Te(e,t+4),i}function Se(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function Ae(e,t){const i=[];if(!t.length)return i;const s=e.byteLength;for(let r=0;r<s;){const n=Te(e,r),a=n>1?r+n:s;if(ve(e.subarray(r+4,r+8))===t[0])if(1===t.length)i.push(e.subarray(r+8,a));else{const s=Ae(e.subarray(r+8,a),t.slice(1));s.length&&pe.apply(i,s)}r=a}return i}function be(e){const t=[],i=e[0];let s=8;const r=Te(e,s);s+=4;let n=0,a=0;0===i?(n=Te(e,s),a=Te(e,s+4),s+=8):(n=Ee(e,s),a=Ee(e,s+8),s+=16),s+=2;let o=e.length+a;const l=ye(e,s);s+=2;for(let i=0;i<l;i++){let i=s;const n=Te(e,i);i+=4;const a=2147483647&n;if(1===(2147483648&n)>>>31)return z.warn("SIDX has hierarchical references (not supported)"),null;const l=Te(e,i);i+=4,t.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/r,start:o,end:o+a-1}}),o+=a,i+=4,s=i}return{earliestPresentationTime:n,timescale:r,version:i,referencesCount:l,references:t}}function Le(e){const t=[],i=Ae(e,["moov","trak"]);for(let e=0;e<i.length;e++){const s=i[e],r=Ae(s,["tkhd"])[0];if(r){let e=r[0];const i=Te(r,0===e?12:20),n=Ae(s,["mdia","mdhd"])[0];if(n){e=n[0];const r=Te(n,0===e?12:20),a=Ae(s,["mdia","hdlr"])[0];if(a){const e=ve(a.subarray(8,12)),n={soun:ae,vide:oe}[e],o=Re(Ae(s,["mdia","minf","stbl","stsd"])[0]);n?(t[i]={timescale:r,type:n,stsd:o},t[n]=G({timescale:r,id:i},o)):t[i]={timescale:r,type:e,stsd:o}}}}}return Ae(e,["moov","mvex","trex"]).forEach(e=>{const i=Te(e,4),s=t[i];s&&(s.default={duration:Te(e,12),flags:Te(e,20)})}),t}function Re(e){const t=e.subarray(8),i=t.subarray(86),s=ve(t.subarray(4,8));let r,n=s;const a="enca"===s||"encv"===s;if(a){const e=Ae(t,[s])[0];Ae(e.subarray("enca"===s?28:78),["sinf"]).forEach(e=>{const t=Ae(e,["schm"])[0];if(t){const i=ve(t.subarray(4,8));if("cbcs"===i||"cenc"===i){const t=Ae(e,["frma"])[0];t&&(n=ve(t))}}})}const o=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const e=Ae(i,["avcC"])[0];e&&e.length>3&&(n+="."+we(e[1])+we(e[2])+we(e[3]),r=Ie("avc1"===o?"dva1":"dvav",i));break}case"mp4a":{const e=Ae(t,[s])[0],i=Ae(e.subarray(28),["esds"])[0];if(i&&i.length>7){let e=4;if(3!==i[e++])break;e=ke(i,e),e+=2;const t=i[e++];if(128&t&&(e+=2),64&t&&(e+=i[e++]),4!==i[e++])break;e=ke(i,e);const s=i[e++];if(64!==s)break;if(n+="."+we(s),e+=12,5!==i[e++])break;e=ke(i,e);const r=i[e++];let a=(248&r)>>3;31===a&&(a+=1+((7&r)<<3)+((224&i[e])>>5)),n+="."+a}break}case"hvc1":case"hev1":{const e=Ae(i,["hvcC"])[0];if(e&&e.length>12){const t=e[1],i=["","A","B","C"][t>>6],s=31&t,r=Te(e,2),a=(32&t)>>5?"H":"L",o=e[12],l=e.subarray(6,12);n+="."+i+s,n+="."+function(e){let t=0;for(let i=0;i<32;i++)t|=(e>>i&1)<<31-i;return t>>>0}(r).toString(16).toUpperCase(),n+="."+a+o;let d="";for(let e=l.length;e--;){const t=l[e];if(t||d){d="."+t.toString(16).toUpperCase()+d}}n+=d}r=Ie("hev1"==o?"dvhe":"dvh1",i);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":n=Ie(n,i)||n;break;case"vp09":{const e=Ae(i,["vpcC"])[0];if(e&&e.length>6){const t=e[4],i=e[5],s=e[6]>>4&15;n+="."+Pe(t)+"."+Pe(i)+"."+Pe(s)}break}case"av01":{const e=Ae(i,["av1C"])[0];if(e&&e.length>2){const t=e[1]>>>5,s=31&e[1],a=e[2]>>>7?"H":"M",o=(64&e[2])>>6,l=(32&e[2])>>5,d=2===t&&o?l?12:10:o?10:8,c=(16&e[2])>>4,u=(8&e[2])>>3,h=(4&e[2])>>2,f=3&e[2],g=1,p=1,m=1,v=0;n+="."+t+"."+Pe(s)+a+"."+Pe(d)+"."+c+"."+u+h+f+"."+Pe(g)+"."+Pe(p)+"."+Pe(m)+"."+v,r=Ie("dav1",i)}break}}return{codec:n,encrypted:a,supplemental:r}}function Ie(e,t){const i=Ae(t,["dvvC"]),s=i.length?i[0]:Ae(t,["dvcC"])[0];if(s){const t=s[2]>>1&127,i=s[2]<<5&32|s[3]>>3&31;return e+"."+Pe(t)+"."+Pe(i)}}function ke(e,t){const i=t+5;for(;128&e[t++]&&t<i;);return t}function we(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function Pe(e){return(e<10?"0":"")+e}function De(e,t){Ae(e,["moov","trak"]).forEach(e=>{const i=Ae(e,["mdia","minf","stbl","stsd"])[0];if(!i)return;const s=i.subarray(8);let r=Ae(s,["enca"]);const n=r.length>0;n||(r=Ae(s,["encv"])),r.forEach(e=>{Ae(n?e.subarray(28):e.subarray(78),["sinf"]).forEach(e=>{const i=xe(e);i&&t(i,n)})})})}function xe(e){const t=Ae(e,["schm"])[0];if(t){const i=ve(t.subarray(4,8));if("cbcs"===i||"cenc"===i){const t=Ae(e,["schi","tenc"])[0];if(t)return t}}}function Ce(e,t){const i=new Uint8Array(e.length+t.length);return i.set(e),i.set(t,e.length),i}function _e(e,t){const i=[],s=t.samples,r=t.timescale,n=t.id;let a=!1;return Ae(s,["moof"]).map(o=>{const l=o.byteOffset-8;Ae(o,["traf"]).map(o=>{const d=Ae(o,["tfdt"]).map(e=>{const t=e[0];let i=Te(e,4);return 1===t&&(i*=Math.pow(2,32),i+=Te(e,8)),i/r})[0];return void 0!==d&&(e=d),Ae(o,["tfhd"]).map(d=>{const c=Te(d,4),u=16777215&Te(d,0);let h=0;const f=!!(16&u);let g=0;const p=!!(32&u);let m=8;c===n&&(!!(1&u)&&(m+=8),!!(2&u)&&(m+=4),!!(8&u)&&(h=Te(d,m),m+=4),f&&(g=Te(d,m),m+=4),p&&(m+=4),"video"===t.type&&(a=Me(t.codec)),Ae(o,["trun"]).map(n=>{const o=n[0],d=16777215&Te(n,0),c=!!(1&d);let u=0;const f=!!(4&d),p=!!(256&d);let m=0;const v=!!(512&d);let y=0;const T=!!(1024&d),E=!!(2048&d);let S=0;const A=Te(n,4);let b=8;c&&(u=Te(n,b),b+=4),f&&(b+=4);let L=u+l;for(let l=0;l<A;l++){if(p?(m=Te(n,b),b+=4):m=h,v?(y=Te(n,b),b+=4):y=g,T&&(b+=4),E&&(S=0===o?Te(n,b):Se(n,b),b+=4),t.type===oe){let t=0;for(;t<y;){const n=Te(s,L);if(L+=4,Oe(a,s[L])){Fe(s.subarray(L,L+n),a?2:1,e+S/r,i)}L+=n,t+=n+4}}e+=m/r}}))})})}),i}function Me(e){if(!e)return!1;const t=e.substring(0,4);return"hvc1"===t||"hev1"===t||"dvh1"===t||"dvhe"===t}function Oe(e,t){if(e){const e=t>>1&63;return 39===e||40===e}return 6===(31&t)}function Fe(e,t,i,s){const r=Ue(e);let n=0;n+=t;let a=0,o=0,l=0;for(;n<r.length;){a=0;do{if(n>=r.length)break;l=r[n++],a+=l}while(255===l);o=0;do{if(n>=r.length)break;l=r[n++],o+=l}while(255===l);const e=r.length-n;let t=n;if(o<e)n+=o;else if(o>e){z.error(`Malformed SEI payload. ${o} is too small, only ${e} bytes left to parse.`);break}if(4===a){if(181===r[t++]){const e=ye(r,t);if(t+=2,49===e){const e=Te(r,t);if(t+=4,1195456820===e){const e=r[t++];if(3===e){const n=r[t++],o=64&n,l=o?2+3*(31&n):0,d=new Uint8Array(l);if(o){d[0]=n;for(let e=1;e<l;e++)d[e]=r[t++]}s.push({type:e,payloadType:a,pts:i,bytes:d})}}}}}else if(5===a&&o>16){const e=[];for(let i=0;i<16;i++){const s=r[t++].toString(16);e.push(1==s.length?"0"+s:s),3!==i&&5!==i&&7!==i&&9!==i||e.push("-")}const n=o-16,l=new Uint8Array(n);for(let e=0;e<n;e++)l[e]=r[t++];s.push({payloadType:a,pts:i,uuid:e.join(""),userData:J(l),userDataBytes:l})}}}function Ue(e){const t=e.byteLength,i=[];let s=1;for(;s<t-2;)0===e[s]&&0===e[s+1]&&3===e[s+2]?(i.push(s+2),s+=2):s++;if(0===i.length)return e;const r=t-i.length,n=new Uint8Array(r);let a=0;for(s=0;s<r;a++,s++)a===i[0]&&(a++,i.shift()),n[s]=e[a];return n}function Ne(e,t,i){if(16!==e.byteLength)throw new RangeError("Invalid system id");let s,r,n;s=0,r=new Uint8Array,n=new Uint8Array;const a=new Uint8Array(4);return i.byteLength>0&&new DataView(a.buffer).setUint32(0,i.byteLength,!1),function(e,...t){const i=t.length;let s=8,r=i;for(;r--;)s+=t[r].byteLength;const n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=255&s,n.set(e,4),r=0,s=8;r<i;r++)n.set(t[r],s),s+=t[r].byteLength;return n}([112,115,115,104],new Uint8Array([0,0,0,0]),e,n,r,a,i)}function Be(e){const t=e.getUint32(0),i=e.byteOffset,s=e.byteLength;if(s<t)return{offset:i,size:s};if(1886614376!==e.getUint32(4))return{offset:i,size:t};const r=e.getUint32(8)>>>24;if(0!==r&&1!==r)return{offset:i,size:t};const n=e.buffer,a=Z(new Uint8Array(n,i+12,16));let o=null,l=null,d=0;if(0===r)d=28;else{const r=e.getUint32(28);if(!r||s<32+16*r)return{offset:i,size:t};o=[];for(let e=0;e<r;e++)o.push(new Uint8Array(n,i+32+16*e,16));d=32+16*r}if(!d)return{offset:i,size:t};const c=e.getUint32(d);return t-32<c?{offset:i,size:t}:(l=new Uint8Array(n,i+d+4,c),{version:r,systemId:a,kids:o,data:l,offset:i,size:t})}const $e=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),Ve={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function Ge(e,t){const i=Ve[t];return!!i&&!!i[e.slice(0,4)]}function He(e,t,i=!0){return!e.split(",").some(e=>!Ke(e,t,i))}function Ke(e,t,i=!0){var s;const r=X(i);return null!=(s=null==r?void 0:r.isTypeSupported(je(e,t)))&&s}function je(e,t){return`${t}/mp4;codecs=${e}`}function We(e){if(e){const t=e.substring(0,4);return Ve.video[t]}return 2}function qe(e){const t=$e();return e.split(",").reduce((e,i)=>{const s=t&&Me(i)?9:Ve.video[i];return s?(2*s+e)/(e?3:2):(Ve.audio[i]+e)/(e?2:1)},0)}const Ye={};const ze=/flac|opus|mp4a\.40\.34/i;function Xe(e,t=!0){return e.replace(ze,e=>function(e,t=!0){if(Ye[e])return Ye[e];const i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e];for(let r=0;r<i.length;r++){var s;if(Ke(i[r],"audio",t))return Ye[e]=i[r],i[r];if("mp3"===i[r]&&null!=(s=X(t))&&s.isTypeSupported("audio/mpeg"))return""}return e}(e.toLowerCase(),t))}function Qe(e,t){if(e&&(e.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e))&&(Je(e,"audio")||Je(e,"video")))return e;if(t){const i=t.split(",");if(i.length>1){if(e)for(let t=i.length;t--;)if(i[t].substring(0,4)===e.substring(0,4))return i[t];return i[0]}}return t||e}function Je(e,t){return Ge(e,t)&&Ke(e,t)}function Ze(e){if(e.startsWith("av01.")){const t=e.split("."),i=["0","111","01","01","01","0"];for(let e=t.length;e>4&&e<10;e++)t[e]=i[e-4];return t.join(".")}return e}function et(e){const t=X(e)||{isTypeSupported:()=>!1};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}function tt(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const it={supported:!1,smooth:!1,powerEfficient:!1},st={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function rt(e,t){return{supported:!1,configurations:t,decodingInfoResults:[it],error:e}}function nt(e,t,i,s,r,n){const a=e.videoCodec,o=e.audioCodec?e.audioGroups:null,l=null==n?void 0:n.audioCodec,d=null==n?void 0:n.channels,c=d?parseInt(d):l?1/0:2;let u=null;if(null!=o&&o.length)try{u=1===o.length&&o[0]?t.groups[o[0]].channels:o.reduce((e,i)=>{if(i){const s=t.groups[i];if(!s)throw new Error(`Audio track group ${i} not found`);Object.keys(s.channels).forEach(t=>{e[t]=(e[t]||0)+s.channels[t]})}return e},{2:0})}catch(e){return!0}return void 0!==a&&(a.split(",").some(e=>Me(e))||e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(s,30)||"SDR"!==e.videoRange&&e.videoRange!==i||e.bitrate>Math.max(r,8e6))||!!u&&L(c)&&Object.keys(u).some(e=>parseInt(e)>c)}function at(e,t,i,s={}){const r=e.videoCodec;if(!r&&!e.audioCodec||!i)return Promise.resolve(st);const n=[],a=function(e){var t;const i=null==(t=e.videoCodec)?void 0:t.split(","),s=lt(e),r=e.width||640,n=e.height||480,a=e.frameRate||30,o=e.videoRange.toLowerCase();return i?i.map(e=>{const t={contentType:je(Ze(e),"video"),width:r,height:n,bitrate:s,framerate:a};return"sdr"!==o&&(t.transferFunction=o),t}):[]}(e),o=a.length,l=function(e,t,i){var s;const r=null==(s=e.audioCodec)?void 0:s.split(","),n=lt(e);if(r&&e.audioGroups)return e.audioGroups.reduce((e,s)=>{var a;const o=s?null==(a=t.groups[s])?void 0:a.tracks:null;return o?o.reduce((e,t)=>{if(t.groupId===s){const s=parseFloat(t.channels||"");r.forEach(t=>{const r={contentType:je(t,"audio"),bitrate:i?ot(t,n):n};s&&(r.channels=""+s),e.push(r)})}return e},e):e},[]);return[]}(e,t,o>0),d=l.length;for(let e=o||1*d||1;e--;){const t={type:"media-source"};if(o&&(t.video=a[e%o]),d){t.audio=l[e%d];const i=t.audio.bitrate;t.video&&i&&(t.video.bitrate-=i)}n.push(t)}if(r){const e=navigator.userAgent;if(r.split(",").some(e=>Me(e))&&$e())return Promise.resolve(rt(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${e})`),n))}return Promise.all(n.map(e=>{const t=function(e){let t="";const{audio:i,video:s}=e;if(s){t+=`${tt(s.contentType)}_r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${Math.ceil(s.bitrate/1e5)}`}if(i){t+=`${s?"_":""}${tt(i.contentType)}_c${i.channels}`}return t}(e);return s[t]||(s[t]=i.decodingInfo(e))})).then(e=>({supported:!e.some(e=>!e.supported),configurations:n,decodingInfoResults:e})).catch(e=>({supported:!1,configurations:n,decodingInfoResults:[],error:e}))}function ot(e,t){if(t<=1)return 1;let i=128e3;return"ec-3"===e?i=768e3:"ac-3"===e&&(i=64e4),Math.min(t/2,i)}function lt(e){return 1e3*Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)/1e3)||1}const dt=["NONE","TYPE-0","TYPE-1",null];const ct=["SDR","PQ","HLG"];var ut="",ht="YES",ft="v2";function gt(e){const{canSkipUntil:t,canSkipDateRanges:i,age:s}=e;return t&&s<t/2?i?ft:ht:ut}class pt{constructor(e,t,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=i}addDirectives(e){const t=new self.URL(e);return void 0!==this.msn&&t.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class mt{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(e=>!!e).map(e=>e.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const i=null==(t=e.supplemental)?void 0:t.videoCodec;i&&i!==e.videoCodec&&(this.codecSet+=`,${i.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return vt(this._audioGroups,e)}hasSubtitleGroup(e){return vt(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t)if("audio"===e){let e=this._audioGroups;e||(e=this._audioGroups=[]),-1===e.indexOf(t)&&e.push(t)}else if("text"===e){let e=this._subtitleGroups;e||(e=this._subtitleGroups=[]),-1===e.indexOf(t)&&e.push(t)}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return null==(e=this.audioGroups)?void 0:e[0]}get textGroupId(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}addFallback(){}}function vt(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}function yt(e,t){let i=!1,s=[];if(e&&(i="SDR"!==e,s=[e]),t){s=t.allowedVideoRanges||ct.slice(0);const e="SDR"!==s.join("")&&!t.videoCodec;i=void 0!==t.preferHDR?t.preferHDR:e&&function(){if("function"==typeof matchMedia){const e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}(),i||(s=["SDR"])}return{preferHDR:i,allowedVideoRanges:s}}const Tt=(e,t)=>JSON.stringify(e,(e=>{const t=new WeakSet;return(i,s)=>{if(e&&(s=e(i,s)),"object"==typeof s&&null!==s){if(t.has(s))return;t.add(s)}return s}})(t));function Et(e,t){z.log(`[abr] start candidates with "${e}" ignored because ${t}`)}function St(e){return e.reduce((e,t)=>{let i=e.groups[t.groupId];i||(i=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(t);const s=t.channels||"2";return i.channels[s]=(i.channels[s]||0)+1,i.hasDefault=i.hasDefault||t.default,i.hasAutoSelect=i.hasAutoSelect||t.autoselect,i.hasDefault&&(e.hasDefaultAudio=!0),i.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function At(e){if(!e)return e;const{lang:t,assocLang:i,characteristics:s,channels:r,audioCodec:n}=e;return{lang:t,assocLang:i,characteristics:s,channels:r,audioCodec:n}}function bt(e,t,i){if("attrs"in e){const i=t.indexOf(e);if(-1!==i)return i}for(let s=0;s<t.length;s++){if(Lt(e,t[s],i))return s}return-1}function Lt(e,t,i){const{groupId:s,name:r,lang:n,assocLang:a,default:o}=e,l=e.forced;return(void 0===s||t.groupId===s)&&(void 0===r||t.name===r)&&(void 0===n||function(e,t="--"){if(e.length===t.length)return e===t;return e.startsWith(t)||t.startsWith(e)}(n,t.lang))&&(void 0===n||t.assocLang===a)&&(void 0===o||t.default===o)&&(void 0===l||t.forced===l)&&(!("characteristics"in e)||function(e,t=""){const i=e.split(","),s=t.split(",");return i.length===s.length&&!i.some(e=>-1===s.indexOf(e))}(e.characteristics||"",t.characteristics))&&(void 0===i||i(e,t))}function Rt(e,t){const{audioCodec:i,channels:s}=e;return!(void 0!==i&&(t.audioCodec||"").substring(0,4)!==i.substring(0,4)||void 0!==s&&s!==(t.channels||"2"))}function It(e,t,i){for(let s=t;s>-1;s--)if(i(e[s]))return s;for(let s=t+1;s<e.length;s++)if(i(e[s]))return s;return-1}function kt(e,t){var i;return!!e&&e!==(null==(i=t.loadLevelObj)?void 0:i.uri)}const wt=function(e,t){let i=0,s=e.length-1,r=null,n=null;for(;i<=s;){r=(i+s)/2|0,n=e[r];const a=t(n);if(a>0)i=r+1;else{if(!(a<0))return n;s=r-1}}return null};function Pt(e,t,i=0,s=0,r=.005){let n=null;if(e){n=t[1+e.sn-t[0].sn]||null;const s=e.endDTS-i;s>0&&s<15e-7&&(i+=15e-7),n&&e.level!==n.level&&n.end<=e.end&&(n=t[2+e.sn-t[0].sn]||null)}else 0===i&&0===t[0].start&&(n=t[0]);if(n&&((!e||e.level===n.level)&&0===Dt(i,s,n)||function(e,t,i){if(t&&0===t.start&&t.level<e.level&&(t.endPTS||0)>0){const s=t.tagList.reduce((e,t)=>("INF"===t[0]&&(e+=parseFloat(t[1])),e),i);return e.start<=s}return!1}(n,e,Math.min(r,s))))return n;const a=wt(t,Dt.bind(null,i,s));return!a||a===e&&n?n:a}function Dt(e=0,t=0,i){if(i.start<=e&&i.start+i.duration>e)return 0;const s=Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-s<=e?1:i.start-s>e&&i.start?-1:0}function xt(e,t,i){const s=1e3*Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return(i.endProgramDateTime||0)-s>e}function Ct(e,t,i){if(e&&e.startCC<=t&&e.endCC>=t){let s=e.fragments;const{fragmentHint:r}=e;let n;return r&&(s=s.concat(r)),wt(s,e=>e.cc<t?1:e.cc>t?-1:(n=e,e.end<=i?1:e.start>i?-1:0)),n||null}return null}function _t(e){switch(e.details){case w.FRAG_LOAD_TIMEOUT:case w.KEY_LOAD_TIMEOUT:case w.LEVEL_LOAD_TIMEOUT:case w.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Mt(e){return e.details.startsWith("key")}function Ot(e){return Mt(e)&&!!e.frag&&!e.frag.decryptdata}function Ft(e,t){const i=_t(t);return e.default[(i?"timeout":"error")+"Retry"]}function Ut(e,t){const i="linear"===e.backoff?1:Math.pow(2,t);return Math.min(i*e.retryDelayMs,e.maxRetryDelayMs)}function Nt(e){return G(G({},e),{errorRetry:null,timeoutRetry:null})}function Bt(e,t,i,s){if(!e)return!1;const r=null==s?void 0:s.code,n=t<e.maxNumRetry&&(function(e){return $t(e)||!!e&&(e<400||e>499)}(r)||!!i);return e.shouldRetry?e.shouldRetry(e,t,i,s,n):n}function $t(e){return 0===e&&!1===navigator.onLine}var Vt=0,Gt=2,Ht=3,Kt=5,jt=0,Wt=1,qt=2,Yt=4;function zt(e){const t={action:Vt,flags:jt};return e&&(t.resolved=!0),t}var Xt="NOT_LOADED",Qt="APPENDING",Jt="PARTIAL",Zt="OK";class ei{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e&&(e.on(P.MANIFEST_LOADING,this.onManifestLoading,this),e.on(P.BUFFER_APPENDED,this.onBufferAppended,this),e.on(P.FRAG_BUFFERED,this.onFragBuffered,this),e.on(P.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(P.MANIFEST_LOADING,this.onManifestLoading,this),e.off(P.BUFFER_APPENDED,this.onBufferAppended,this),e.off(P.FRAG_BUFFERED,this.onFragBuffered,this),e.off(P.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const i=this.activePartLists[t];if(i)for(let t=i.length;t--;){const s=i[t];if(!s)break;if(s.start<=e&&e<=s.end&&s.loaded)return s}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,i){const{fragments:s}=this,r=Object.keys(s);for(let n=r.length;n--;){const a=s[r[n]];if((null==a?void 0:a.body.type)===t&&(!i||a.buffered)){const t=a.body;if(t.start<=e&&e<=t.end)return t}}return null}detectEvictedFragments(e,t,i,s,r){this.timeRanges&&(this.timeRanges[e]=t);const n=(null==s?void 0:s.fragment.sn)||-1;Object.keys(this.fragments).forEach(s=>{const a=this.fragments[s];if(!a)return;if(n>=a.body.sn)return;if(!a.buffered&&(!a.loaded||r))return void(a.body.type===i&&this.removeFragment(a.body));const o=a.range[e];o&&(0!==o.time.length?o.time.some(e=>{const i=!this.isTimeBuffered(e.startPTS,e.endPTS,t);return i&&this.removeFragment(a.body),i}):this.removeFragment(a.body))})}detectPartialFragments(e){const t=this.timeRanges;if(!t||"initSegment"===e.frag.sn)return;const i=e.frag,s=ii(i),r=this.fragments[s];if(!r||r.buffered&&i.gap)return;const n=!i.relurl;if(Object.keys(t).forEach(s=>{const a=i.elementaryStreams[s];if(!a)return;const o=t[s],l=n||!0===a.partial;r.range[s]=this.getBufferedTimes(i,e.part,l,o)}),r.loaded=null,Object.keys(r.range).length){r.buffered=!0;(r.body.endList=i.endList||r.body.endList)&&(this.endListFragments[r.body.type]=r),ti(r)||this.removeParts(i.sn-1,i.type)}else this.removeFragment(r.body)}removeParts(e,t){const i=this.activePartLists[t];i&&(this.activePartLists[t]=si(i,t=>t.fragment.sn>=e))}fragBuffered(e,t){const i=ii(e);let s=this.fragments[i];!s&&t&&(s=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),s&&(s.loaded=null,s.buffered=!0)}getBufferedTimes(e,t,i,s){const r={time:[],partial:i},n=e.start,a=e.end,o=e.minEndPTS||a,l=e.maxStartPTS||n;for(let e=0;e<s.length;e++){const t=s.start(e)-this.bufferPadding,i=s.end(e)+this.bufferPadding;if(l>=t&&o<=i){r.time.push({startPTS:Math.max(n,s.start(e)),endPTS:Math.min(a,s.end(e))});break}if(n<i&&a>t){const t=Math.max(n,s.start(e)),i=Math.min(a,s.end(e));i>t&&(r.partial=!0,r.time.push({startPTS:t,endPTS:i}))}else if(a<=t)break}return r}getPartialFragment(e){let t,i,s,r=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach(l=>{const d=o[l];d&&ti(d)&&(i=d.body.start-a,s=d.body.end+a,e>=i&&e<=s&&(t=Math.min(e-i,s-e),n<=t&&(r=d.body,n=t)))}),r}isEndListAppended(e){const t=this.endListFragments[e];return void 0!==t&&(t.buffered||ti(t))}getState(e){const t=ii(e),i=this.fragments[t];return i?i.buffered?ti(i)?Jt:Zt:Qt:Xt}isTimeBuffered(e,t,i){let s,r;for(let n=0;n<i.length;n++){if(s=i.start(n)-this.bufferPadding,r=i.end(n)+this.bufferPadding,e>=s&&t<=r)return!0;if(t<=s)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if("initSegment"===t.frag.sn||t.frag.bitrateTest)return;const i=t.frag,s=t.part?null:t,r=ii(i);this.fragments[r]={body:i,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:i,part:s,timeRanges:r,type:n}=t;if("initSegment"===i.sn)return;const a=i.type;if(s){let e=this.activePartLists[a];e||(this.activePartLists[a]=e=[]),e.push(s)}this.timeRanges=r;const o=r[n];this.detectEvictedFragments(n,o,a,s)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=ii(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,i=Object.keys(t);if(!e)return i.length>0;for(let s=i.length;s--;){const r=t[i[s]];if((null==r?void 0:r.body.type)===e)return!0}return!1}hasParts(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)}removeFragmentsInRange(e,t,i,s,r){s&&!this.hasGaps||Object.keys(this.fragments).forEach(n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==i||s&&!o.gap||o.start<t&&o.end>e&&(a.buffered||r)&&this.removeFragment(o)})}removeFragment(e){const t=ii(e);e.clearElementaryStreamInfo();const i=this.activePartLists[e.type];if(i){const t=e.sn;this.activePartLists[e.type]=si(i,e=>e.fragment.sn!==t)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const t=null==(e=this.hls)||null==(e=e.latestLevelDetails)?void 0:e.partList;t&&t.forEach(e=>e.clearElementaryStreamInfo())}}function ti(e){var t,i,s;return e.buffered&&!!(e.body.gap||null!=(t=e.range.video)&&t.partial||null!=(i=e.range.audio)&&i.partial||null!=(s=e.range.audiovideo)&&s.partial)}function ii(e){return`${e.type}_${e.level}_${e.sn}`}function si(e,t){return e.filter(e=>{const i=t(e);return i||e.clearElementaryStreamInfo(),i})}var ri=0,ni=1;class ai{constructor(e,t,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=i}decrypt(e,t){switch(this.aesMode){case ri:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case ni:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}class oi{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),i=new Uint32Array(4);for(let e=0;e<4;e++)i[e]=t.getUint32(4*e);return i}initTable(){const e=this.sBox,t=this.invSBox,i=this.subMix,s=i[0],r=i[1],n=i[2],a=i[3],o=this.invSubMix,l=o[0],d=o[1],c=o[2],u=o[3],h=new Uint32Array(256);let f=0,g=0,p=0;for(p=0;p<256;p++)h[p]=p<128?p<<1:p<<1^283;for(p=0;p<256;p++){let i=g^g<<1^g<<2^g<<3^g<<4;i=i>>>8^255&i^99,e[f]=i,t[i]=f;const o=h[f],p=h[o],m=h[p];let v=257*h[i]^16843008*i;s[f]=v<<24|v>>>8,r[f]=v<<16|v>>>16,n[f]=v<<8|v>>>24,a[f]=v,v=16843009*m^65537*p^257*o^16843008*f,l[i]=v<<24|v>>>8,d[i]=v<<16|v>>>16,c[i]=v<<8|v>>>24,u[i]=v,f?(f=o^h[h[h[m^o]]],g^=h[h[g]]):f=g=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let i=!0,s=0;for(;s<t.length&&i;)i=t[s]===this.key[s],s++;if(i)return;this.key=t;const r=this.keySize=t.length;if(4!==r&&6!==r&&8!==r)throw new Error("Invalid aes key size="+r);const n=this.ksRows=4*(r+6+1);let a,o;const l=this.keySchedule=new Uint32Array(n),d=this.invKeySchedule=new Uint32Array(n),c=this.sBox,u=this.rcon,h=this.invSubMix,f=h[0],g=h[1],p=h[2],m=h[3];let v,y;for(a=0;a<n;a++)a<r?v=l[a]=t[a]:(y=v,a%r===0?(y=y<<8|y>>>24,y=c[y>>>24]<<24|c[y>>>16&255]<<16|c[y>>>8&255]<<8|c[255&y],y^=u[a/r|0]<<24):r>6&&a%r===4&&(y=c[y>>>24]<<24|c[y>>>16&255]<<16|c[y>>>8&255]<<8|c[255&y]),l[a]=v=(l[a-r]^y)>>>0);for(o=0;o<n;o++)a=n-o,y=3&o?l[a]:l[a-4],d[o]=o<4||a<=4?y:f[c[y>>>24]]^g[c[y>>>16&255]]^p[c[y>>>8&255]]^m[c[255&y]],d[o]=d[o]>>>0}networkToHostOrderSwap(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24}decrypt(e,t,i){const s=this.keySize+6,r=this.invKeySchedule,n=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],d=a[2],c=a[3],u=this.uint8ArrayToUint32Array_(i);let h=u[0],f=u[1],g=u[2],p=u[3];const m=new Int32Array(e),v=new Int32Array(m.length);let y,T,E,S,A,b,L,R,I,k,w,P,D,x;const C=this.networkToHostOrderSwap;for(;t<m.length;){for(I=C(m[t]),k=C(m[t+1]),w=C(m[t+2]),P=C(m[t+3]),A=I^r[0],b=P^r[1],L=w^r[2],R=k^r[3],D=4,x=1;x<s;x++)y=o[A>>>24]^l[b>>16&255]^d[L>>8&255]^c[255&R]^r[D],T=o[b>>>24]^l[L>>16&255]^d[R>>8&255]^c[255&A]^r[D+1],E=o[L>>>24]^l[R>>16&255]^d[A>>8&255]^c[255&b]^r[D+2],S=o[R>>>24]^l[A>>16&255]^d[b>>8&255]^c[255&L]^r[D+3],A=y,b=T,L=E,R=S,D+=4;y=n[A>>>24]<<24^n[b>>16&255]<<16^n[L>>8&255]<<8^n[255&R]^r[D],T=n[b>>>24]<<24^n[L>>16&255]<<16^n[R>>8&255]<<8^n[255&A]^r[D+1],E=n[L>>>24]<<24^n[R>>16&255]<<16^n[A>>8&255]<<8^n[255&b]^r[D+2],S=n[R>>>24]<<24^n[A>>16&255]<<16^n[b>>8&255]<<8^n[255&L]^r[D+3],v[t]=C(y^h),v[t+1]=C(S^f),v[t+2]=C(E^g),v[t+3]=C(T^p),h=I,f=k,g=w,p=P,t+=4}return v.buffer}}class li{constructor(e,t,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=i}expandKey(){const e=function(e){switch(e){case ri:return"AES-CBC";case ni:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${e}`)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}class di{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const e=self.crypto;e&&(this.subtle=e.subtle||e.webkitSubtle)}catch(e){}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const i=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?function(e){const t=e.byteLength,i=t&&new DataView(e.buffer).getUint8(t-1);return i?e.slice(0,t-i):e}(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,i,s){return this.useSoftware?new Promise((r,n)=>{const a=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(a,t,i,s);const o=this.flush();o?r(o.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i,s)}softwareDecrypt(e,t,i,s){const{currentIV:r,currentResult:n,remainderData:a}=this;if(s!==ri||16!==t.byteLength)return z.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(e=Ce(a,e),this.remainderData=null);const o=this.getValidChunk(e);if(!o.length)return null;r&&(i=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new oi),l.expandKey(t);const d=n;return this.currentResult=l.decrypt(o.buffer,0,i),this.currentIV=o.slice(-16).buffer,d||null}webCryptoDecrypt(e,t,i,s){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,s));this.key=t,this.fastAesKey=new li(this.subtle,t,s)}return this.fastAesKey.expandKey().then(t=>{if(!this.subtle)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new ai(this.subtle,new Uint8Array(i),s).decrypt(e.buffer,t)}).catch(r=>(z.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,i,s)))}onWebCryptoError(e,t,i,s){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i,s);const r=this.flush();if(r)return r.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const i=e.length-e.length%16;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}logOnce(e){this.logEnabled&&(z.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const ci=Math.pow(2,17);class ui{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const i=e.url;if(!i)return Promise.reject(new gi({type:k.NETWORK_ERROR,details:w.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a "+(i?"part list":"url")),networkDetails:null}));this.abort();const s=this.config,r=s.fLoader,n=s.loader;return new Promise((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap){if(e.tagList.some(e=>"GAP"===e[0]))return void o(fi(e));e.gap=!1}const l=this.loader=r?new r(s):new n(s),d=hi(e);e.loader=l;const c=Nt(s.fragLoadPolicy.default),u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:ci};e.stats=l.stats;const h={onSuccess:(t,i,s,r)=>{this.resetLoader(e,l);let n=t.data;s.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),a({frag:e,part:null,payload:n,networkDetails:r})},onError:(t,s,r,n)=>{this.resetLoader(e,l),o(new gi({type:k.NETWORK_ERROR,details:w.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:G({url:i,data:void 0},t),error:new Error(`HTTP Error ${t.code} ${t.text}`),networkDetails:r,stats:n}))},onAbort:(t,i,s)=>{this.resetLoader(e,l),o(new gi({type:k.NETWORK_ERROR,details:w.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:s,stats:t}))},onTimeout:(t,i,s)=>{this.resetLoader(e,l),o(new gi({type:k.NETWORK_ERROR,details:w.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:s,stats:t}))}};t&&(h.onProgress=(i,s,r,n)=>t({frag:e,part:null,payload:r,networkDetails:n})),l.load(d,u,h)})}loadPart(e,t,i){this.abort();const s=this.config,r=s.fLoader,n=s.loader;return new Promise((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap)return void o(fi(e,t));const l=this.loader=r?new r(s):new n(s),d=hi(e,t);e.loader=l;const c=Nt(s.fragLoadPolicy.default),u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:ci};t.stats=l.stats,l.load(d,u,{onSuccess:(s,r,n,o)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const d={frag:e,part:t,payload:s.data,networkDetails:o};i(d),a(d)},onError:(i,s,r,n)=>{this.resetLoader(e,l),o(new gi({type:k.NETWORK_ERROR,details:w.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:G({url:d.url,data:void 0},i),error:new Error(`HTTP Error ${i.code} ${i.text}`),networkDetails:r,stats:n}))},onAbort:(i,s,r)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),o(new gi({type:k.NETWORK_ERROR,details:w.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:r,stats:i}))},onTimeout:(i,s,r)=>{this.resetLoader(e,l),o(new gi({type:k.NETWORK_ERROR,details:w.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:r,stats:i}))}})})}updateStatsFromPart(e,t){const i=e.stats,s=t.stats,r=s.total;if(i.loaded+=s.loaded,r){const s=Math.round(e.duration/t.duration),n=Math.min(Math.round(i.loaded/r),s),a=(s-n)*Math.round(i.loaded/n);i.total=i.loaded+a}else i.total=Math.max(i.loaded,i.total);const n=i.loading,a=s.loading;n.start?n.first+=a.first-a.start:(n.start=a.start,n.first=a.first),n.end=a.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function hi(e,t=null){const i=t||e,s={frag:e,part:t,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},r=i.byteRangeStartOffset,n=i.byteRangeEndOffset;if(L(r)&&L(n)){var a;let t=r,i=n;if("initSegment"===e.sn&&("AES-128"===(o=null==(a=e.decryptdata)?void 0:a.method)||"AES-256"===o)){const e=n-r;e%16&&(i=n+(16-e%16)),0!==r&&(s.resetIV=!0,t=r-16)}s.rangeStart=t,s.rangeEnd=i}var o;return s}function fi(e,t){const i=new Error(`GAP ${e.gap?"tag":"attribute"} found`),s={type:k.MEDIA_ERROR,details:w.FRAG_GAP,fatal:!1,frag:e,error:i,networkDetails:null};return t&&(s.part=t),(t||e).stats.aborted=!0,new gi(s)}class gi extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class pi extends H{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class mi{constructor(e,t,i,s=0,r=-1,n=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=e,this.sn=t,this.id=i,this.size=s,this.part=r,this.partial=n}}const vi={length:0,start:()=>0,end:()=>0};class yi{static isBuffered(e,t){if(e){const i=yi.getBuffered(e);for(let e=i.length;e--;)if(t>=i.start(e)&&t<=i.end(e))return!0}return!1}static bufferedRanges(e){if(e){const t=yi.getBuffered(e);return yi.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let i=0;i<e.length;i++)t.push({start:e.start(i),end:e.end(i)});return t}static bufferInfo(e,t,i){if(e){const s=yi.bufferedRanges(e);if(s.length)return yi.bufferedInfo(s,t,i)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,i){t=Math.max(0,t),e.length>1&&e.sort((e,t)=>e.start-t.start||t.end-e.end);let s=-1,r=[];if(i)for(let n=0;n<e.length;n++){t>=e[n].start&&t<=e[n].end&&(s=n);const a=r.length;if(a){const t=r[a-1].end;e[n].start-t<i?e[n].end>t&&(r[a-1].end=e[n].end):r.push(e[n])}else r.push(e[n])}else r=e;let n,a=0,o=t,l=t;for(let e=0;e<r.length;e++){const d=r[e].start,c=r[e].end;if(-1===s&&t>=d&&t<=c&&(s=e),t+i>=d&&t<c)o=d,l=c,a=l-t;else if(t+i<d){n=d;break}}return{len:a,start:o||0,end:l||0,nextStart:n,buffered:e,bufferedIndex:s}}static getBuffered(e){try{return e.buffered||vi}catch(e){return z.log("failed to get media.buffered",e),vi}}}const Ti=/\{\$([a-zA-Z0-9-_]+)\}/g;function Ei(e){return Ti.test(e)}function Si(e,t){if(null!==e.variableList||e.hasVariableRefs){const i=e.variableList;return t.replace(Ti,t=>{const s=t.substring(2,t.length-1),r=null==i?void 0:i[s];return void 0===r?(e.playlistParsingError||(e.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${s}"`)),t):r})}return t}function Ai(e,t,i){let s,r,n=e.variableList;if(n||(e.variableList=n={}),"QUERYPARAM"in t){s=t.QUERYPARAM;try{const e=new self.URL(i).searchParams;if(!e.has(s))throw new Error(`"${s}" does not match any query parameter in URI: "${i}"`);r=e.get(s)}catch(t){e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${t.message}`))}}else s=t.NAME,r=t.VALUE;s in n?e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${s}"`)):n[s]=r||""}function bi(e,t,i){const s=t.IMPORT;if(i&&s in i){let t=e.variableList;t||(e.variableList=t={}),t[s]=i[s]}else e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}const Li=/^(\d+)x(\d+)$/,Ri=/(.+?)=(".*?"|.*?)(?:,|$)/g;class Ii{constructor(e,t){"string"==typeof e&&(e=Ii.parseAttrList(e,t)),$(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>"X-"===e.substring(0,2))}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;const i=new Uint8Array(t.length/2);for(let e=0;e<t.length/2;e++)i[e]=parseInt(t.slice(2*e,2*e+2),16);return i}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const i=this[e];return(i?i.split(/[ ,]+/):[]).reduce((e,t)=>(e[t.toLowerCase()]=!0,e),t)}bool(e){return"YES"===this[e]}decimalResolution(e){const t=Li.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let i;const s={};for(Ri.lastIndex=0;null!==(i=Ri.exec(e));){const r=i[1].trim();let n=i[2];const a=0===n.indexOf('"')&&n.lastIndexOf('"')===n.length-1;let o=!1;if(a)n=n.slice(1,-1);else switch(r){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(t&&(a||o))n=Si(t,n);else if(!o&&!a)switch(r){case"CLOSED-CAPTIONS":if("NONE"===n)break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":z.warn(`${e}: attribute ${r} is missing quotes`)}s[r]=n}return s}}function ki(e){return"ID"!==e&&"CLASS"!==e&&"CUE"!==e&&"START-DATE"!==e&&"DURATION"!==e&&"END-DATE"!==e&&"END-ON-NEXT"!==e}function wi(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e||"SCTE35-CMD"===e}class Pi{constructor(e,t,i=0){var s;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==t?void 0:t.tagAnchor)||null,this.tagOrder=null!=(s=null==t?void 0:t.tagOrder)?s:i,t){const i=t.attr;for(const t in i)if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==i[t]){z.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=$(new Ii({}),i,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const e=(null==t?void 0:t.endDate)||new Date(this.attr["END-DATE"]);L(e.getTime())&&(this._endDate=e)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return void 0===e?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return null===e||null===e.programDateTime?(z.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return null!==t?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*t):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(L(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return"com.apple.hls.interstitial"===this.class}get isValid(){return!!this.id&&!this._badValueForSameId&&L(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}class Di{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e)return this.advanced=!0,void(this.updated=!0);const t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&i>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let i=t.decryptdata;return i||(t.setKeyFormat(e.keyFormat),i=t.decryptdata),!!i&&e.matches(i)})}get hasProgramDateTime(){return!!this.fragments.length&&L(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const e=this.driftEndTime-this.driftStartTime;if(e>0){return 1e3*(this.driftEnd-this.driftStart)/e}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(-1!==t){for(let i=e.length;i--;)if(e[i].index>t)return e[i].index;return t}}return 0}get lastPartSn(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function xi(e,t){return e.length===t.length&&!e.some((e,i)=>e!==t[i])}function Ci(e,t){return!e&&!t||!(!e||!t)&&xi(e,t)}function _i(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function Mi(e){switch(e){case"AES-128":case"AES-256":return ri;case"AES-256-CTR":return ni;default:throw new Error(`invalid full segment method ${e}`)}}function Oi(e){return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}function Fi(e){return Uint8Array.from(unescape(encodeURIComponent(e)),e=>e.charCodeAt(0))}function Ui(e){const t=function(e,t,i){const s=e[t];e[t]=e[i],e[i]=s};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function Ni(e){const t=e.split(":");let i=null;if("data"===t[0]&&2===t.length){const e=t[1].split(";"),s=e[e.length-1].split(",");if(2===s.length){const t="base64"===s[0],r=s[1];t?(e.splice(-1,1),i=Oi(r)):i=function(e){const t=Fi(e).subarray(0,16),i=new Uint8Array(16);return i.set(t,16-t.length),i}(r)}}return i}const Bi="undefined"!=typeof self?self:void 0;var $i={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Vi="org.w3.clearkey",Gi="com.apple.streamingkeydelivery",Hi="com.microsoft.playready",Ki="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function ji(e){switch(e){case Gi:return $i.FAIRPLAY;case Hi:return $i.PLAYREADY;case Ki:return $i.WIDEVINE;case Vi:return $i.CLEARKEY}}function Wi(e){switch(e){case $i.FAIRPLAY:return Gi;case $i.PLAYREADY:return Hi;case $i.WIDEVINE:return Ki;case $i.CLEARKEY:return Vi}}function qi(e){const{drmSystems:t,widevineLicenseUrl:i}=e,s=t?[$i.FAIRPLAY,$i.WIDEVINE,$i.PLAYREADY,$i.CLEARKEY].filter(e=>!!t[e]):[];return!s[$i.WIDEVINE]&&i&&s.push($i.WIDEVINE),s}const Yi=null!=Bi&&null!=(zi=Bi.navigator)&&zi.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var zi;function Xi(e){const t=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),i=String.fromCharCode.apply(null,Array.from(t)),s=i.substring(i.indexOf("<"),i.length),r=(new DOMParser).parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(r){const e=r.childNodes[0]?r.childNodes[0].nodeValue:r.getAttribute("VALUE");if(e){const t=Oi(e).subarray(0,16);return Ui(t),t}}return null}let Qi={};class Ji{static clearKeyUriToKeyIdMap(){Qi={}}static setKeyIdForUri(e,t){Qi[e]=t}constructor(e,t,i,s=[1],r=null,n){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=i,this.keyFormatVersions=s,this.iv=r,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&!_i(e),null!=n&&n.startsWith("0x")&&(this.keyId=new Uint8Array(ee(n)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&xi(e.keyFormatVersions,this.keyFormatVersions)&&Ci(e.iv,this.iv)&&Ci(e.keyId,this.keyId)}isSupported(){if(this.method){if(_i(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case Gi:case Ki:case Hi:case Vi:return-1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(_i(this.method)){let t=this.iv;t||("number"!=typeof e&&(z.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),t=function(e){const t=new Uint8Array(16);for(let i=12;i<16;i++)t[i]=e>>8*(15-i)&255;return t}(e));return new Ji(this.method,this.uri,"identity",this.keyFormatVersions,t)}if(this.keyId){const e=Qi[this.uri];if(e&&!xi(this.keyId,e)&&Ji.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const i=Ni(this.uri);if(i)switch(this.keyFormat){case Ki:if(this.pssh=i,!this.keyId){const e=function(e){const t=[];if(e instanceof ArrayBuffer){const i=e.byteLength;let s=0;for(;s+32<i;){const i=Be(new DataView(e,s));t.push(i),s+=i.size}}return t}(i.buffer);if(e.length){var s;const t=e[0];this.keyId=null!=(s=t.kids)&&s.length?t.kids[0]:null}}this.keyId||(this.keyId=Zi(t));break;case Hi:{const e=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Ne(e,0,i),this.keyId=Xi(i);break}default:{let e=i.subarray(0,16);if(16!==e.length){const t=new Uint8Array(16);t.set(e,16-e.length),e=t}this.keyId=e;break}}if(!this.keyId||16!==this.keyId.byteLength){let e;e=function(e){const t=null==e?void 0:e[Ki];if(t)return t.keyId;return null}(t),e||(e=Zi(t),e||(e=Qi[this.uri])),e&&(this.keyId=e,Ji.setKeyIdForUri(this.uri,e))}return this}}function Zi(e){const t=null==e?void 0:e[Hi];if(t){const e=Ni(t.uri);if(e)return Xi(e)}return null}const es=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,ts=/#EXT-X-MEDIA:(.*)/g,is=/^#EXT(?:INF|-X-TARGETDURATION):/m,ss=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),rs=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class ns{static findGroup(e,t){for(let i=0;i<e.length;i++){const s=e[i];if(s.id===t)return s}}static resolve(e,t){return re.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return is.test(e)}static parseMasterPlaylist(e,t){const i={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:Ei(e)},s=[];if(es.lastIndex=0,!e.startsWith("#EXTM3U"))return i.playlistParsingError=new Error("no EXTM3U delimiter"),i;let r;for(;null!=(r=es.exec(e));)if(r[1]){var n;const e=new Ii(r[1],i),a=Si(i,r[2]),o={attrs:e,bitrate:e.decimalInteger("BANDWIDTH")||e.decimalInteger("AVERAGE-BANDWIDTH"),name:e.NAME,url:ns.resolve(a,t)},l=e.decimalResolution("RESOLUTION");l&&(o.width=l.width,o.height=l.height),cs(e.CODECS,o);const d=e["SUPPLEMENTAL-CODECS"];d&&(o.supplemental={},cs(d,o.supplemental)),null!=(n=o.unknownCodecs)&&n.length||s.push(o),i.levels.push(o)}else if(r[3]){const e=r[3],s=r[4];switch(e){case"SESSION-DATA":{const e=new Ii(s,i),t=e["DATA-ID"];t&&(null===i.sessionData&&(i.sessionData={}),i.sessionData[t]=e);break}case"SESSION-KEY":{const e=ls(s,t,i);e.encrypted&&e.isSupported()?(null===i.sessionKeys&&(i.sessionKeys=[]),i.sessionKeys.push(e)):z.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${s}"`);break}case"DEFINE":Ai(i,new Ii(s,i),t);break;case"CONTENT-STEERING":{const e=new Ii(s,i);i.contentSteering={uri:ns.resolve(e["SERVER-URI"],t),pathwayId:e["PATHWAY-ID"]||"."};break}case"START":i.startTimeOffset=ds(s)}}const a=s.length>0&&s.length<i.levels.length;return i.levels=a?s:i.levels,0===i.levels.length&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(e,t,i){let s;const r={},n=i.levels,a={AUDIO:n.map(e=>({id:e.attrs.AUDIO,audioCodec:e.audioCodec})),SUBTITLES:n.map(e=>({id:e.attrs.SUBTITLES,textCodec:e.textCodec})),"CLOSED-CAPTIONS":[]};let o=0;for(ts.lastIndex=0;null!==(s=ts.exec(e));){const e=new Ii(s[1],i),n=e.TYPE;if(n){const i=a[n],s=r[n]||[];r[n]=s;const l=e.LANGUAGE,d=e["ASSOC-LANGUAGE"],c=e.CHANNELS,u=e.CHARACTERISTICS,h=e["INSTREAM-ID"],f={attrs:e,bitrate:0,id:o++,groupId:e["GROUP-ID"]||"",name:e.NAME||l||"",type:n,default:e.bool("DEFAULT"),autoselect:e.bool("AUTOSELECT"),forced:e.bool("FORCED"),lang:l,url:e.URI?ns.resolve(e.URI,t):""};if(d&&(f.assocLang=d),c&&(f.channels=c),u&&(f.characteristics=u),h&&(f.instreamId=h),null!=i&&i.length){const e=ns.findGroup(i,f.groupId)||i[0];us(f,e,"audioCodec"),us(f,e,"textCodec")}s.push(f)}}return r}static parseLevelPlaylist(e,t,i,s,r,n){var a;const o={url:t},l=new Di(t),d=l.fragments,c=[];let u,h,f,g,p=null,m=0,v=0,y=0,T=0,E=0,S=null,A=new ue(s,o),b=-1,R=!1,I=null;if(ss.lastIndex=0,l.m3u8=e,l.hasVariableRefs=Ei(e),"#EXTM3U"!==(null==(a=ss.exec(e))?void 0:a[0]))return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;null!==(u=ss.exec(e));){R&&(R=!1,A=new ue(s,o),A.playlistOffset=y,A.setStart(y),A.sn=m,A.cc=T,E&&(A.bitrate=E),A.level=i,p&&(A.initSegment=p,p.rawProgramDateTime&&(A.rawProgramDateTime=p.rawProgramDateTime,p.rawProgramDateTime=null),I&&(A.setByteRange(I),I=null)));const e=u[1];if(e){A.duration=parseFloat(e);const t=(" "+u[2]).slice(1);A.title=t||null,A.tagList.push(t?["INF",e,t]:["INF",e])}else if(u[3]){if(L(A.duration)){A.playlistOffset=y,A.setStart(y),f&&gs(A,f,l),A.sn=m,A.level=i,A.cc=T,d.push(A);const e=(" "+u[3]).slice(1);A.relurl=Si(l,e),hs(A,S,c),S=A,y+=A.duration,m++,v=0,R=!0}}else{if(u=u[0].match(rs),!u){z.warn("No matches on slow regex match for level playlist!");continue}for(h=1;h<u.length&&void 0===u[h];h++);const e=(" "+u[h]).slice(1),r=(" "+u[h+1]).slice(1),a=u[h+2]?(" "+u[h+2]).slice(1):null;switch(e){case"BYTERANGE":S?A.setByteRange(r,S):A.setByteRange(r);break;case"PROGRAM-DATE-TIME":A.rawProgramDateTime=r,A.tagList.push(["PROGRAM-DATE-TIME",r]),-1===b&&(b=d.length);break;case"PLAYLIST-TYPE":l.type&&ps(l,e,u),l.type=r.toUpperCase();break;case"MEDIA-SEQUENCE":0!==l.startSN?ps(l,e,u):d.length>0&&ms(l,e,u),m=l.startSN=parseInt(r);break;case"SKIP":{l.skippedSegments&&ps(l,e,u);const t=new Ii(r,l),i=t.decimalInteger("SKIPPED-SEGMENTS");if(L(i)){l.skippedSegments+=i;for(let e=i;e--;)d.push(null);m+=i}const s=t.enumeratedString("RECENTLY-REMOVED-DATERANGES");s&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(s.split("\t")));break}case"TARGETDURATION":0!==l.targetduration&&ps(l,e,u),l.targetduration=Math.max(parseInt(r),1);break;case"VERSION":null!==l.version&&ps(l,e,u),l.version=parseInt(r);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||ps(l,e,u),l.live=!1;break;case"#":(r||a)&&A.tagList.push(a?[r,a]:[r]);break;case"DISCONTINUITY":T++,A.tagList.push(["DIS"]);break;case"GAP":A.gap=!0,A.tagList.push([e]);break;case"BITRATE":A.tagList.push([e,r]),E=1e3*parseInt(r),L(E)?A.bitrate=E:E=0;break;case"DATERANGE":{const e=new Ii(r,l),t=new Pi(e,l.dateRanges[e.ID],l.dateRangeTagCount);l.dateRangeTagCount++,t.isValid||l.skippedSegments?l.dateRanges[t.id]=t:z.warn(`Ignoring invalid DATERANGE tag: "${r}"`),A.tagList.push(["EXT-X-DATERANGE",r]);break}case"DEFINE":{const e=new Ii(r,l);"IMPORT"in e?bi(l,e,n):Ai(l,e,t)}break;case"DISCONTINUITY-SEQUENCE":0!==l.startCC?ps(l,e,u):d.length>0&&ms(l,e,u),l.startCC=T=parseInt(r);break;case"KEY":{const e=ls(r,t,l);if(e.isSupported()){if("NONE"===e.method){f=void 0;break}f||(f={});const t=f[e.keyFormat];null!=t&&t.matches(e)||(t&&(f=$({},f)),f[e.keyFormat]=e)}else z.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${r}"`);break}case"START":l.startTimeOffset=ds(r);break;case"MAP":{const e=new Ii(r,l);if(A.duration){const t=new ue(s,o);fs(t,e,i,f),p=t,A.initSegment=p,p.rawProgramDateTime&&!A.rawProgramDateTime&&(A.rawProgramDateTime=p.rawProgramDateTime)}else{const t=A.byteRangeEndOffset;if(t){const e=A.byteRangeStartOffset;I=`${t-e}@${e}`}else I=null;fs(A,e,i,f),p=A,R=!0}p.cc=T;break}case"SERVER-CONTROL":g&&ps(l,e,u),g=new Ii(r),l.canBlockReload=g.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=g.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&g.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=g.optionalFloat("PART-HOLD-BACK",0),l.holdBack=g.optionalFloat("HOLD-BACK",0);break;case"PART-INF":{l.partTarget&&ps(l,e,u);const t=new Ii(r);l.partTarget=t.decimalFloatingPoint("PART-TARGET");break}case"PART":{let e=l.partList;e||(e=l.partList=[]);const t=v>0?e[e.length-1]:void 0,i=v++,s=new Ii(r,l),n=new he(s,A,o,i,t);e.push(n),A.duration+=n.duration;break}case"PRELOAD-HINT":{const e=new Ii(r,l);l.preloadHint=e;break}case"RENDITION-REPORT":{const e=new Ii(r,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(e);break}default:z.warn(`line parsed but not handled: ${u}`)}}}S&&!S.relurl?(d.pop(),y-=S.duration,l.partList&&(l.fragmentHint=S)):l.partList&&(hs(A,S,c),A.cc=T,l.fragmentHint=A,f&&gs(A,f,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));const k=d.length,w=d[0],P=d[k-1];if(y+=l.skippedSegments*l.targetduration,y>0&&k&&P){l.averagetargetduration=y/k;const e=P.sn;l.endSN="initSegment"!==e?e:0,l.live||(P.endList=!0),b>0&&(!function(e,t){let i=e[t];for(let s=t;s--;){const t=e[s];if(!t)return;t.programDateTime=i.programDateTime-1e3*t.duration,i=t}}(d,b),w&&c.unshift(w))}return l.fragmentHint&&(y+=l.fragmentHint.duration),l.totalduration=y,c.length&&l.dateRangeTagCount&&w&&as(c,l),l.endCC=T,l}}function as(e,t){let i=e.length;if(!i){if(!t.hasProgramDateTime)return;{const s=t.fragments[t.fragments.length-1];e.push(s),i++}}const s=e[i-1],r=t.live?1/0:t.totalduration,n=Object.keys(t.dateRanges);for(let o=n.length;o--;){const l=t.dateRanges[n[o]],d=l.startDate.getTime();l.tagAnchor=s.ref;for(let s=i;s--;){var a;if((null==(a=e[s])?void 0:a.sn)<t.startSN)break;const i=os(t,d,e,s,r);if(-1!==i){l.tagAnchor=t.fragments[i].ref;break}}}}function os(e,t,i,s,r){const n=i[s];if(n){const o=n.programDateTime;if(t>=o||0===s){var a;if(t<=o+1e3*(((null==(a=i[s+1])?void 0:a.start)||r)-n.start)){const r=i[s].sn-e.startSN;if(r<0)return-1;const n=e.fragments;if(n.length>i.length){for(let a=(i[s+1]||n[n.length-1]).sn-e.startSN;a>r;a--){const e=n[a].programDateTime;if(t>=e&&t<e+1e3*n[a].duration)return a}}return r}}}return-1}function ls(e,t,i){var s,r;const n=new Ii(e,i),a=null!=(s=n.METHOD)?s:"",o=n.URI,l=n.hexadecimalInteger("IV"),d=n.KEYFORMATVERSIONS,c=null!=(r=n.KEYFORMAT)?r:"identity";o&&n.IV&&!l&&z.error(`Invalid IV: ${n.IV}`);const u=o?ns.resolve(o,t):"",h=(d||"1").split("/").map(Number).filter(Number.isFinite);return new Ji(a,u,c,h,l,n.KEYID)}function ds(e){const t=new Ii(e).decimalFloatingPoint("TIME-OFFSET");return L(t)?t:null}function cs(e,t){let i=(e||"").split(/[ ,]+/).filter(e=>e);["video","audio","text"].forEach(e=>{const s=i.filter(t=>Ge(t,e));s.length&&(t[`${e}Codec`]=s.map(e=>e.split("/")[0]).join(","),i=i.filter(e=>-1===s.indexOf(e)))}),t.unknownCodecs=i}function us(e,t,i){const s=t[i];s&&(e[i]=s)}function hs(e,t,i){e.rawProgramDateTime?i.push(e):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function fs(e,t,i,s){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=i,e.sn="initSegment",s&&(e.levelkeys=s),e.initSegment=null}function gs(e,t,i){e.levelkeys=t;const{encryptedFragments:s}=i;s.length&&s[s.length-1].levelkeys===t||!Object.keys(t).some(e=>t[e].isCommonEncryption)||s.push(e)}function ps(e,t,i){e.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${i[0]})`)}function ms(e,t,i){e.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${i[0]})`)}function vs(e,t){const i=t.startPTS;if(L(i)){let s,r=0;t.sn>e.sn?(r=i-e.start,s=e):(r=e.start-i,s=t),s.duration!==r&&s.setDuration(r)}else if(t.sn>e.sn){e.cc===t.cc&&e.minEndPTS?t.setStart(e.start+(e.minEndPTS-e.start)):t.setStart(e.start+e.duration)}else t.setStart(Math.max(e.start-t.duration,0))}function ys(e,t,i,s,r,n,a){s-i<=0&&(a.warn("Fragment should have a positive duration",t),s=i+t.duration,n=r+t.duration);let o=i,l=s;const d=t.startPTS,c=t.endPTS;if(L(d)){const u=Math.abs(d-i);e&&u>e.totalduration?a.warn(`media timestamps and playlist times differ by ${u}s for level ${t.level} ${e.url}`):L(t.deltaPTS)?t.deltaPTS=Math.max(u,t.deltaPTS):t.deltaPTS=u,o=Math.max(i,d),i=Math.min(i,d),r=void 0!==t.startDTS?Math.min(r,t.startDTS):r,l=Math.min(s,c),s=Math.max(s,c),n=void 0!==t.endDTS?Math.max(n,t.endDTS):n}const u=i-t.start;0!==t.start&&t.setStart(i),t.setDuration(s-t.start),t.startPTS=i,t.maxStartPTS=o,t.startDTS=r,t.endPTS=s,t.minEndPTS=l,t.endDTS=n;const h=t.sn;if(!e||h<e.startSN||h>e.endSN)return 0;let f;const g=h-e.startSN,p=e.fragments;for(p[g]=t,f=g;f>0;f--)vs(p[f],p[f-1]);for(f=g;f<p.length-1;f++)vs(p[f],p[f+1]);return e.fragmentHint&&vs(p[p.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,u}function Ts(e,t,i){if(e===t)return;let s=null;const r=e.fragments;for(let e=r.length-1;e>=0;e--){const t=r[e].initSegment;if(t){s=t;break}}let n;e.fragmentHint&&delete e.fragmentHint.endPTS,function(e,t,i){const s=t.skippedSegments,r=Math.max(e.startSN,t.startSN)-t.startSN,n=(e.fragmentHint?1:0)+(s?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,a=t.startSN-e.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments;for(let d=r;d<=n;d++){const r=l[a+d];let n=o[d];if(s&&!n&&r&&(n=t.fragments[d]=r),r&&n){i(r,n,d,o);const s=r.relurl,a=n.relurl;if(s&&ws(s,a))return void(t.playlistParsingError=Es(`media sequence mismatch ${n.sn}:`,e,t,r,n));if(r.cc!==n.cc)return void(t.playlistParsingError=Es(`discontinuity sequence mismatch (${r.cc}!=${n.cc})`,e,t,r,n))}}}(e,t,(e,i,r,a)=>{if((!t.startCC||t.skippedSegments)&&i.cc!==e.cc){const s=e.cc-i.cc;for(let e=r;e<a.length;e++)a[e].cc+=s;t.endCC=a[a.length-1].cc}L(e.startPTS)&&L(e.endPTS)&&(i.setStart(i.startPTS=e.startPTS),i.startDTS=e.startDTS,i.maxStartPTS=e.maxStartPTS,i.endPTS=e.endPTS,i.endDTS=e.endDTS,i.minEndPTS=e.minEndPTS,i.setDuration(e.endPTS-e.startPTS),i.duration&&(n=i),t.PTSKnown=t.alignedSliding=!0),e.hasStreams&&(i.elementaryStreams=e.elementaryStreams),i.loader=e.loader,e.hasStats&&(i.stats=e.stats),e.initSegment&&(i.initSegment=e.initSegment,s=e.initSegment)});const a=t.fragments,o=t.fragmentHint?a.concat(t.fragmentHint):a;if(s&&o.forEach(e=>{var t;!e||e.initSegment&&e.initSegment.relurl!==(null==(t=s)?void 0:t.relurl)||(e.initSegment=s)}),t.skippedSegments){if(t.deltaUpdateFailed=a.some(e=>!e),t.deltaUpdateFailed){i.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let e=t.skippedSegments;e--;)a.shift();t.startSN=a[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=function(e,t,i){const{dateRanges:s,recentlyRemovedDateranges:r}=t,n=$({},e);r&&r.forEach(e=>{delete n[e]});const a=Object.keys(n).length;if(!a)return s;return Object.keys(s).forEach(e=>{const t=n[e],r=new Pi(s[e].attr,t);r.isValid?(n[e]=r,t||(r.tagOrder+=a)):i.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Tt(s[e].attr)}"`)}),n}(e.dateRanges,t,i));const s=e.fragments.filter(e=>e.rawProgramDateTime);if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(let e=1;e<o.length;e++)null===o[e].programDateTime&&hs(o[e],o[e-1],s);as(s,t)}t.endCC=a[a.length-1].cc}if(!t.startCC){var l;const i=Ls(e,t.startSN-1);t.startCC=null!=(l=null==i?void 0:i.cc)?l:a[0].cc}!function(e,t,i){if(e&&t){let s=0;for(let r=0,n=e.length;r<=n;r++){const n=e[r],a=t[r+s];n&&a&&n.index===a.index&&n.fragment.sn===a.fragment.sn?i(n,a):s--}}}(e.partList,t.partList,(e,t)=>{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats}),n?ys(t,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,i):Ss(e,t),a.length&&(t.totalduration=t.edge-a[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;const d=t.advancedDateTime;if(t.advanced&&d){const e=t.edge;t.driftStart||(t.driftStartTime=d,t.driftStart=e),t.driftEndTime=d,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;-1===t.requestScheduled&&(t.requestScheduled=e.requestScheduled)}function Es(e,t,i,s,r){return new Error(`${e} ${r.url}\nPlaylist starting @${t.startSN}\n${t.m3u8}\n\nPlaylist starting @${i.startSN}\n${i.m3u8}`)}function Ss(e,t,i=!0){const s=t.startSN+t.skippedSegments-e.startSN,r=e.fragments,n=s>=0;let a=0;if(n&&s<r.length)a=r[s].start;else if(n&&t.startSN===e.endSN+1)a=e.fragmentEnd;else if(n&&i)a=e.fragmentStart+s*t.levelTargetDuration;else{if(t.skippedSegments||0!==t.fragmentStart)return;a=e.fragmentStart}As(t,a)}function As(e,t){if(t){const i=e.fragments;for(let s=e.skippedSegments;s<i.length;s++)i[s].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}function bs(e,t=1/0){let i=1e3*e.targetduration;if(e.updated){const s=e.fragments,r=4;if(s.length&&i*r>t){const e=1e3*s[s.length-1].duration;e<i&&(i=e)}}else i/=2;return Math.round(i)}function Ls(e,t,i){if(!e)return null;let s=e.fragments[t-e.startSN];return s||(s=e.fragmentHint,s&&s.sn===t?s:t<e.startSN&&i&&i.sn===t?i:null)}function Rs(e,t,i){return e?Is(e.partList,t,i):null}function Is(e,t,i){if(e)for(let s=e.length;s--;){const r=e[s];if(r.index===i&&r.fragment.sn===t)return r}return null}function ks(e){e.forEach((e,t)=>{var i;null==(i=e.details)||i.fragments.forEach(e=>{e.level=t,e.initSegment&&(e.initSegment.level=t)})})}function ws(e,t){return!(e===t||!t)&&Ps(e)!==Ps(t)}function Ps(e){return e.replace(/\?[^?]*$/,"")}function Ds(e,t){for(let s=0,r=e.length;s<r;s++){var i;if((null==(i=e[s])?void 0:i.cc)===t)return e[s]}return null}function xs(e,t){const i=e.start+t;e.startPTS=i,e.setStart(i),e.endPTS=i+e.duration}function Cs(e,t){const i=t.fragments;for(let t=0,s=i.length;t<s;t++)xs(i[t],e);t.fragmentHint&&xs(t.fragmentHint,e),t.alignedSliding=!0}function _s(e,t){if(!function(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}(t,e))return;const i=Math.min(t.endCC,e.endCC),s=Ds(t.fragments,i),r=Ds(e.fragments,i);if(!s||!r)return;z.log(`Aligning playlist at start of dicontinuity sequence ${i}`);Cs(s.start-r.start,e)}function Ms(e,t){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;const i=e.fragments,s=t.fragments;if(!i.length||!s.length)return;let r,n;const a=Math.min(t.endCC,e.endCC);t.startCC<a&&e.startCC<a&&(r=Ds(s,a),n=Ds(i,a)),r&&n||(r=s[Math.floor(s.length/2)],n=Ds(i,r.cc)||i[Math.floor(i.length/2)]);const o=r.programDateTime,l=n.programDateTime;if(!o||!l)return;Cs((l-o)/1e3-(n.start-r.start),e)}function Os(e,t,i){Fs(e,t,i),e.addEventListener(t,i)}function Fs(e,t,i){e.removeEventListener(t,i)}const Us=function(e){let t="";const i=e.length;for(let s=0;s<i;s++)t+=`[${e.start(s).toFixed(3)}-${e.end(s).toFixed(3)}]`;return t},Ns="STOPPED",Bs="IDLE",$s="KEY_LOADING",Vs="FRAG_LOADING",Gs="FRAG_LOADING_WAITING_RETRY",Hs="WAITING_TRACK",Ks="PARSING",js="PARSED",Ws="ENDED",qs="ERROR",Ys="WAITING_INIT_PTS",zs="WAITING_LEVEL";class Xs extends pi{constructor(e,t,i,s,r){super(s,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=Ns,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:e,fragCurrent:t,media:i,mediaBuffer:s,state:r}=this,n=i?i.currentTime:0,a=yi.bufferInfo(s||i,n,e.maxBufferHole),o=!a.len;if(this.log(`Media seeking to ${L(n)?n.toFixed(3):n}, state: ${r}, ${o?"out of":"in"} buffer`),this.state===Ws)this.resetLoadingState();else if(t){const i=e.maxFragLookUpTolerance,s=t.start-i,r=t.start+t.duration+i;if(o||r<a.start||s>a.end){const e=n>r;(n<s||e)&&(e&&t.loader&&(this.log(`Cancelling fragment load for seek (sn: ${t.sn})`),t.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(i){this.fragmentTracker.removeFragmentsInRange(n,1/0,this.playlistType,!0);if(n>this.lastCurrentTime&&(this.lastCurrentTime=n),!this.loadingParts){const e=Math.max(a.end,n),t=this.shouldLoadParts(this.getLevelDetails(),e);t&&(this.log(`LL-Part loading ON after seeking to ${n.toFixed(2)} with buffer @${e.toFixed(2)}`),this.loadingParts=t)}}this.hls.hasEnoughToStart||(this.log(`Setting ${o?"startPosition":"nextLoadPosition"} to ${n} for seek without enough to start`),this.nextLoadPosition=n,o&&(this.startPosition=n)),o&&this.state===Bs&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=e,this.fragmentLoader=new ui(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new di(e.config)}registerListeners(){const{hls:e}=this;e.on(P.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(P.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(P.MANIFEST_LOADING,this.onManifestLoading,this),e.on(P.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(P.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(P.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(P.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(P.MANIFEST_LOADING,this.onManifestLoading,this),e.off(P.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(P.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===Ns)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;null!=e&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=Ns}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return-1===t&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const i=e.end||0,s=this.config.timelineOffset||0;if(i<=s)return!1;const r=e.buffered;this.config.maxBufferHole&&r&&r.length>1&&(e=yi.bufferedInfo(r,e.start,0));const n=e.nextStart;if(n&&n>s&&n<t.edge)return!1;if(this.media.currentTime<e.start)return!1;const a=t.partList;if(null!=a&&a.length){const e=a[a.length-1];return yi.isBuffered(this.media,e.start+e.duration/2)}const o=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(o)}getLevelDetails(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;var t;return e?(null==(t=this.getLevelDetails())?void 0:t.appliedTimelineOffset)||e:0}onMediaAttached(e,t){const i=this.media=this.mediaBuffer=t.media;Os(i,"seeking",this.onMediaSeeking),Os(i,"ended",this.onMediaEnded);const s=this.config;this.levels&&s.autoStartLoad&&this.state===Ns&&this.startLoad(s.startPosition)}onMediaDetaching(e,t){const i=!!t.transferMedia,s=this.media;if(null!==s){if(s.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Fs(s,"seeking",this.onMediaSeeking),Fs(s,"ended",this.onMediaEnded),this.keyLoader&&!i&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,i)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=Ns,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,i){this.startFragRequested=!0,this._loadFragForPlayback(e,t,i)}_loadFragForPlayback(e,t,i){this._doFragLoad(e,t,i,e=>{const t=e.frag;if(this.fragContextChanged(t))return this.warn(`${t.type} sn: ${t.sn}${e.part?" part: "+e.part.index:""} of ${this.fragInfo(t,!1,e.part)}) was dropped during download.`),void this.fragmentTracker.removeFragment(t);t.stats.chunkCount++,this._handleFragmentLoadProgress(e)}).then(e=>{if(!e)return;const t=this.state,i=e.frag;this.fragContextChanged(i)?(t===Vs||!this.fragCurrent&&t===Ks)&&(this.fragmentTracker.removeFragment(i),this.state=Bs):("payload"in e&&(this.log(`Loaded ${i.type} sn: ${i.sn} of ${this.playlistLabel()} ${i.level}`),this.hls.trigger(P.FRAG_LOADED,e)),this._handleFragmentLoadComplete(e))}).catch(t=>{this.state!==Ns&&this.state!==qs&&(this.warn(`Frag error: ${(null==t?void 0:t.message)||t}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:i}=this;if(i.getState(e)===Qt){const t=e.type,s=this.getFwdBufferInfo(this.mediaBuffer,t),r=Math.max(e.duration,s?s.len:this.config.maxBufferLength),n=this.backtrackFragment;(1===(n?e.sn-n.sn:0)||this.reduceMaxBufferLength(r,e.duration))&&i.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===Jt&&i.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return(null==t?void 0:t.live)&&"EVENT"!==t.type&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,i=null){if(!(e-t))return;const s={startOffset:e,endOffset:t,type:i};this.hls.trigger(P.BUFFER_FLUSHING,s)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(e=>{const t=null==e?void 0:e.frag;if(!t||this.fragContextChanged(t)||!this.levels)throw new Error("init load aborted");return e}).then(e=>{const{hls:t}=this,{frag:i,payload:s}=e,r=i.decryptdata;if(s&&s.byteLength>0&&null!=r&&r.key&&r.iv&&_i(r.method)){const n=self.performance.now();return this.decrypter.decrypt(new Uint8Array(s),r.key.buffer,r.iv.buffer,Mi(r.method)).catch(e=>{throw t.trigger(P.ERROR,{type:k.MEDIA_ERROR,details:w.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:i}),e}).then(s=>{const r=self.performance.now();return t.trigger(P.FRAG_DECRYPTED,{frag:i,payload:s,stats:{tstart:n,tdecrypt:r}}),e.payload=s,this.completeInitSegmentLoad(e)})}return this.completeInitSegmentLoad(e)}).catch(t=>{this.state!==Ns&&this.state!==qs&&(this.warn(t),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const i=e.frag.stats;this.state!==Ns&&(this.state=Bs),e.frag.data=new Uint8Array(e.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var i,s;const r=e.tracks;if(r&&!t.encrypted&&(null!=(i=r.audio)&&i.encrypted||null!=(s=r.video)&&s.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const e=this.media,i=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${e?"attached mediaKeys: "+e.mediaKeys:"detached"})`);return this.warn(i.message),!e||e.mediaKeys?!1:(this.hls.trigger(P.ERROR,{type:k.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_KEYS,fatal:!1,error:i,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${i?Us(yi.getBuffered(i)):"(detached)"})`),ce(e)){var s;if(e.type!==F){const t=e.elementaryStreams;if(!Object.keys(t).some(e=>!!t[e]))return void(this.state=Bs)}const t=null==(s=this.levels)?void 0:s[e.level];null!=t&&t.fragmentError&&(this.log(`Resetting level fragment error count of ${t.fragmentError} on frag buffered`),t.fragmentError=0)}this.state=Bs}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:i,part:s,partsLoaded:r}=e,n=!r||0===r.length||r.some(e=>!e),a=new mi(i.level,i.sn,i.stats.chunkCount+1,0,s?s.index:-1,!n);t.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,s){var r;this.fragCurrent=e;const n=t.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let a=null;if(!e.encrypted||null!=(r=e.decryptdata)&&r.key)e.encrypted||(a=this.keyLoader.loadClear(e,n.encryptedFragments,this.startFragRequested),a&&this.log("[eme] blocking frag load until media-keys acquired"));else if(this.log(`Loading key for ${e.sn} of [${n.startSN}-${n.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=$s,this.fragCurrent=e,a=this.keyLoader.load(e).then(e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(P.KEY_LOADED,e),this.state===$s&&(this.state=Bs),e}),this.hls.trigger(P.KEY_LOADING,{frag:e}),null===this.fragCurrent)return this.log("context changed in KEY_LOADING"),Promise.resolve(null);const o=this.fragPrevious;if(ce(e)&&(!o||e.sn!==o.sn)){const i=this.shouldLoadParts(t.details,e.end);i!==this.loadingParts&&(this.log(`LL-Part loading ${i?"ON":"OFF"} loading sn ${null==o?void 0:o.sn}->${e.sn}`),this.loadingParts=i)}if(i=Math.max(e.start,i||0),this.loadingParts&&ce(e)){const r=n.partList;if(r&&s){i>n.fragmentEnd&&n.fragmentHint&&(e=n.fragmentHint);const o=this.getNextPart(r,e,i);if(o>-1){const l=r[o];let d;return e=this.fragCurrent=l.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${l.index} (${o}/${r.length-1}) of ${this.fragInfo(e,!1,l)}) cc: ${e.cc} [${n.startSN}-${n.endSN}], target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=Vs,d=a?a.then(i=>!i||this.fragContextChanged(i.frag)?null:this.doFragPartsLoad(e,l,t,s)).catch(e=>this.handleFragLoadError(e)):this.doFragPartsLoad(e,l,t,s).catch(e=>this.handleFragLoadError(e)),this.hls.trigger(P.FRAG_LOADING,{frag:e,part:l,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):d}if(!e.url||this.loadedEndOfParts(r,i))return Promise.resolve(null)}}var l;if(ce(e)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${i.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${null==(l=n.partList)?void 0:l.filter(e=>e.loaded).map(e=>`[${e.start}-${e.end}]`)}`),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+n.startSN+"-"+n.endSN+"]"}, target: ${parseFloat(i.toFixed(3))}`),L(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=Vs;const d=this.config.progressive;let c;return c=d&&a?a.then(t=>!t||this.fragContextChanged(t.frag)?null:this.fragmentLoader.load(e,s)).catch(e=>this.handleFragLoadError(e)):Promise.all([this.fragmentLoader.load(e,d?s:void 0),a]).then(([e])=>(!d&&s&&s(e),e)).catch(e=>this.handleFragLoadError(e)),this.hls.trigger(P.FRAG_LOADING,{frag:e,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):c}doFragPartsLoad(e,t,i,s){return new Promise((r,n)=>{var a;const o=[],l=null==(a=i.details)?void 0:a.partList,d=t=>{this.fragmentLoader.loadPart(e,t,s).then(s=>{o[t.index]=s;const n=s.part;this.hls.trigger(P.FRAG_LOADED,s);const a=Rs(i.details,e.sn,t.index+1)||Is(l,e.sn,t.index+1);if(!a)return r({frag:e,part:n,partsLoaded:o});d(a)}).catch(n)};d(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===w.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===k.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(P.ERROR,t)}else this.hls.trigger(P.ERROR,{type:k.OTHER_ERROR,details:w.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==Ks)return void(this.fragCurrent||this.state===Ns||this.state===qs||(this.state=Bs));const{frag:i,part:s,level:r}=t,n=self.performance.now();i.stats.parsing.end=n,s&&(s.stats.parsing.end=n);const a=this.getLevelDetails(),o=a&&i.sn>a.endSN||this.shouldLoadParts(a,i.end);o!==this.loadingParts&&(this.log(`LL-Part loading ${o?"ON":"OFF"} after parsing segment ending @${i.end.toFixed(2)}`),this.loadingParts=o),this.updateLevelTiming(i,s,r,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var i;const r=e.partList[0];if(r.fragment.type===F)return!1;if(t>=r.end+((null==(i=e.fragmentHint)?void 0:i.duration)||0)){var s;if((this.hls.hasEnoughToStart?(null==(s=this.media)?void 0:s.currentTime)||this.lastCurrentTime:this.getLoadPosition())>r.start-r.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:i}=this,{level:s,sn:r,part:n}=e;if(null==t||!t[s])return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${s}. The current chunk will not be buffered.`),null;const a=t[s],o=a.details,l=n>-1?Rs(o,r,n):null,d=l?l.fragment:Ls(o,r,i);return d?(i&&i!==d&&(d.stats=i.stats),{frag:d,part:l,level:a}):null}bufferFragmentData(e,t,i,s,r){if(this.state!==Ks)return;const{data1:n,data2:a}=e;let o=n;if(a&&(o=Ce(n,a)),!o.length)return;const l=this.initPTS[t.cc],d=l?-l.baseTime/l.timescale:void 0,c={type:e.type,frag:t,part:i,chunkMeta:s,offset:d,parent:t.type,data:o};if(this.hls.trigger(P.BUFFER_APPENDING,c),e.dropped&&e.independent&&!i){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!yi.isBuffered(t,t.currentTime))return void this.flushMainBuffer(0,e.start);const i=t.currentTime,s=yi.bufferInfo(t,i,0),r=e.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*r),a=Math.max(Math.min(e.start-n,s.end-n),i+n);e.start-a>n&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){var i;const s=this.getLoadPosition();if(!L(s))return null;const r=this.lastCurrentTime>s||null!=(i=this.media)&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,s,t,r)}getFwdBufferInfoAtPos(e,t,i,s){const r=yi.bufferInfo(e,t,s);if(0===r.len&&void 0!==r.nextStart){const n=this.fragmentTracker.getBufferedFrag(t,i);if(n&&(r.nextStart<=n.end||n.gap)){const i=Math.max(Math.min(r.nextStart,n.end)-t,s);return yi.bufferInfo(e,t,i)}}return r}getMaxBufferLength(e){const{config:t}=this;let i;return i=e?Math.max(8*t.maxBufferSize/e,t.maxBufferLength):t.maxBufferLength,Math.min(i,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const i=this.config,s=Math.max(Math.min(e-t,i.maxBufferLength),t),r=Math.max(e-3*t,i.maxMaxBufferLength/2,s);return r>=s&&(i.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0)}getAppendedFrag(e,t=M){const i=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return i&&"fragment"in i?i.fragment:i}getNextFragment(e,t){const i=t.fragments,s=i.length;if(!s)return null;const{config:r}=this,n=i[0].start,a=r.lowLatencyMode&&!!t.partList;let o=null;if(t.live){const i=r.initialLiveManifestSize;if(s<i)return this.warn(`Not enough fragments to start playback (have: ${s}, need: ${i})`),null;if(!t.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||e<n){var l;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),o=this.getInitialLiveFragment(t);const i=this.hls.startPosition,s=this.hls.liveSyncPosition,r=o?(-1!==i&&i>=n?i:s)||o.start:e;this.log(`Setting startPosition to ${r} to match start frag at live edge. mainStart: ${i} liveSyncPosition: ${s} frag.start: ${null==(l=o)?void 0:l.start}`),this.startPosition=this.nextLoadPosition=r}}else e<=n&&(o=i[0]);if(!o){const i=this.loadingParts?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,i,t)}let d=this.filterReplacedPrimary(o,t);if(!d&&o){const e=o.sn-t.startSN;d=this.filterReplacedPrimary(i[e+1]||null,t)}return this.mapToInitFragWhenRequired(d)}isLoopLoading(e,t){const i=this.fragmentTracker.getState(e);return(i===Zt||i===Jt&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,i,s,r){let n=null;if(e.gap&&(n=this.getNextFragment(this.nextLoadPosition,t),n&&!n.gap&&i.nextStart)){const e=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,s,0);if(null!==e&&i.len+e.len>=r){const e=n.sn;return this.loopSn!==e&&(this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${e}`),this.loopSn=e),null}}return this.loopSn=void 0,n}get primaryPrefetch(){if(Qs(this.config)){var e;if(null==(e=this.hls.interstitialsManager)||null==(e=e.playingItem)?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(Qs(this.config)&&e.type!==F){const i=this.hls.interstitialsManager,s=null==i?void 0:i.bufferingItem;if(s){const i=s.event;if(i){if(i.appendInPlace||Math.abs(e.start-s.start)>1||0===s.start)return null}else{if(e.end<=s.start&&!1===(null==t?void 0:t.live))return null;if(e.start>s.end&&s.nextEvent&&(s.nextEvent.appendInPlace||e.start-s.end>1))return null}}const r=null==i?void 0:i.playerQueue;if(r)for(let t=r.length;t--;){const i=r[t].interstitial;if(i.appendInPlace&&e.start>=i.startTime&&e.end<=i.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return null==e||!e.initSegment||e.initSegment.data||this.bitrateTest?e:e.initSegment}getNextPart(e,t,i){let s=-1,r=!1,n=!0;for(let a=0,o=e.length;a<o;a++){const o=e[a];if(n=n&&!o.independent,s>-1&&i<o.start)break;const l=o.loaded;l?s=-1:(r||(o.independent||n)&&o.fragment===t)&&(o.fragment!==t&&this.warn(`Need buffer at ${i} but next unloaded part starts at ${o.start}`),s=a),r=l}return s}loadedEndOfParts(e,t){let i;for(let s=e.length;s--;){if(i=e[s],!i.loaded)return!1;if(t>i.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,i=this.fragPrevious;let s=null;if(i){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),s=function(e,t,i){if(null===t||!Array.isArray(e)||!e.length||!L(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;for(let s=0;s<e.length;++s){const r=e[s];if(xt(t,i,r))return r}return null}(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!s){const r=i.sn+1;if(r>=e.startSN&&r<=e.endSN){const n=t[r-e.startSN];i.cc===n.cc&&(s=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`))}s||(s=Ct(e,i.cc,i.end),s&&this.log(`Live playlist, switching playlist, load frag with same CC: ${s.sn}`))}}else{const t=this.hls.liveSyncPosition;null!==t&&(s=this.getFragmentAtPosition(t,this.bitrateTest?e.fragmentEnd:e.edge,e))}return s}getFragmentAtPosition(e,t,i){const{config:s}=this;let{fragPrevious:r}=this,{fragments:n,endSN:a}=i;const{fragmentHint:o}=i,{maxFragLookUpTolerance:l}=s,d=i.partList,c=!!(this.loadingParts&&null!=d&&d.length&&o);let u;if(c&&!this.bitrateTest&&d[d.length-1].fragment.sn===o.sn&&(n=n.concat(o),a=o.sn),e<t){var h;u=Pt(r,n,e,e<this.lastCurrentTime||e>t-l||null!=(h=this.media)&&h.paused||!this.startFragRequested?0:l)}else u=n[n.length-1];if(u){const e=u.sn-i.startSN,t=this.fragmentTracker.getState(u);if((t===Zt||t===Jt&&u.gap)&&(r=u),r&&u.sn===r.sn&&(!c||d[0].fragment.sn>u.sn||!i.live)){if(u.level===r.level){const t=n[e+1];u=u.sn<a&&this.fragmentTracker.getState(t)!==Zt?t:null}}}return u}alignPlaylists(e,t,i){const s=e.fragments.length;if(!s)return this.warn("No fragments in live playlist"),0;const r=e.fragmentStart,n=!t,a=e.alignedSliding&&L(r);if(n||!a&&!r){!function(e,t){e&&(_s(t,e),t.alignedSliding||Ms(t,e),t.alignedSliding||t.skippedSegments||Ss(e,t,!1))}(i,e);const r=e.fragmentStart;return this.log(`Live playlist sliding: ${r.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${s}`),r}return r}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}setStartPosition(e,t){let i=this.startPosition;i<t&&(i=-1);const s=this.timelineOffset;if(-1===i){const r=null!==this.startTimeOffset,n=r?this.startTimeOffset:e.startTimeOffset;null!==n&&L(n)?(i=t+n,n<0&&(i+=e.edge),i=Math.min(Math.max(t,i),t+e.totalduration),this.log(`Setting startPosition to ${i} for start time offset ${n} found in ${r?"multivariant":"media"} playlist`),this.startPosition=i):e.live?(i=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${i}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=i=0),this.lastCurrentTime=i+s}this.nextLoadPosition=i+s}getLoadPosition(){var e;const{media:t}=this;let i=0;return null!=(e=this.hls)&&e.hasEnoughToStart&&t?i=t.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&ce(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){this.fragCurrent&&(this.fragContextChanged(e)||this.state===Gs)||(this.state=Bs)}onFragmentOrKeyLoadError(e,t){var i;if(t.chunkMeta&&!t.frag){const e=this.getCurrentContext(t.chunkMeta);e&&(t.frag=e.frag)}const s=t.frag;if(!s||s.type!==e||!this.levels)return;var r;if(this.fragContextChanged(s))return void this.warn(`Frag load error must match current frag to retry ${s.url} > ${null==(r=this.fragCurrent)?void 0:r.url}`);const n=t.details===w.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(s,!0);const a=t.errorAction;if(!a)return void(this.state=qs);const{action:o,flags:l,retryCount:d=0,retryConfig:c}=a,u=!!c,h=u&&o===Kt,f=u&&!a.resolved&&l===Wt,g=null==(i=this.hls.latestLevelDetails)?void 0:i.live;if(!h&&f&&ce(s)&&!s.endList&&g&&!Ot(t))this.resetFragmentErrors(e),this.treatAsGap(s),a.resolved=!0;else if((h||f)&&d<c.maxNumRetry){var p;const i=$t(null==(p=t.response)?void 0:p.code),r=Ut(c,d);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+r,this.state=Gs,a.resolved=!0,i)return this.log("Waiting for connection (offline)"),this.retryDate=1/0,void(t.reason="offline");this.warn(`Fragment ${s.sn} of ${e} ${s.level} errored with ${t.details}, retrying loading ${d+1}/${c.maxNumRetry} in ${r}ms`)}else if(c){if(this.resetFragmentErrors(e),!(d<c.maxNumRetry))return void this.warn(`${t.details} reached or exceeded max retry (${d})`);n||o===Ht||(a.resolved=!0)}else this.state=o===Gt?zs:qs;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,i=t===1/0;(!t||e>=t||i&&!$t(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=Bs)}reduceLengthAndFlushBuffer(e){if(this.state===Ks||this.state===js){const t=e.frag,i=e.parent,s=this.getFwdBufferInfo(this.mediaBuffer,i),r=s&&s.len>.5;r&&this.reduceMaxBufferLength(s.len,(null==t?void 0:t.duration)||10);const n=!r;return n&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${i} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(e){e===O&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==Ns&&(this.state=Bs)}afterBufferFlushed(e,t,i){if(!e)return;const s=yi.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,s,i),this.state===Ws&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==Ns&&(this.state=Bs)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.levelLastLoaded,t=e?e.details:null;null!=t&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${-1===e.level?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,s){const r=i.details;if(!r)return void this.warn("level.details undefined");var n;if(!Object.keys(e.elementaryStreams).reduce((t,n)=>{const a=e.elementaryStreams[n];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${e.sn} ${n} duration reliably (${o})`),t||!1;const l=s?0:ys(r,e,a.startPTS,a.endPTS,a.startDTS,a.endDTS,this);return this.hls.trigger(P.LEVEL_PTS_UPDATED,{details:r,level:i,drift:l,type:n,frag:e,start:a.startPTS,end:a.endPTS}),!0}return t},!1)&&(0===i.fragmentError&&this.treatAsGap(e,i),null===(null==(n=this.transmuxer)?void 0:n.error))){const t=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(t.message),this.hls.trigger(P.ERROR,{type:k.MEDIA_ERROR,details:w.FRAG_PARSING_ERROR,fatal:!1,error:t,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=js,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(P.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===M?"level":"track"}fragInfo(e,t=!0,i){var s,r;return`${this.playlistLabel()} ${e.level} (${i?"part":"frag"}:[${(null!=(s=t&&!i?e.startPTS:(i||e).start)?s:NaN).toFixed(3)}-${(null!=(r=t&&!i?e.endPTS:(i||e).end)?r:NaN).toFixed(3)}]${i&&"main"===e.type?"INDEPENDENT="+(i.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;null==(e=this.transmuxer)||e.reset()}recoverWorkerError(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function Qs(e){return!!e.interstitialsController&&!1!==e.enableInterstitialPlayback}class Js{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let i;return e.length?(i=1===e.length?e[0]:function(e,t){const i=new Uint8Array(t);let s=0;for(let t=0;t<e.length;t++){const r=e[t];i.set(r,s),s+=r.length}return i}(e,t),this.reset(),i):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}var Zs,er={exports:{}};var tr=(Zs||(Zs=1,function(e){var t=Object.prototype.hasOwnProperty,i="~";function s(){}function r(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function n(e,t,s,n,a){if("function"!=typeof s)throw new TypeError("The listener must be a function");var o=new r(s,n||e,a),l=i?i+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function a(e,t){0===--e._eventsCount?e._events=new s:delete e._events[t]}function o(){this._events=new s,this._eventsCount=0}Object.create&&(s.prototype=Object.create(null),(new s).__proto__||(i=!1)),o.prototype.eventNames=function(){var e,s,r=[];if(0===this._eventsCount)return r;for(s in e=this._events)t.call(e,s)&&r.push(i?s.slice(1):s);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(e)):r},o.prototype.listeners=function(e){var t=i?i+e:e,s=this._events[t];if(!s)return[];if(s.fn)return[s.fn];for(var r=0,n=s.length,a=new Array(n);r<n;r++)a[r]=s[r].fn;return a},o.prototype.listenerCount=function(e){var t=i?i+e:e,s=this._events[t];return s?s.fn?1:s.length:0},o.prototype.emit=function(e,t,s,r,n,a){var o=i?i+e:e;if(!this._events[o])return!1;var l,d,c=this._events[o],u=arguments.length;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),u){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,s),!0;case 4:return c.fn.call(c.context,t,s,r),!0;case 5:return c.fn.call(c.context,t,s,r,n),!0;case 6:return c.fn.call(c.context,t,s,r,n,a),!0}for(d=1,l=new Array(u-1);d<u;d++)l[d-1]=arguments[d];c.fn.apply(c.context,l)}else{var h,f=c.length;for(d=0;d<f;d++)switch(c[d].once&&this.removeListener(e,c[d].fn,void 0,!0),u){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,t);break;case 3:c[d].fn.call(c[d].context,t,s);break;case 4:c[d].fn.call(c[d].context,t,s,r);break;default:if(!l)for(h=1,l=new Array(u-1);h<u;h++)l[h-1]=arguments[h];c[d].fn.apply(c[d].context,l)}}return!0},o.prototype.on=function(e,t,i){return n(this,e,t,i,!1)},o.prototype.once=function(e,t,i){return n(this,e,t,i,!0)},o.prototype.removeListener=function(e,t,s,r){var n=i?i+e:e;if(!this._events[n])return this;if(!t)return a(this,n),this;var o=this._events[n];if(o.fn)o.fn!==t||r&&!o.once||s&&o.context!==s||a(this,n);else{for(var l=0,d=[],c=o.length;l<c;l++)(o[l].fn!==t||r&&!o[l].once||s&&o[l].context!==s)&&d.push(o[l]);d.length?this._events[n]=1===d.length?d[0]:d:a(this,n)}return this},o.prototype.removeAllListeners=function(e){var t;return e?(t=i?i+e:e,this._events[t]&&a(this,t)):(this._events=new s,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=i,o.EventEmitter=o,e.exports=o}(er)),er.exports),ir=te(tr);const sr="1.6.14",rr={};function nr(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 ar(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 or(e,t){let i=0;return i=(127&e[t])<<21,i|=(127&e[t+1])<<14,i|=(127&e[t+2])<<7,i|=127&e[t+3],i}function lr(e,t){const i=t;let s=0;for(;ar(e,t);){s+=10;s+=or(e,t+6),nr(e,t+10)&&(s+=10),t+=s}if(s>0)return e.subarray(i,i+s)}function dr(e,t){return 255===e[t]&&240==(246&e[t+1])}function cr(e,t){return 1&e[t+1]?7:9}function ur(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function hr(e,t){return t+1<e.length&&dr(e,t)}function fr(e,t){if(hr(e,t)){const i=cr(e,t);if(t+i>=e.length)return!1;const s=ur(e,t);if(s<=i)return!1;const r=t+s;return r===e.length||hr(e,r)}return!1}function gr(e,t,i,s,r){if(!e.samplerate){const n=function(e,t,i,s){const r=t[i+2],n=r>>2&15;if(n>12){const t=new Error(`invalid ADTS sampling index:${n}`);return void e.emit(P.ERROR,P.ERROR,{type:k.MEDIA_ERROR,details:w.FRAG_PARSING_ERROR,fatal:!0,error:t,reason:t.message})}const a=1+(r>>6&3),o=t[i+3]>>6&3|(1&r)<<2,l="mp4a.40."+a,d=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][n];let c=n;5!==a&&29!==a||(c-=3);const u=[a<<3|(14&c)>>1,(1&c)<<7|o<<3];return z.log(`manifest codec:${s}, parsed codec:${l}, channels:${o}, rate:${d} (ADTS object type:${a} sampling index:${n})`),{config:u,samplerate:d,channelCount:o,codec:l,parsedCodec:l,manifestCodec:s}}(t,i,s,r);if(!n)return;$(e,n)}}function pr(e){return 9216e4/e}function mr(e,t,i,s,r){const n=s+r*pr(e.samplerate),a=function(e,t){const i=cr(e,t);if(t+i<=e.length){const s=ur(e,t)-i;if(s>0)return{headerLength:i,frameLength:s}}}(t,i);let o;if(a){const{frameLength:s,headerLength:r}=a,l=r+s,d=Math.max(0,i+l-t.length);d?(o=new Uint8Array(l-r),o.set(t.subarray(i+r,t.length),0)):o=t.subarray(i+r,i+l);const c={unit:o,pts:n};return d||e.samples.push(c),{sample:c,length:l,missing:d}}const l=t.length-i;o=new Uint8Array(l),o.set(t.subarray(i,t.length),0);return{sample:{unit:o,pts:n},length:l,missing:-1}}function vr(e,t){return ar(e,t)&&or(e,t+6)+10<=e.length-t}function yr(e,t=0,i=1/0){return function(e,t,i,s){const r=function(e){return e instanceof ArrayBuffer?e:e.buffer}(e);let n=1;"BYTES_PER_ELEMENT"in s&&(n=s.BYTES_PER_ELEMENT);const a=(u=e,u&&u.buffer instanceof ArrayBuffer&&void 0!==u.byteLength&&void 0!==u.byteOffset?e.byteOffset:0),o=(a+e.byteLength)/n,l=(a+t)/n,d=Math.floor(Math.max(0,Math.min(l,o))),c=Math.floor(Math.min(d+Math.max(i,0),o));var u;return new s(r,d,c-d)}(e,t,i,Uint8Array)}function Tr(e){const t={key:e.type,description:"",data:"",mimeType:null,pictureType:null};if(e.size<2)return;if(3!==e.data[0])return void console.log("Ignore frame with unrecognized character encoding");const i=e.data.subarray(1).indexOf(0);if(-1===i)return;const s=J(yr(e.data,1,i)),r=e.data[2+i],n=e.data.subarray(3+i).indexOf(0);if(-1===n)return;const a=J(yr(e.data,3+i,n));let o;return o="--\x3e"===s?J(yr(e.data,4+i+n)):function(e){return e instanceof ArrayBuffer?e:0==e.byteOffset&&e.byteLength==e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer}(e.data.subarray(4+i+n)),t.mimeType=s,t.pictureType=r,t.description=a,t.data=o,t}function Er(e){return"PRIV"===e.type?function(e){if(e.size<2)return;const t=J(e.data,!0),i=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:i.buffer}}(e):"W"===e.type[0]?function(e){if("WXXX"===e.type){if(e.size<2)return;let t=1;const i=J(e.data.subarray(t),!0);t+=i.length+1;const s=J(e.data.subarray(t));return{key:e.type,info:i,data:s}}const t=J(e.data);return{key:e.type,info:"",data:t}}(e):"APIC"===e.type?Tr(e):function(e){if(e.size<2)return;if("TXXX"===e.type){let t=1;const i=J(e.data.subarray(t),!0);t+=i.length+1;const s=J(e.data.subarray(t));return{key:e.type,info:i,data:s}}const t=J(e.data.subarray(1));return{key:e.type,info:"",data:t}}(e)}function Sr(e){const t=String.fromCharCode(e[0],e[1],e[2],e[3]),i=or(e,4);return{type:t,size:i,data:e.subarray(10,10+i)}}function Ar(e){let t=0;const i=[];for(;ar(e,t);){const s=or(e,t+6);e[t+5]>>6&1&&(t+=10),t+=10;const r=t+s;for(;t+10<r;){const s=Sr(e.subarray(t)),r=Er(s);r&&i.push(r),t+=s.size+10}nr(e,t)&&(t+=10)}return i}function br(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info}function Lr(e){if(8===e.data.byteLength){const t=new Uint8Array(e.data),i=1&t[3];let s=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return s/=45,i&&(s+=47721858.84),Math.round(s)}}function Rr(e){const t=Ar(e);for(let e=0;e<t.length;e++){const i=t[e];if(br(i))return Lr(i)}}let Ir=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 kr(e="",t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}class wr{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,i,s){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,i){}demux(e,t){this.cachedData&&(e=Ce(this.cachedData,e),this.cachedData=null);let i,s=lr(e,0),r=s?s.length:0;const n=this._audioTrack,a=this._id3Track,o=s?Rr(s):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&L(o))&&(this.basePTS=Pr(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),s&&s.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:Ir.audioId3,duration:Number.POSITIVE_INFINITY});r<l;){if(this.canParse(e,r)){const t=this.appendFrame(n,e,r);t?(this.frameIndex++,this.lastPTS=t.sample.pts,r+=t.length,i=r):r=l}else vr(e,r)?(s=lr(e,r),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:Ir.audioId3,duration:Number.POSITIVE_INFINITY}),r+=s.length,i=r):r++;if(r===l&&i!==l){const t=e.slice(i);this.cachedData?this.cachedData=Ce(this.cachedData,t):this.cachedData=t}}return{audioTrack:n,videoTrack:kr(),id3Track:a,textTrack:kr()}}demuxSampleAes(e,t,i){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:kr(),id3Track:this._id3Track,textTrack:kr()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const Pr=(e,t,i)=>{if(L(e))return 90*e;return 9e4*t+(i?9e4*i.baseTime/i.timescale:0)};let Dr=null;const xr=[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],Cr=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],_r=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Mr=[0,1,1,4];function Or(e,t,i,s,r){if(i+24>t.length)return;const n=Fr(t,i);if(n&&i+n.frameLength<=t.length){const a=s+r*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:t.subarray(i,i+n.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=n.channelCount,e.samplerate=n.sampleRate,e.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function Fr(e,t){const i=e[t+1]>>3&3,s=e[t+1]>>1&3,r=e[t+2]>>4&15,n=e[t+2]>>2&3;if(1!==i&&0!==r&&15!==r&&3!==n){const a=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*xr[14*(3===i?3-s:3===s?3:4)+r-1],d=Cr[3*(3===i?0:2===i?1:2)+n],c=3===o?1:2,u=_r[i][s],h=Mr[s],f=8*u*h,g=Math.floor(u*l/d+a)*h;if(null===Dr){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Dr=e?parseInt(e[1]):0}return!!Dr&&Dr<=87&&2===s&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:d,channelCount:c,frameLength:g,samplesPerFrame:f}}}function Ur(e,t){return!(255!==e[t]||224&~e[t+1]||!(6&e[t+1]))}function Nr(e,t){return t+1<e.length&&Ur(e,t)}function Br(e,t){if(t+1<e.length&&Ur(e,t)){const i=4,s=Fr(e,t);let r=i;null!=s&&s.frameLength&&(r=s.frameLength);const n=t+r;return n===e.length||Nr(e,n)}return!1}const $r=(e,t)=>{let i=0,s=5;t+=s;const r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;s>0;){a[0]=e[t];const o=Math.min(s,8),l=8-o;n[0]=4278190080>>>24+l<<l,r[0]=(a[0]&n[0])>>l,i=i?i<<o|r[0]:r[0],t+=1,s-=o}return i};class Vr extends wr{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,i){const s=Gr(e,t,i,this.basePTS,this.frameIndex);if(-1!==s){return{sample:e.samples[e.samples.length-1],length:s,missing:0}}}static probe(e){if(!e)return!1;const t=lr(e,0);if(!t)return!1;const i=t.length;return 11===e[i]&&119===e[i+1]&&void 0!==Rr(t)&&$r(e,i)<16}}function Gr(e,t,i,s,r){if(i+8>t.length)return-1;if(11!==t[i]||119!==t[i+1])return-1;const n=t[i+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=63&t[i+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+n];if(i+l>t.length)return-1;const d=t[i+6]>>5;let c=0;2===d?c+=2:(1&d&&1!==d&&(c+=2),4&d&&(c+=2));const u=(t[i+6]<<8|t[i+7])>>12-c&1,h=[2,1,2,3,3,4,4,5][d]+u,f=t[i+5]>>3,g=7&t[i+5],p=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|d<<3|u<<2|o>>4,o<<4&224]),m=s+r*(1536/a*9e4),v=t.subarray(i,i+l);return e.config=p,e.channelCount=h,e.samplerate=a,e.samples.push({unit:v,pts:m}),l}const Hr=/\/emsg[-/]ID3/i;function Kr(e,t){return L(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}class jr{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new di(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,ri)}decryptAacSample(e,t,i){const s=e[t].unit;if(s.length<=16)return;const r=s.subarray(16,s.length-s.length%16),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(n).then(r=>{const n=new Uint8Array(r);s.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)}).catch(i)}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length)return void i();if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=16*Math.floor((e.length-48)/160)+16,i=new Int8Array(t);let s=0;for(let t=32;t<e.length-16;t+=160,s+=16)i.set(e.subarray(t,t+16),s);return i}getAvcDecryptedUnit(e,t){const i=new Uint8Array(t);let s=0;for(let t=32;t<e.length-16;t+=160,s+=16)e.set(i.subarray(s,s+16),t);return e}decryptAvcSample(e,t,i,s,r){const n=Ue(r.data),a=this.getAvcEncryptedData(n);this.decryptBuffer(a.buffer).then(a=>{r.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,s)}).catch(s)}decryptAvcSamples(e,t,i,s){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length)return void s();const r=e[t].units;for(;!(i>=r.length);i++){const n=r[i];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(e,t,i,s,n),this.decrypter.isSync())))return}}}}class Wr{constructor(){this.VideoSample=null}createVideoSample(e,t,i){return{key:e,frame:!1,pts:t,dts:i,units:[],length:0}}getLastNalUnit(e){var t;let i,s=this.VideoSample;if(s&&0!==s.units.length||(s=e[e.length-1]),null!=(t=s)&&t.units){const e=s.units;i=e[e.length-1]}return i}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){const i=t.samples,s=i.length;if(!s)return void t.dropped++;{const t=i[s-1];e.pts=t.pts,e.dts=t.dts}}t.samples.push(e)}}parseNALu(e,t,i){const s=t.byteLength;let r=e.naluState||0;const n=r,a=[];let o,l,d,c=0,u=-1,h=0;for(-1===r&&(u=0,h=this.getNALuType(t,0),r=0,c=1);c<s;)if(o=t[c++],r)if(1!==r)if(o)if(1===o){if(l=c-r-1,u>=0){const e={data:t.subarray(u,l),type:h};a.push(e)}else{const i=this.getLastNalUnit(e.samples);i&&(n&&c<=4-n&&i.state&&(i.data=i.data.subarray(0,i.data.byteLength-n)),l>0&&(i.data=Ce(i.data,t.subarray(0,l)),i.state=0))}c<s?(d=this.getNALuType(t,c),u=c,h=d,r=0):r=-1}else r=0;else r=3;else r=o?0:2;else r=o?0:1;if(u>=0&&r>=0){const e={data:t.subarray(u,s),type:h,state:r};a.push(e)}if(0===a.length){const i=this.getLastNalUnit(e.samples);i&&(i.data=Ce(i.data,t))}return e.naluState=r,a}}class qr{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,i=e.byteLength-t,s=new Uint8Array(4),r=Math.min(4,t);if(0===r)throw new Error("no bytes available");s.set(e.subarray(i,i+r)),this.word=new DataView(s.buffer).getUint32(0),this.bitsAvailable=8*r,this.bytesAvailable-=r}skipBits(e){let t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(t=(e-=this.bitsAvailable)>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const i=this.word>>>32-t;if(e>32&&z.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return t=e-t,t>0&&this.bitsAvailable?i<<t|this.readBits(t):i}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class Yr extends Wr{parsePES(e,t,i,s){const r=this.parseNALu(e,i.data,s);let n,a=this.VideoSample,o=!1;i.data=null,a&&r.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),r.forEach(s=>{var r,l;switch(s.type){case 1:{let t=!1;n=!0;const r=s.data;if(o&&r.length>4){const e=this.readSliceType(r);2!==e&&4!==e&&7!==e&&9!==e||(t=!0)}var d;if(t)null!=(d=a)&&d.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null);a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.frame=!0,a.key=t;break}case 5:n=!0,null!=(r=a)&&r.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 6:n=!0,Fe(s.data,1,i.pts,t.samples);break;case 7:{var c,u;n=!0,o=!0;const t=s.data,i=this.readSPS(t);if(!e.sps||e.width!==i.width||e.height!==i.height||(null==(c=e.pixelRatio)?void 0:c[0])!==i.pixelRatio[0]||(null==(u=e.pixelRatio)?void 0:u[1])!==i.pixelRatio[1]){e.width=i.width,e.height=i.height,e.pixelRatio=i.pixelRatio,e.sps=[t];const s=t.subarray(1,4);let r="avc1.";for(let e=0;e<3;e++){let t=s[e].toString(16);t.length<2&&(t="0"+t),r+=t}e.codec=r}break}case 8:n=!0,e.pps=[s.data];break;case 9:n=!0,e.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:n=!0;break;default:n=!1}if(a&&n){a.units.push(s)}}),s&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,t){return 31&e[t]}readSliceType(e){const t=new qr(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let i,s=8,r=8;for(let n=0;n<e;n++)0!==r&&(i=t.readEG(),r=(s+i+256)%256),s=0===r?s:r}readSPS(e){const t=new qr(e);let i,s,r,n=0,a=0,o=0,l=0;const d=t.readUByte.bind(t),c=t.readBits.bind(t),u=t.readUEG.bind(t),h=t.readBoolean.bind(t),f=t.skipBits.bind(t),g=t.skipEG.bind(t),p=t.skipUEG.bind(t),m=this.skipScalingList.bind(this);d();const v=d();if(c(5),f(3),d(),p(),100===v||110===v||122===v||244===v||44===v||83===v||86===v||118===v||128===v){const e=u();if(3===e&&f(1),p(),p(),f(1),h())for(s=3!==e?8:12,r=0;r<s;r++)h()&&m(r<6?16:64,t)}p();const y=u();if(0===y)u();else if(1===y)for(f(1),g(),g(),i=u(),r=0;r<i;r++)g();p(),f(1);const T=u(),E=u(),S=c(1);0===S&&f(1),f(1),h()&&(n=u(),a=u(),o=u(),l=u());let A=[1,1];if(h()&&h()){switch(d()){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=[d()<<8|d(),d()<<8|d()]}}return{width:Math.ceil(16*(T+1)-2*n-2*a),height:(2-S)*(E+1)*16-(S?2:4)*(o+l),pixelRatio:A}}}class zr extends Wr{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,i,s){const r=this.parseNALu(e,i.data,s);let n,a=this.VideoSample,o=!1;i.data=null,a&&r.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),r.forEach(s=>{var r,l;switch(s.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),a.frame=!0,n=!0;break;case 16:case 17:case 18:case 21:var d;if(n=!0,o)null!=(d=a)&&d.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null);a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 19:case 20:n=!0,null!=(r=a)&&r.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 39:n=!0,Fe(s.data,2,i.pts,t.samples);break;case 32:n=!0,e.vps||("object"!=typeof e.params&&(e.params={}),e.params=$(e.params,this.readVPS(s.data)),this.initVPS=s.data),e.vps=[s.data];break;case 33:if(n=!0,o=!0,void 0===e.vps||e.vps[0]===this.initVPS||void 0===e.sps||this.matchSPS(e.sps[0],s.data)||(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const t=this.readSPS(s.data);e.width=t.width,e.height=t.height,e.pixelRatio=t.pixelRatio,e.codec=t.codecString,e.sps=[],"object"!=typeof e.params&&(e.params={});for(const i in t.params)e.params[i]=t.params[i]}this.pushParameterSet(e.sps,s.data,e.vps),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0;break;case 34:if(n=!0,"object"==typeof e.params){if(!e.pps){e.pps=[];const t=this.readPPS(s.data);for(const i in t)e.params[i]=t[i]}this.pushParameterSet(e.pps,s.data,e.vps)}break;case 35:n=!0,e.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;default:n=!1}if(a&&n){a.units.push(s)}}),s&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,i){(i&&i[0]===this.initVPS||!i&&!e.length)&&e.push(t)}getNALuType(e,t){return(126&e[t])>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let i=0;for(let s=0;s<e.byteLength;s++)s>=2&&3===e[s]&&0===e[s-1]&&0===e[s-2]||(t[i]=e[s],i++);return new Uint8Array(t.buffer,0,i)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new qr(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);return{numTemporalLayers:t.readBits(3)+1,temporalIdNested:t.readBoolean()}}readSPS(e){const t=new qr(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const i=t.readBits(3);t.readBoolean();const s=t.readBits(2),r=t.readBoolean(),n=t.readBits(5),a=t.readUByte(),o=t.readUByte(),l=t.readUByte(),d=t.readUByte(),c=t.readUByte(),u=t.readUByte(),h=t.readUByte(),f=t.readUByte(),g=t.readUByte(),p=t.readUByte(),m=t.readUByte(),v=[],y=[];for(let e=0;e<i;e++)v.push(t.readBoolean()),y.push(t.readBoolean());if(i>0)for(let e=i;e<8;e++)t.readBits(2);for(let e=0;e<i;e++)v[e]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),y[e]&&t.readUByte();t.readUEG();const T=t.readUEG();3==T&&t.skipBits(1);const E=t.readUEG(),S=t.readUEG(),A=t.readBoolean();let b=0,L=0,R=0,I=0;A&&(b+=t.readUEG(),L+=t.readUEG(),R+=t.readUEG(),I+=t.readUEG());const k=t.readUEG(),w=t.readUEG(),P=t.readUEG();for(let e=t.readBoolean()?0:i;e<=i;e++)t.skipUEG(),t.skipUEG(),t.skipUEG();t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.readBoolean()){if(t.readBoolean())for(let e=0;e<4;e++)for(let i=0;i<(3===e?2:6);i++){if(t.readBoolean()){const i=Math.min(64,1<<4+(e<<1));e>1&&t.readEG();for(let e=0;e<i;e++)t.readEG()}else t.readUEG()}}t.readBoolean(),t.readBoolean();t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const D=t.readUEG();let x=0;for(let e=0;e<D;e++){let i=!1;if(0!==e&&(i=t.readBoolean()),i){e===D&&t.readUEG(),t.readBoolean(),t.readUEG();let i=0;for(let e=0;e<=x;e++){const e=t.readBoolean();let s=!1;e||(s=t.readBoolean()),(e||s)&&i++}x=i}else{const e=t.readUEG(),i=t.readUEG();x=e+i;for(let i=0;i<e;i++)t.readUEG(),t.readBoolean();for(let e=0;e<i;e++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const e=t.readUEG();for(let i=0;i<e;i++){for(let e=0;e<P+4;e++)t.readBits(1);t.readBits(1)}}let C=0,_=1,M=1,O=!0,F=1,U=0;t.readBoolean(),t.readBoolean();let N=!1;if(t.readBoolean()){if(t.readBoolean()){const e=t.readUByte();e>0&&e<16?(_=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][e-1],M=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][e-1]):255===e&&(_=t.readBits(16),M=t.readBits(16))}t.readBoolean()&&t.readBoolean();if(t.readBoolean()){t.readBits(3),t.readBoolean();t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())}t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),N=t.readBoolean(),N&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG());if(t.readBoolean()){F=t.readBits(32),U=t.readBits(32);t.readBoolean()&&t.readUEG();if(t.readBoolean()){const e=t.readBoolean(),s=t.readBoolean();let r=!1;(e||s)&&(r=t.readBoolean(),r&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),r&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let n=0;n<=i;n++){O=t.readBoolean();let i=!1;O||t.readBoolean()?t.readEG():i=t.readBoolean();const n=i?1:t.readUEG()+1;if(e)for(let e=0;e<n;e++)t.readUEG(),t.readUEG(),r&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(s)for(let e=0;e<n;e++)t.readUEG(),t.readUEG(),r&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),C=t.readUEG())}let B=E,$=S;if(A){let e=1,t=1;1===T?e=t=2:2==T&&(e=2),B=E-e*L-e*b,$=S-t*I-t*R}const V=s?["A","B","C"][s]:"",G=a<<24|o<<16|l<<8|d;let H=0;for(let e=0;e<32;e++)H=(H|(G>>e&1)<<31-e)>>>0;let K=H.toString(16);1===n&&"2"===K&&(K="6");return{codecString:`hvc1.${V}${n}.${K}.${r?"H":"L"}${m}.B0`,params:{general_tier_flag:r,general_profile_idc:n,general_profile_space:s,general_profile_compatibility_flags:[a,o,l,d],general_constraint_indicator_flags:[c,u,h,f,g,p],general_level_idc:m,bit_depth:k+8,bit_depth_luma_minus8:k,bit_depth_chroma_minus8:w,min_spatial_segmentation_idc:C,chroma_format_idc:T,frame_rate:{fixed:O,fps:U/F}},width:B,height:$,pixelRatio:[_,M]}}readPPS(e){const t=new qr(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);const i=t.readBoolean(),s=t.readBoolean();let r=1;return s&&i?r=0:s?r=3:i&&(r=2),{parallelismType:r}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const Xr=188;class Qr{constructor(e,t,i,s){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.logger=s,this.videoParser=null}static probe(e,t){const i=Qr.syncOffset(e);return i>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),-1!==i}static syncOffset(e){const t=e.length;let i=Math.min(940,t-Xr)+1,s=0;for(;s<i;){let r=!1,n=-1,a=0;for(let o=s;o<t;o+=Xr){if(71!==e[o]||t-o!==Xr&&71!==e[o+Xr]){if(a)return-1;break}if(a++,-1===n&&(n=o,0!==n&&(i=Math.min(n+18612,e.length-Xr)+1)),r||(r=0===Jr(e,o)),r&&a>1&&(0===n&&a>2||o+Xr>i))return n}s++}return-1}static createTrack(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:me[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}resetInitSegment(e,t,i,s){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=Qr.createTrack("video"),this._videoTrack.duration=s,this._audioTrack=Qr.createTrack("audio",s),this._id3Track=Qr.createTrack("id3"),this._txtTrack=Qr.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,i=!1,s=!1){let r;i||(this.sampleAes=null);const n=this._videoTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let d=n.pid,c=n.pesData,u=a.pid,h=o.pid,f=a.pesData,g=o.pesData,p=null,m=this.pmtParsed,v=this._pmtId,y=e.length;if(this.remainderData&&(y=(e=Ce(this.remainderData,e)).length,this.remainderData=null),y<Xr&&!s)return this.remainderData=e,{audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};const T=Math.max(0,Qr.syncOffset(e));y-=(y-T)%Xr,y<e.byteLength&&!s&&(this.remainderData=new Uint8Array(e.buffer,y,e.buffer.byteLength-y));let E=0;for(let t=T;t<y;t+=Xr)if(71===e[t]){const s=!!(64&e[t+1]),y=Jr(e,t);let E;if((48&e[t+3])>>4>1){if(E=t+5+e[t+4],E===t+Xr)continue}else E=t+4;switch(y){case d:s&&(c&&(r=rn(c,this.logger))&&(this.readyVideoParser(n.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(n,l,r,!1)),c={data:[],size:0}),c&&(c.data.push(e.subarray(E,t+Xr)),c.size+=t+Xr-E);break;case u:if(s){if(f&&(r=rn(f,this.logger)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,r);break;case"mp3":this.parseMPEGPES(a,r);break;case"ac3":this.parseAC3PES(a,r)}f={data:[],size:0}}f&&(f.data.push(e.subarray(E,t+Xr)),f.size+=t+Xr-E);break;case h:s&&(g&&(r=rn(g,this.logger))&&this.parseID3PES(o,r),g={data:[],size:0}),g&&(g.data.push(e.subarray(E,t+Xr)),g.size+=t+Xr-E);break;case 0:s&&(E+=e[E]+1),v=this._pmtId=Zr(e,E);break;case v:{s&&(E+=e[E]+1);const r=en(e,E,this.typeSupported,i,this.observer,this.logger);d=r.videoPid,d>0&&(n.pid=d,n.segmentCodec=r.segmentVideoCodec),u=r.audioPid,u>0&&(a.pid=u,a.segmentCodec=r.segmentAudioCodec),h=r.id3Pid,h>0&&(o.pid=h),null===p||m||(this.logger.warn(`MPEG-TS PMT found at ${t} after unknown PID '${p}'. Backtracking to sync byte @${T} to parse all TS packets.`),p=null,t=T-188),m=this.pmtParsed=!0;break}case 17:case 8191:break;default:p=y}}else E++;E>0&&tn(this.observer,new Error(`Found ${E} TS packet/s that do not start with 0x47`),void 0,this.logger),n.pesData=c,a.pesData=f,o.pesData=g;const S={audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};return s&&this.extractRemainingSamples(S),S}flush(){const{remainderData:e}=this;let t;return this.remainderData=null,t=e?this.demux(e,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:i,id3Track:s,textTrack:r}=e,n=i.pesData,a=t.pesData,o=s.pesData;let l;if(n&&(l=rn(n,this.logger))?(this.readyVideoParser(i.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(i,r,l,!0),i.pesData=null)):i.pesData=n,a&&(l=rn(a,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l);break;case"ac3":this.parseAC3PES(t,l)}t.pesData=null}else null!=a&&a.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=a;o&&(l=rn(o,this.logger))?(this.parseID3PES(s,l),s.pesData=null):s.pesData=o}demuxSampleAes(e,t,i){const s=this.demux(e,i,!0,!this.config.progressive),r=this.sampleAes=new jr(this.observer,this.config,t);return this.decrypt(s,r)}readyVideoParser(e){null===this.videoParser&&("avc"===e?this.videoParser=new Yr:"hevc"===e&&(this.videoParser=new zr))}decrypt(e,t){return new Promise(i=>{const{audioTrack:s,videoTrack:r}=e;s.samples&&"aac"===s.segmentCodec?t.decryptAacSamples(s.samples,0,()=>{r.samples?t.decryptAvcSamples(r.samples,0,0,()=>{i(e)}):i(e)}):r.samples&&t.decryptAvcSamples(r.samples,0,0,()=>{i(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let i=0;const s=this.aacOverFlow;let r,n,a,o=t.data;if(s){this.aacOverFlow=null;const t=s.missing,r=s.sample.unit.byteLength;if(-1===t)o=Ce(s.sample.unit,o);else{const n=r-t;s.sample.unit.set(o.subarray(0,t),n),e.samples.push(s.sample),i=s.missing}}for(r=i,n=o.length;r<n-1&&!hr(o,r);r++);if(r!==i){let e;const t=r<n-1;if(e=t?`AAC PES did not start with ADTS header,offset:${r}`:"No ADTS header found in AAC PES",tn(this.observer,new Error(e),t,this.logger),!t)return}if(gr(e,this.observer,o,r,this.audioCodec),void 0!==t.pts)a=t.pts;else{if(!s)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const t=pr(e.samplerate);a=s.sample.pts+t}}let l,d=0;for(;r<n;){if(l=mr(e,o,r,a,d),r+=l.length,l.missing){this.aacOverFlow=l;break}for(d++;r<n-1&&!hr(o,r);r++);}}parseMPEGPES(e,t){const i=t.data,s=i.length;let r=0,n=0;const a=t.pts;if(void 0!==a)for(;n<s;)if(Nr(i,n)){const t=Or(e,i,n,a,r);if(!t)break;n+=t.length,r++}else n++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(e,t){{const i=t.data,s=t.pts;if(void 0===s)return void this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");const r=i.length;let n,a=0,o=0;for(;o<r&&(n=Gr(e,i,o,s,a++))>0;)o+=n}}parseID3PES(e,t){if(void 0===t.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const i=$({},t,{type:this._videoTrack?Ir.emsg:Ir.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}}function Jr(e,t){return((31&e[t+1])<<8)+e[t+2]}function Zr(e,t){return(31&e[t+10])<<8|e[t+11]}function en(e,t,i,s,r,n){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t<o;){const o=Jr(e,t),l=(15&e[t+3])<<8|e[t+4];switch(e[t]){case 207:if(!s){sn("ADTS AAC",n);break}case 15:-1===a.audioPid&&(a.audioPid=o);break;case 21:-1===a.id3Pid&&(a.id3Pid=o);break;case 219:if(!s){sn("H.264",n);break}case 27:-1===a.videoPid&&(a.videoPid=o);break;case 3:case 4:i.mpeg||i.mp3?-1===a.audioPid&&(a.audioPid=o,a.segmentAudioCodec="mp3"):n.log("MPEG audio found, not supported in this browser");break;case 193:if(!s){sn("AC-3",n);break}case 129:i.ac3?-1===a.audioPid&&(a.audioPid=o,a.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===a.audioPid&&l>0){let s=t+5,r=l;for(;r>2;){if(106===e[s])!0!==i.ac3?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=o,a.segmentAudioCodec="ac3");const t=e[s+1]+2;s+=t,r-=t}}break;case 194:case 135:return tn(r,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:-1===a.videoPid&&(a.videoPid=o,a.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"))}t+=l+5}return a}function tn(e,t,i,s){s.warn(`parsing error: ${t.message}`),e.emit(P.ERROR,P.ERROR,{type:k.MEDIA_ERROR,details:w.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,error:t,reason:t.message})}function sn(e,t){t.log(`${e} with AES-128-CBC encryption found in unencrypted stream`)}function rn(e,t){let i,s,r,n,a,o=0;const l=e.data;if(!e||0===e.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=Ce(l[0],l[1]),l.splice(1,1);i=l[0];if(1===(i[0]<<16)+(i[1]<<8)+i[2]){if(s=(i[4]<<8)+i[5],s&&s>e.size-6)return null;const d=i[7];192&d&&(n=536870912*(14&i[9])+4194304*(255&i[10])+16384*(254&i[11])+128*(255&i[12])+(254&i[13])/2,64&d?(a=536870912*(14&i[14])+4194304*(255&i[15])+16384*(254&i[16])+128*(255&i[17])+(254&i[18])/2,n-a>54e5&&(t.warn(`${Math.round((n-a)/9e4)}s delta between PTS and DTS, align them`),n=a)):a=n),r=i[8];let c=r+9;if(e.size<=c)return null;e.size-=c;const u=new Uint8Array(e.size);for(let e=0,t=l.length;e<t;e++){i=l[e];let t=i.byteLength;if(c){if(c>t){c-=t;continue}i=i.subarray(c),t-=c,c=0}u.set(i,o),o+=t}return s&&(s-=r+3),{data:u,pts:n,dts:a,len:s}}return null}class nn{static getSilentFrame(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}}const an=Math.pow(2,32)-1;class on{static init(){let e;for(e in on.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},on.types)on.types.hasOwnProperty(e)&&(on.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),i=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);on.HDLR_TYPES={video:t,audio:i};const s=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),r=new Uint8Array([0,0,0,0,0,0,0,0]);on.STTS=on.STSC=on.STCO=r,on.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),on.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),on.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),on.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const n=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),o=new Uint8Array([0,0,0,1]);on.FTYP=on.box(on.types.ftyp,n,o,n,a),on.DINF=on.box(on.types.dinf,on.box(on.types.dref,s))}static box(e,...t){let i=8,s=t.length;const r=s;for(;s--;)i+=t[s].byteLength;const n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=255&i,n.set(e,4),s=0,i=8;s<r;s++)n.set(t[s],i),i+=t[s].byteLength;return n}static hdlr(e){return on.box(on.types.hdlr,on.HDLR_TYPES[e])}static mdat(e){return on.box(on.types.mdat,e)}static mdhd(e,t){t*=e;const i=Math.floor(t/(an+1)),s=Math.floor(t%(an+1));return on.box(on.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,s>>24,s>>16&255,s>>8&255,255&s,85,196,0,0]))}static mdia(e){return on.box(on.types.mdia,on.mdhd(e.timescale||0,e.duration||0),on.hdlr(e.type),on.minf(e))}static mfhd(e){return on.box(on.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))}static minf(e){return"audio"===e.type?on.box(on.types.minf,on.box(on.types.smhd,on.SMHD),on.DINF,on.stbl(e)):on.box(on.types.minf,on.box(on.types.vmhd,on.VMHD),on.DINF,on.stbl(e))}static moof(e,t,i){return on.box(on.types.moof,on.mfhd(e),on.traf(i,t))}static moov(e){let t=e.length;const i=[];for(;t--;)i[t]=on.trak(e[t]);return on.box.apply(null,[on.types.moov,on.mvhd(e[0].timescale||0,e[0].duration||0)].concat(i).concat(on.mvex(e)))}static mvex(e){let t=e.length;const i=[];for(;t--;)i[t]=on.trex(e[t]);return on.box.apply(null,[on.types.mvex,...i])}static mvhd(e,t){t*=e;const i=Math.floor(t/(an+1)),s=Math.floor(t%(an+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,s>>24,s>>16&255,s>>8&255,255&s,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 on.box(on.types.mvhd,r)}static sdtp(e){const t=e.samples||[],i=new Uint8Array(4+t.length);let s,r;for(s=0;s<t.length;s++)r=t[s].flags,i[s+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return on.box(on.types.sdtp,i)}static stbl(e){return on.box(on.types.stbl,on.stsd(e),on.box(on.types.stts,on.STTS),on.box(on.types.stsc,on.STSC),on.box(on.types.stsz,on.STSZ),on.box(on.types.stco,on.STCO))}static avc1(e){let t,i,s,r=[],n=[];for(t=0;t<e.sps.length;t++)i=e.sps[t],s=i.byteLength,r.push(s>>>8&255),r.push(255&s),r=r.concat(Array.prototype.slice.call(i));for(t=0;t<e.pps.length;t++)i=e.pps[t],s=i.byteLength,n.push(s>>>8&255),n.push(255&s),n=n.concat(Array.prototype.slice.call(i));const a=on.box(on.types.avcC,new Uint8Array([1,r[3],r[4],r[5],255,224|e.sps.length].concat(r).concat([e.pps.length]).concat(n))),o=e.width,l=e.height,d=e.pixelRatio[0],c=e.pixelRatio[1];return on.box(on.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,o>>8&255,255&o,l>>8&255,255&l,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),a,on.box(on.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),on.box(on.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,c>>24,c>>16&255,c>>8&255,255&c])))}static esds(e){const t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,255&t,0,0])}static mp4a(e){return on.box(on.types.mp4a,on.audioStsd(e),on.box(on.types.esds,on.esds(e)))}static mp3(e){return on.box(on.types[".mp3"],on.audioStsd(e))}static ac3(e){return on.box(on.types["ac-3"],on.audioStsd(e),on.box(on.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if("audio"===e.type){if("aac"===t)return on.box(on.types.stsd,on.STSD,on.mp4a(e));if("ac3"===t&&e.config)return on.box(on.types.stsd,on.STSD,on.ac3(e));if("mp3"===t&&"mp3"===e.codec)return on.box(on.types.stsd,on.STSD,on.mp3(e))}else{if(!e.pps||!e.sps)throw new Error("video track missing pps or sps");if("avc"===t)return on.box(on.types.stsd,on.STSD,on.avc1(e));if("hevc"===t&&e.vps)return on.box(on.types.stsd,on.STSD,on.hvc1(e))}throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){const t=e.id,i=(e.duration||0)*(e.timescale||0),s=e.width||0,r=e.height||0,n=Math.floor(i/(an+1)),a=Math.floor(i%(an+1));return on.box(on.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,s>>8&255,255&s,0,0,r>>8&255,255&r,0,0]))}static traf(e,t){const i=on.sdtp(e),s=e.id,r=Math.floor(t/(an+1)),n=Math.floor(t%(an+1));return on.box(on.types.traf,on.box(on.types.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s])),on.box(on.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,n>>24,n>>16&255,n>>8&255,255&n])),on.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,on.box(on.types.trak,on.tkhd(e),on.mdia(e))}static trex(e){const t=e.id;return on.box(on.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const i=e.samples||[],s=i.length,r=12+16*s,n=new Uint8Array(r);let a,o,l,d,c,u;for(t+=8+r,n.set(["video"===e.type?1:0,0,15,1,s>>>24&255,s>>>16&255,s>>>8&255,255&s,t>>>24&255,t>>>16&255,t>>>8&255,255&t],0),a=0;a<s;a++)o=i[a],l=o.duration,d=o.size,c=o.flags,u=o.cts,n.set([l>>>24&255,l>>>16&255,l>>>8&255,255&l,d>>>24&255,d>>>16&255,d>>>8&255,255&d,c.isLeading<<2|c.dependsOn,c.isDependedOn<<6|c.hasRedundancy<<4|c.paddingValue<<1|c.isNonSync,61440&c.degradPrio,15&c.degradPrio,u>>>24&255,u>>>16&255,u>>>8&255,255&u],12+16*a);return on.box(on.types.trun,n)}static initSegment(e){on.types||on.init();const t=on.moov(e);return Ce(on.FTYP,t)}static hvc1(e){const t=e.params,i=[e.vps,e.sps,e.pps],s=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),3|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),i.length]);let r=s.length;for(let e=0;e<i.length;e+=1){r+=3;for(let t=0;t<i[e].length;t+=1)r+=2+i[e][t].length}const n=new Uint8Array(r);n.set(s,0),r=s.length;const a=i.length-1;for(let e=0;e<i.length;e+=1){n.set(new Uint8Array([32+e|(e===a?128:0),0,i[e].length]),r),r+=3;for(let t=0;t<i[e].length;t+=1)n.set(new Uint8Array([i[e][t].length>>8,255&i[e][t].length]),r),r+=2,n.set(i[e][t],r),r+=i[e][t].length}const o=on.box(on.types.hvcC,n),l=e.width,d=e.height,c=e.pixelRatio[0],u=e.pixelRatio[1];return on.box(on.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,255&l,d>>8&255,255&d,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,on.box(on.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),on.box(on.types.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,255&c,u>>24,u>>16&255,u>>8&255,255&u])))}}on.types=void 0,on.HDLR_TYPES=void 0,on.STTS=void 0,on.STSC=void 0,on.STCO=void 0,on.STSZ=void 0,on.VMHD=void 0,on.SMHD=void 0,on.STSD=void 0,on.FTYP=void 0,on.DINF=void 0;function ln(e,t,i=1,s=!1){const r=e*t*i;return s?Math.round(r):r}function dn(e,t=!1){return ln(e,1e3,1/9e4,t)}function cn(e){const{baseTime:t,timescale:i,trackId:s}=e;return`${t/i} (${t}/${i}) trackId: ${s}`}let un,hn=null,fn=null;function gn(e,t,i,s){return{duration:t,size:i,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}class pn extends H{constructor(e,t,i,s){if(super("mp4-remuxer",s),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.ISGenerated=!1,null===hn){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);hn=e?parseInt(e[1]):0}if(null===fn){const e=navigator.userAgent.match(/Safari\/(\d+)/i);fn=e?parseInt(e[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const t=this._initPTS;t&&e&&e.trackId===t.trackId&&e.baseTime===t.baseTime&&e.timescale===t.timescale||this.log(`Reset initPTS: ${t?cn(t):t} > ${e?cn(e):e}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const i=e[0].pts,s=e.reduce((e,s)=>{let r=s.pts,n=r-e;return n<-4294967296&&(t=!0,r=mn(r,i),n=r-e),n>0?e:r},i);return t&&this.debug("PTS rollover detected"),s}remux(e,t,i,s,r,n,a,o){let l,d,c,u,h,f,g=r,p=r;const m=e.pid>-1,v=t.pid>-1,y=t.samples.length,T=e.samples.length>0,E=a&&y>0||y>1;if((!m||T)&&(!v||E)||this.ISGenerated||a){if(this.ISGenerated){var S,A,b,L;const e=this.videoTrackConfig;(e&&(t.width!==e.width||t.height!==e.height||(null==(S=t.pixelRatio)?void 0:S[0])!==(null==(A=e.pixelRatio)?void 0:A[0])||(null==(b=t.pixelRatio)?void 0:b[1])!==(null==(L=e.pixelRatio)?void 0:L[1]))||!e&&E||null===this.nextAudioTs&&T)&&this.resetInitSegment()}this.ISGenerated||(c=this.generateIS(e,t,r,n));const i=this.isVideoContiguous;let s,a=-1;if(E&&(a=function(e){for(let t=0;t<e.length;t++)if(e[t].key)return t;return-1}(t.samples),!i&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,a>0){this.warn(`Dropped ${a} out of ${y} video samples due to a missing keyframe`);const e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(a),t.dropped+=a,p+=(t.samples[0].pts-e)/t.inputTimeScale,s=p}else-1===a&&(this.warn(`No keyframe found out of ${y} video samples`),f=!1);if(this.ISGenerated){if(T&&E){const i=this.getVideoStartPts(t.samples),s=(mn(e.samples[0].pts,i)-i)/t.inputTimeScale;g+=Math.max(0,s),p+=Math.max(0,-s)}if(T){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),c=this.generateIS(e,t,r,n)),d=this.remuxAudio(e,g,this.isAudioContiguous,n,v||E||o===O?p:void 0),E){const s=d?d.endPTS-d.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),c=this.generateIS(e,t,r,n)),l=this.remuxVideo(t,p,i,s)}}else E&&(l=this.remuxVideo(t,p,i,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=s)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(h=vn(i,r,this._initPTS,this._initDTS)),s.samples.length&&(u=yn(s,r,this._initPTS))),{audio:d,video:l,initSegment:c,independent:f,text:u,id3:h}}computeInitPts(e,t,i,s){const r=Math.round(i*t);let n=mn(e,r);if(n<r+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-n)/t} ${s}`);n<r+t;)n+=8589934592;return n-r}generateIS(e,t,i,s){const r=e.samples,n=t.samples,a=this.typeSupported,o={},l=this._initPTS;let d,c,u,h=!l||s,f="audio/mp4",g=-1;if(h&&(d=c=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}o.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&a.mpeg?new Uint8Array(0):on.initSegment([e]),metadata:{channelCount:e.channelCount}},h&&(g=e.id,u=e.inputTimeScale,l&&u===l.timescale?h=!1:d=c=this.computeInitPts(r[0].pts,u,i,"audio"))}if(t.sps&&t.pps&&n.length){if(t.timescale=t.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:on.initSegment([t]),metadata:{width:t.width,height:t.height}},h)if(g=t.id,u=t.inputTimeScale,l&&u===l.timescale)h=!1;else{const e=this.getVideoStartPts(n),t=mn(n[0].dts,e),s=this.computeInitPts(t,u,i,"video"),r=this.computeInitPts(e,u,i,"video");c=Math.min(c,s),d=Math.min(d,r)}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,h?(l&&this.warn(`Timestamps at playlist time: ${s?"":"~"}${i} ${d/u} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${i} offset: ${d/u} (${d}/${u}) trackId: ${g}`),this._initPTS={baseTime:d,timescale:u,trackId:g},this._initDTS={baseTime:c,timescale:u,trackId:g}):d=u=void 0,{tracks:o,initPTS:d,timescale:u,trackId:g}}remuxVideo(e,t,i,s){const r=e.inputTimeScale,n=e.samples,a=[],o=n.length,l=this._initPTS,d=l.baseTime*r/l.timescale;let c,u,h=this.nextVideoTs,f=8,g=this.videoSampleDuration,p=Number.POSITIVE_INFINITY,m=Number.NEGATIVE_INFINITY,v=!1;if(!i||null===h){const e=d+t*r,s=n[0].pts-mn(n[0].dts,n[0].pts);hn&&null!==h&&Math.abs(e-s-(h+d))<15e3?i=!0:h=e-s-d}const y=h+d;for(let e=0;e<o;e++){const t=n[e];t.pts=mn(t.pts,y),t.dts=mn(t.dts,y),t.dts<n[e>0?e-1:e].dts&&(v=!0)}v&&n.sort(function(e,t){const i=e.dts-t.dts,s=e.pts-t.pts;return i||s}),c=n[0].dts,u=n[n.length-1].dts;const T=u-c,E=T?Math.round(T/(o-1)):g||e.inputTimeScale/30;if(i){const i=c-y,s=i>E,r=i<-1;if((s||r)&&(s?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${dn(i,!0)} ms (${i}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${dn(-i,!0)} ms (${i}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!r||y>=n[0].pts||hn)){c=y;const e=n[0].pts-i;if(s)n[0].dts=c,n[0].pts=e;else{let t=!0;for(let s=0;s<n.length&&!(n[s].dts>e&&t);s++){const e=n[s].pts;if(n[s].dts-=i,n[s].pts-=i,s<n.length-1){const i=n[s+1].pts;t=i<=n[s].pts==i<=e}}}this.log(`Video: Initial PTS/DTS adjusted: ${dn(e,!0)}/${dn(c,!0)}, delta: ${dn(i,!0)} ms`)}}c=Math.max(0,c);let S=0,A=0,b=c;for(let e=0;e<o;e++){const t=n[e],i=t.units,s=i.length;let r=0;for(let e=0;e<s;e++)r+=i[e].data.length;A+=r,S+=s,t.length=r,t.dts<b?(t.dts=b,b+=E/4|0||1):b=t.dts,p=Math.min(t.pts,p),m=Math.max(t.pts,m)}u=n[o-1].dts;const L=A+4*S+8;let R;try{R=new Uint8Array(L)}catch(e){return void this.observer.emit(P.ERROR,P.ERROR,{type:k.MUX_ERROR,details:w.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:L,reason:`fail allocating video mdat ${L}`})}const I=new DataView(R.buffer);I.setUint32(0,L),R.set(on.types.mdat,4);let D=!1,x=Number.POSITIVE_INFINITY,C=Number.POSITIVE_INFINITY,_=Number.NEGATIVE_INFINITY,M=Number.NEGATIVE_INFINITY;for(let e=0;e<o;e++){const t=n[e],i=t.units;let l,c=0;for(let e=0,t=i.length;e<t;e++){const t=i[e],s=t.data,r=t.data.byteLength;I.setUint32(f,r),f+=4,R.set(s,f),f+=r,c+=4+r}if(e<o-1)g=n[e+1].dts-t.dts,l=n[e+1].pts-t.pts;else{const i=this.config,a=e>0?t.dts-n[e-1].dts:E;if(l=e>0?t.pts-n[e-1].pts:E,i.stretchShortVideoTrack&&null!==this.nextAudioTs){const e=Math.floor(i.maxBufferHole*r),n=(s?p+s*r:this.nextAudioTs+d)-t.pts;n>e?(g=n-a,g<0?g=a:D=!0,this.log(`It is approximately ${n/90} ms to the next segment; using duration ${g/90} ms for the last video frame.`)):g=a}else g=a}const u=Math.round(t.pts-t.dts);x=Math.min(x,g),_=Math.max(_,g),C=Math.min(C,l),M=Math.max(M,l),a.push(gn(t.key,g,c,u))}if(a.length)if(hn){if(hn<70){const e=a[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(fn&&M-C<_-x&&E/_<.025&&0===a[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let e=c;for(let t=0,i=a.length;t<i;t++){const s=e+a[t].duration,r=e+a[t].cts;if(t<i-1){const e=s+a[t+1].cts;a[t].duration=e-r}else a[t].duration=t?a[t-1].duration:E;a[t].cts=0,e=s}}g=D||!g?E:g;const O=u+g;this.nextVideoTs=h=O-d,this.videoSampleDuration=g,this.isVideoContiguous=!0;const F={data1:on.moof(e.sequenceNumber++,c,$(e,{samples:a})),data2:R,startPTS:(p-d)/r,endPTS:(m+g-d)/r,startDTS:(c-d)/r,endDTS:h/r,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:e.dropped};return e.samples=[],e.dropped=0,F}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(e,t,i,s,r){const n=e.inputTimeScale,a=n/(e.samplerate?e.samplerate:n),o=this.getSamplesPerFrame(e),l=o*a,d=this._initPTS,c="mp3"===e.segmentCodec&&this.typeSupported.mpeg,u=[],h=void 0!==r;let f=e.samples,g=c?0:8,p=this.nextAudioTs||-1;const m=d.baseTime*n/d.timescale,v=m+t*n;if(this.isAudioContiguous=i=i||f.length&&p>0&&(s&&Math.abs(v-(p+m))<9e3||Math.abs(mn(f[0].pts,v)-(p+m))<20*l),f.forEach(function(e){e.pts=mn(e.pts,v)}),!i||p<0){const e=f.length;if(f=f.filter(e=>e.pts>=0),e!==f.length&&this.warn(`Removed ${f.length-e} of ${e} samples (initPTS ${m} / ${n})`),!f.length)return;p=0===r?0:s&&!h?Math.max(0,v-m):f[0].pts-m}if("aac"===e.segmentCodec){const t=this.config.maxAudioFramesDrift;for(let i=0,s=p+m;i<f.length;i++){const r=f[i],a=r.pts,o=a-s,d=Math.abs(1e3*o/n);if(o<=-t*l&&h)0===i&&(this.warn(`Audio frame @ ${(a/n).toFixed(3)}s overlaps marker by ${Math.round(1e3*o/n)} ms.`),this.nextAudioTs=p=a-m,s=a);else if(o>=t*l&&d<1e4&&h){let t=Math.round(o/l);for(s=a-t*l;s<0&&t&&l;)t--,s+=l;0===i&&(this.nextAudioTs=p=s-m),this.warn(`Injecting ${t} audio frames @ ${((s-m)/n).toFixed(3)}s due to ${Math.round(1e3*o/n)} ms gap.`);for(let n=0;n<t;n++){let t=nn.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);t||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),t=r.unit.subarray()),f.splice(i,0,{unit:t,pts:s}),s+=l,i++}}r.pts=s,s+=l}}let y,T=null,E=null,S=0,A=f.length;for(;A--;)S+=f[A].unit.byteLength;for(let t=0,s=f.length;t<s;t++){const s=f[t],r=s.unit;let n=s.pts;if(null!==E){u[t-1].duration=Math.round((n-E)/a)}else{if(i&&"aac"===e.segmentCodec&&(n=p+m),T=n,!(S>0))return;S+=g;try{y=new Uint8Array(S)}catch(e){return void this.observer.emit(P.ERROR,P.ERROR,{type:k.MUX_ERROR,details:w.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:S,reason:`fail allocating audio mdat ${S}`})}if(!c){new DataView(y.buffer).setUint32(0,S),y.set(on.types.mdat,4)}}y.set(r,g);const l=r.byteLength;g+=l,u.push(gn(!0,o,l,0)),E=n}const b=u.length;if(!b)return;const L=u[u.length-1];p=E-m,this.nextAudioTs=p+a*L.duration;const R=c?new Uint8Array(0):on.moof(e.sequenceNumber++,T/a,$({},e,{samples:u}));e.samples=[];const I=(T-m)/n,D=p/n,x={data1:R,data2:y,startPTS:I,endPTS:D,startDTS:I,endDTS:D,type:"audio",hasAudio:!0,hasVideo:!1,nb:b};return this.isAudioContiguous=!0,x}}function mn(e,t){let i;if(null===t)return e;for(i=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=i;return e}function vn(e,t,i,s){const r=e.samples.length;if(!r)return;const n=e.inputTimeScale;for(let a=0;a<r;a++){const r=e.samples[a];r.pts=mn(r.pts-i.baseTime*n/i.timescale,t*n)/n,r.dts=mn(r.dts-s.baseTime*n/s.timescale,t*n)/n}const a=e.samples;return e.samples=[],{samples:a}}function yn(e,t,i){const s=e.samples.length;if(!s)return;const r=e.inputTimeScale;for(let n=0;n<s;n++){const s=e.samples[n];s.pts=mn(s.pts-i.baseTime*r/i.timescale,t*r)/r}e.samples.sort((e,t)=>e.pts-t.pts);const n=e.samples;return e.samples=[],{samples:n}}function Tn(e,t,i=!1){return void 0!==(null==e?void 0:e.start)?(e.start+(i?e.duration:0))/e.timescale:t}function En(e,t,i){const s=e.codec;if(s&&s.length>4)return s;if(t===ae){if("ec-3"===s||"ac-3"===s||"alac"===s)return s;if("fLaC"===s||"Opus"===s){return Xe(s,!1)}return i.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"}return i.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1"}try{un=self.performance.now.bind(self.performance)}catch(e){un=Date.now}const Sn=[{demux:class{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,i,s){const r=this.videoTrack=kr("video",1),n=this.audioTrack=kr("audio",1),a=this.txtTrack=kr("text",1);if(this.id3Track=kr("id3",1),this.timeOffset=0,null==e||!e.byteLength)return;const o=Le(e);if(o.video){const{id:e,timescale:t,codec:i,supplemental:s}=o.video;r.id=e,r.timescale=a.timescale=t,r.codec=i,r.supplemental=s}if(o.audio){const{id:e,timescale:t,codec:i}=o.audio;n.id=e,n.timescale=t,n.codec=i}a.id=me.text,r.sampleDuration=0,r.duration=n.duration=s}resetContiguity(){this.remainderData=null}static probe(e){return function(e){const t=e.byteLength;for(let i=0;i<t;){const s=Te(e,i);if(s>8&&109===e[i+4]&&111===e[i+5]&&111===e[i+6]&&102===e[i+7])return!0;i=s>1?i+s:t}return!1}(e)}demux(e,t){this.timeOffset=t;let i=e;const s=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=Ce(this.remainderData,e));const t=function(e){const t={valid:null,remainder:null},i=Ae(e,["moof"]);if(i.length<2)return t.remainder=e,t;const s=i[i.length-1];return t.valid=e.slice(0,s.byteOffset-8),t.remainder=e.slice(s.byteOffset-8),t}(i);this.remainderData=t.remainder,s.samples=t.valid||new Uint8Array}else s.samples=i;const n=this.extractID3Track(s,t);return r.samples=_e(t,s),{videoTrack:s,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const s=this.extractID3Track(t,this.timeOffset);return i.samples=_e(e,t),{videoTrack:t,audioTrack:kr(),id3Track:s,textTrack:kr()}}extractID3Track(e,t){const i=this.id3Track;if(e.samples.length){const s=Ae(e.samples,["emsg"]);s&&s.forEach(e=>{const s=function(e){const t=e[0];let i="",s="",r=0,n=0,a=0,o=0,l=0,d=0;if(0===t){for(;"\0"!==ve(e.subarray(d,d+1));)i+=ve(e.subarray(d,d+1)),d+=1;for(i+=ve(e.subarray(d,d+1)),d+=1;"\0"!==ve(e.subarray(d,d+1));)s+=ve(e.subarray(d,d+1)),d+=1;s+=ve(e.subarray(d,d+1)),d+=1,r=Te(e,12),n=Te(e,16),o=Te(e,20),l=Te(e,24),d=28}else if(1===t){d+=4,r=Te(e,d),d+=4;const t=Te(e,d);d+=4;const n=Te(e,d);for(d+=4,a=2**32*t+n,R(a)||(a=Number.MAX_SAFE_INTEGER,z.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=Te(e,d),d+=4,l=Te(e,d),d+=4;"\0"!==ve(e.subarray(d,d+1));)i+=ve(e.subarray(d,d+1)),d+=1;for(i+=ve(e.subarray(d,d+1)),d+=1;"\0"!==ve(e.subarray(d,d+1));)s+=ve(e.subarray(d,d+1)),d+=1;s+=ve(e.subarray(d,d+1)),d+=1}return{schemeIdUri:i,value:s,timeScale:r,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:e.subarray(d,e.byteLength)}}(e);if(Hr.test(s.schemeIdUri)){const e=Kr(s,t);let r=4294967295===s.eventDuration?Number.POSITIVE_INFINITY:s.eventDuration/s.timeScale;r<=.001&&(r=Number.POSITIVE_INFINITY);const n=s.payload;i.samples.push({data:n,len:n.byteLength,dts:e,pts:e,type:Ir.emsg,duration:r})}else if(this.config.enableEmsgKLVMetadata&&s.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const e=Kr(s,t);i.samples.push({data:s.payload,len:s.payload.byteLength,dts:e,pts:e,type:Ir.misbklv,duration:Number.POSITIVE_INFINITY})}})}return i}demuxSampleAes(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}},remux:class extends H{constructor(e,t,i,s){super("passthrough-remuxer",s),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;const t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,i,s){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(e,s),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:i,videoCodec:s}=this;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const{audio:r,video:n}=this.initData=Le(e);if(t)!function(e,t){if(!e||!t)return;const i=t.keyId;i&&t.isCommonEncryption&&De(e,(e,t)=>{const s=e.subarray(8,24);s.some(e=>0!==e)||(z.log(`[eme] Patching keyId in 'enc${t?"a":"v"}>sinf>>tenc' box: ${Z(s)} -> ${Z(i)}`),e.set(i,8))})}(e,t);else{const e=r||n;null!=e&&e.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${e.codec}")!`)}r&&(i=En(r,ae,this)),n&&(s=En(n,oe,this));const a={};r&&n?a.audiovideo={container:"video/mp4",codec:i+","+s,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:r?a.audio={container:"audio/mp4",codec:i,encrypted:r.encrypted,initSegment:e,id:"audio"}:n?a.video={container:"video/mp4",codec:s,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=a}remux(e,t,i,s,r,n){var a,o;let{initPTS:l,lastEndTime:d}=this;const c={audio:void 0,video:void 0,text:s,id3:i,initSegment:void 0};L(d)||(d=this.lastEndTime=r||0);const u=t.samples;if(!u.length)return c;const h={initPTS:void 0,timescale:void 0,trackId:void 0};let f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(u),f=this.initData),null==(o=f)||!o.length)return this.warn("Failed to generate initSegment."),c;this.emitInitSegment&&(h.tracks=this.initTracks,this.emitInitSegment=!1);const g=function(e,t,i){const s={},r=Ae(e,["moof","traf"]);for(let e=0;e<r.length;e++){const n=r[e],a=Ae(n,["tfhd"])[0],o=Te(a,4),l=t[o];if(!l)continue;s[o]||(s[o]={start:NaN,duration:0,sampleCount:0,timescale:l.timescale,type:l.type});const d=s[o],c=Ae(n,["tfdt"])[0];if(c){const e=c[0];let t=Te(c,4);1===e&&(t===ge?i.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(t*=ge+1,t+=Te(c,8))),L(t)&&(!L(d.start)||t<d.start)&&(d.start=t)}const u=l.default,h=Te(a,0)|(null==u?void 0:u.flags);let f=(null==u?void 0:u.duration)||0;8&h&&(f=Te(a,2&h?12:8));const g=Ae(n,["trun"]);let p=d.start||0,m=0,v=f;for(let e=0;e<g.length;e++){const t=g[e],i=Te(t,4),s=d.sampleCount;d.sampleCount+=i;const r=1&t[3],n=4&t[3],a=1&t[2],o=2&t[2],l=4&t[2],c=8&t[2];let u=8,h=i;for(r&&(u+=4),n&&i&&(1&t[u+1]||void 0!==d.keyFrameIndex||(d.keyFrameIndex=s),u+=4,a?(v=Te(t,u),u+=4):v=f,o&&(u+=4),c&&(u+=4),p+=v,m+=v,h--);h--;)a?(v=Te(t,u),u+=4):v=f,o&&(u+=4),l&&(1&t[u+1]||void 0===d.keyFrameIndex&&(d.keyFrameIndex=d.sampleCount-(h+1),d.keyFrameStart=p),u+=4),c&&(u+=4),p+=v,m+=v;!m&&f&&(m+=f*i)}d.duration+=m}if(!Object.keys(s).some(e=>s[e].duration)){let t=1/0,i=0;const r=Ae(e,["sidx"]);for(let e=0;e<r.length;e++){const s=be(r[e]);if(null!=s&&s.references){t=Math.min(t,s.earliestPresentationTime/s.timescale);const e=s.references.reduce((e,t)=>e+t.info.duration||0,0);i=Math.max(i,e+s.earliestPresentationTime/s.timescale)}}i&&L(i)&&Object.keys(s).forEach(e=>{s[e].duration||(s[e].duration=i*s[e].timescale-s[e].start)})}return s}(u,f,this),p=f.audio?g[f.audio.id]:null,m=f.video?g[f.video.id]:null,v=Tn(m,1/0),y=Tn(p,1/0),T=Tn(m,0,!0),E=Tn(p,0,!0);let S=r,A=0;const b=p&&(!m||!l&&y<v||l&&l.trackId===f.audio.id),R=b?p:m;if(R){const e=R.timescale,t=R.start-r*e,i=b?f.audio.id:f.video.id;S=R.start/e,A=b?E-y:T-v,!n&&l||!function(e,t,i,s){if(null===e)return!0;const r=Math.max(s,1),n=t-e.baseTime/e.timescale;return Math.abs(n-i)>r}(l,S,r,A)&&e===l.timescale||(l&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${r} ${t/e} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${S-r} (${t}/${e}) trackId: ${i}`),l=null,h.initPTS=t,h.timescale=e,h.trackId=i)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${r}`);l?(h.initPTS=l.baseTime,h.timescale=l.timescale,h.trackId=l.trackId):(h.timescale&&void 0!==h.trackId&&void 0!==h.initPTS||(this.warn("Could not set initPTS"),h.initPTS=S,h.timescale=1,h.trackId=-1),this.initPTS=l={baseTime:h.initPTS,timescale:h.timescale,trackId:h.trackId});const I=S-l.baseTime/l.timescale,k=I+A;A>0?this.lastEndTime=k:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const w=!!f.audio,P=!!f.video;let D="";w&&(D+="audio"),P&&(D+="video");const x={data1:u,startPTS:I,startDTS:I,endPTS:k,endDTS:k,type:D,hasAudio:w,hasVideo:P,nb:1,dropped:0,encrypted:!!f.audio&&f.audio.encrypted||!!f.video&&f.video.encrypted};c.audio=w&&!P?x:void 0,c.video=P?x:void 0;const C=null==m?void 0:m.sampleCount;if(C){const e=m.keyFrameIndex,t=-1!==e;x.nb=C,x.dropped=0===e||this.isVideoContiguous?0:t?e:C,x.independent=t,x.firstKeyFrame=e,t&&m.keyFrameStart&&(x.firstKeyFramePTS=(m.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(c.independent=t),this.isVideoContiguous||(this.isVideoContiguous=t),x.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${e}/${C} dropped: ${x.dropped} start: ${x.firstKeyFramePTS||"NA"}`)}return c.initSegment=h,c.id3=vn(i,r,l,l),s.samples.length&&(c.text=yn(s,r,l)),c}}},{demux:Qr,remux:pn},{demux:class extends wr{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const i=lr(e,0);let s=(null==i?void 0:i.length)||0;if(Br(e,s))return!1;for(let i=e.length;s<i;s++)if(fr(e,s))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return function(e,t){return t+5<e.length}(e,t)&&dr(e,t)&&ur(e,t)<=e.length-t}(e,t)}appendFrame(e,t,i){gr(e,this.observer,t,i,e.manifestCodec);const s=mr(e,t,i,this.basePTS,this.frameIndex);if(s&&0===s.missing)return s}},remux:pn},{demux:class extends wr{resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=lr(e,0);let i=(null==t?void 0:t.length)||0;if(t&&11===e[i]&&119===e[i+1]&&void 0!==Rr(t)&&$r(e,i)<=16)return!1;for(let t=e.length;i<t;i++)if(Br(e,i))return z.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return Ur(e,t)&&4<=e.length-t}(e,t)}appendFrame(e,t,i){if(null!==this.basePTS)return Or(e,t,i,this.basePTS,this.frameIndex)}},remux:pn}];Sn.splice(2,0,{demux:Vr,remux:pn});class An{constructor(e,t,i,s,r,n){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=i,this.id=r,this.logger=n}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,s){const r=i.transmuxing;r.executeStart=un();let n=new Uint8Array(e);const{currentTransmuxState:a,transmuxConfig:o}=this;s&&(this.currentTransmuxState=s);const{contiguous:l,discontinuity:d,trackSwitch:c,accurateTimeOffset:u,timeOffset:h,initSegmentChange:f}=s||a,{audioCodec:g,videoCodec:p,defaultInitPts:m,duration:v,initSegmentData:y}=o,T=function(e,t){let i=null;e.byteLength>0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(i=t);return i}(n,t);if(T&&_i(T.method)){const e=this.getDecrypter(),t=Mi(T.method);if(!e.isSync())return this.asyncResult=!0,this.decryptionPromise=e.webCryptoDecrypt(n,T.key.buffer,T.iv.buffer,t).then(e=>{const t=this.push(e,null,i);return this.decryptionPromise=null,t}),this.decryptionPromise;{let s=e.softwareDecrypt(n,T.key.buffer,T.iv.buffer,t);if(i.part>-1){const t=e.flush();s=t?t.buffer:t}if(!s)return r.executeEnd=un(),bn(i);n=new Uint8Array(s)}}const E=this.needsProbing(d,c);if(E){const e=this.configureTransmuxer(n);if(e)return this.logger.warn(`[transmuxer] ${e.message}`),this.observer.emit(P.ERROR,P.ERROR,{type:k.MEDIA_ERROR,details:w.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),r.executeEnd=un(),bn(i)}(d||c||f||E)&&this.resetInitSegment(y,g,p,v,t),(d||f||E)&&this.resetInitialTimestamp(m),l||this.resetContiguity();const S=this.transmux(n,T,h,u,i);this.asyncResult=Ln(S);const A=this.currentTransmuxState;return A.contiguous=!0,A.discontinuity=!1,A.trackSwitch=!1,r.executeEnd=un(),S}flush(e){const t=e.transmuxing;t.executeStart=un();const{decrypter:i,currentTransmuxState:s,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(e));const n=[],{timeOffset:a}=s;if(i){const t=i.flush();t&&n.push(this.push(t.buffer,null,e))}const{demuxer:o,remuxer:l}=this;if(!o||!l){t.executeEnd=un();const i=[bn(e)];return this.asyncResult?Promise.resolve(i):i}const d=o.flush(a);return Ln(d)?(this.asyncResult=!0,d.then(t=>(this.flushRemux(n,t,e),n))):(this.flushRemux(n,d,e),this.asyncResult?Promise.resolve(n):n)}flushRemux(e,t,i){const{audioTrack:s,videoTrack:r,id3Track:n,textTrack:a}=t,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id===M?"level":"track"} ${i.level}`);const d=this.remuxer.remux(s,r,n,a,l,o,!0,this.id);e.push({remuxResult:d,chunkMeta:i}),i.transmuxing.executeEnd=un()}resetInitialTimestamp(e){const{demuxer:t,remuxer:i}=this;t&&i&&(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,s,r){const{demuxer:n,remuxer:a}=this;n&&a&&(n.resetInitSegment(e,t,i,s),a.resetInitSegment(e,t,i,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,i,s,r){let n;return n=t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,i,s,r):this.transmuxUnencrypted(e,i,s,r),n}transmuxUnencrypted(e,t,i,s){const{audioTrack:r,videoTrack:n,id3Track:a,textTrack:o}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,n,a,o,t,i,!1,this.id),chunkMeta:s}}transmuxSampleAes(e,t,i,s,r){return this.demuxer.demuxSampleAes(e,t,i).then(e=>({remuxResult:this.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,i,s,!1,this.id),chunkMeta:r}))}configureTransmuxer(e){const{config:t,observer:i,typeSupported:s}=this;let r;for(let t=0,i=Sn.length;t<i;t++){var n;if(null!=(n=Sn[t].demux)&&n.probe(e,this.logger)){r=Sn[t];break}}if(!r)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=r.remux,d=r.demux;o&&o instanceof l||(this.remuxer=new l(i,t,s,this.logger)),a&&a instanceof d||(this.demuxer=new d(i,t,s,this.logger),this.probe=d.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new di(this.config)),e}}const bn=e=>({remuxResult:{},chunkMeta:e});function Ln(e){return"then"in e&&e.then instanceof Function}class Rn{constructor(e,t,i,s,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=s,this.defaultInitPts=r||null}}class In{constructor(e,t,i,s,r,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=s,this.timeOffset=r,this.initSegmentChange=n}}let kn=0;class wn{constructor(e,t,i,s){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=kn++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=e=>{const t=e.data,i=this.hls;if(i&&null!=t&&t.event&&t.instanceNo===this.instanceNo)switch(t.event){case"init":{var s;const e=null==(s=this.workerContext)?void 0:s.objectURL;e&&self.URL.revokeObjectURL(e);break}case"transmuxComplete":this.handleTransmuxComplete(t.data);break;case"flush":this.onFlush(t.data);break;case"workerLog":i.logger[t.data.logType]&&i.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.part=this.part,t.data.id=this.id,i.trigger(t.event,t.data)}},this.onWorkerError=e=>{if(!this.hls)return;const t=new Error(`${e.message} (${e.filename}:${e.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(P.ERROR,{type:k.OTHER_ERROR,details:w.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:t})};const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=i,this.onFlush=s;const n=(e,t)=>{(t=t||{}).frag=this.frag||void 0,e===P.ERROR&&(t.parent=this.id,t.part=this.part,this.error=t.error),this.hls.trigger(e,t)};this.observer=new ir,this.observer.on(P.FRAG_DECRYPTED,n),this.observer.on(P.ERROR,n);const a=et(r.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){const i=this.hls.logger;if(r.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{r.workerPath?(i.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=function(e){const t=rr[e];if(t)return t.clientCount++,t;const i=new self.URL(e,self.location.href).href,s={worker:new self.Worker(i),scriptURL:i,clientCount:1};return rr[e]=s,s}(r.workerPath)):(i.log(`injecting Web Worker for "${t}"`),this.workerContext=function(){const e=rr[sr];if(e)return e.clientCount++,e;const t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),i=self.URL.createObjectURL(t),s={worker:new self.Worker(i),objectURL:i,clientCount:1};return rr[sr]=s,s}());const{worker:e}=this.workerContext;e.addEventListener("message",this.onWorkerMessage),e.addEventListener("error",this.onWorkerError),e.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:t,config:Tt(r)})}catch(s){i.warn(`Error setting up "${t}" Web Worker, fallback to inline`,s),this.terminateWorker(),this.error=null,this.transmuxer=new An(this.observer,a,r,"",t,e.logger)}return}}this.transmuxer=new An(this.observer,a,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=kn++;const t=this.hls.config,i=et(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:Tt(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),function(e){const t=rr[e||sr];if(t&&1===t.clientCount--){const{worker:i,objectURL:s}=t;delete rr[e||sr],s&&self.URL.revokeObjectURL(s),i.terminate()}}(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,i,s,r,n,a,o,l,d){var c,u;l.transmuxing.start=self.performance.now();const{instanceNo:h,transmuxer:f}=this,g=n?n.start:r.start,p=r.decryptdata,m=this.frag,v=!(m&&r.cc===m.cc),y=!(m&&l.level===m.level),T=m?l.sn-m.sn:-1,E=this.part?l.part-this.part.index:-1,S=0===T&&l.id>1&&l.id===(null==m?void 0:m.stats.chunkCount),A=!y&&(1===T||0===T&&(1===E||S&&E<=0)),b=self.performance.now();(y||T||0===r.stats.parsing.start)&&(r.stats.parsing.start=b),!n||!E&&A||(n.stats.parsing.start=b);const L=!(m&&(null==(c=r.initSegment)?void 0:c.url)===(null==(u=m.initSegment)?void 0:u.url)),R=new In(v,A,o,y,g,L);if(!A||v||L){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===M?"level":"track"}: ${l.level} id: ${l.id}\n discontinuity: ${v}\n trackSwitch: ${y}\n contiguous: ${A}\n accurateTimeOffset: ${o}\n timeOffset: ${g}\n initSegmentChange: ${L}`);const e=new Rn(i,s,t,a,d);this.configureTransmuxer(e)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:h,cmd:"demux",data:e,decryptdata:p,chunkMeta:l,state:R},e instanceof ArrayBuffer?[e]:[]);else if(f){const t=f.push(e,p,l,R);Ln(t)?t.then(e=>{this.handleTransmuxComplete(e)}).catch(e=>{this.transmuxerError(e,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(t)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(i){const t=i.flush(e);Ln(t)?t.then(t=>{this.handleFlushResult(t,e)}).catch(t=>{this.transmuxerError(t,e,"transmuxer-interface flush error")}):this.handleFlushResult(t,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(P.ERROR,{type:k.MEDIA_ERROR,details:w.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach(e=>{this.handleTransmuxComplete(e)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):i&&i.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}class Pn extends H{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,i){const s=null==t?void 0:t.renditionReports;if(s){let r=-1;for(let i=0;i<s.length;i++){const n=s[i];let a;try{a=new self.URL(n.URI,t.url).href}catch(e){this.warn(`Could not construct new URL for Rendition Report: ${e}`),a=n.URI||""}if(a===e){r=i;break}a===e.substring(0,a.length)&&(r=i)}if(-1!==r){const e=s[r],n=parseInt(e["LAST-MSN"])||t.lastPartSn;let a=parseInt(e["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const e=Math.min(t.age-t.partTarget,t.targetduration);a>=0&&e>t.partTarget&&(a+=1)}const o=i&>(i);return new pt(n,a>=0?a:void 0,o)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}return e}playlistLoaded(e,t,i){const{details:s,stats:r}=t,n=self.performance.now(),a=r.loading.first?Math.max(0,n-r.loading.first):0;s.advancedDateTime=Date.now()-a;const o=this.hls.config.timelineOffset;if(o!==s.appliedTimelineOffset){const e=Math.max(o||0,0);s.appliedTimelineOffset=e,s.fragments.forEach(t=>{t.setStart(t.playlistOffset+e)})}if(s.live||null!=i&&i.live){const o="levelInfo"in t?t.levelInfo:t.track;if(s.reloaded(i),i&&s.fragments.length>0){Ts(i,s,this);const e=s.playlistParsingError;if(e){this.warn(e);const i=this.hls;if(!i.config.ignorePlaylistParsingErrors){var l;const{networkDetails:n}=t;return void i.trigger(P.ERROR,{type:k.NETWORK_ERROR,details:w.LEVEL_PARSING_ERROR,fatal:!1,url:s.url,error:e,reason:e.message,level:t.level||void 0,parent:null==(l=s.fragments[0])?void 0:l.type,networkDetails:n,stats:r})}s.playlistParsingError=null}}-1===s.requestScheduled&&(s.requestScheduled=r.loading.start);const d=this.hls.mainForwardBufferInfo,c=d?d.end-d.len:0,u=bs(s,1e3*(s.edge-c));if(s.requestScheduled+u<n?s.requestScheduled=n:s.requestScheduled+=u,this.log(`live playlist ${e} ${s.advanced?"REFRESHED "+s.lastPartSn+"-"+s.lastPartIndex:s.updated?"UPDATED":"MISSED"}`),!this.canLoad||!s.live)return;let h,f,g;if(s.canBlockReload&&s.endSN&&s.advanced){const e=this.hls.config.lowLatencyMode,r=s.lastPartSn,a=s.endSN,l=s.lastPartIndex,d=r===a;-1!==l?d?(f=a+1,g=e?0:l):(f=r,g=e?l+1:s.maxPartIndex):f=a+1;const c=s.age,u=c+s.ageHeader;let p=Math.min(u-s.partTarget,1.5*s.targetduration);if(p>0){if(u>3*s.targetduration)this.log(`Playlist last advanced ${c.toFixed(2)}s ago. Omitting segment and part directives.`),f=void 0,g=void 0;else if(null!=i&&i.tuneInGoal&&u-s.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${p} with playlist age: ${s.age}`),p=0;else{const e=Math.floor(p/s.targetduration);if(f+=e,void 0!==g){g+=Math.round(p%s.targetduration/s.partTarget)}this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${c.toFixed(2)}s goal: ${p} skip sn ${e} to part ${g}`)}s.tuneInGoal=p}if(h=this.getDeliveryDirectives(s,t.deliveryDirectives,f,g),e||!d)return s.requestScheduled=n,void this.loadingPlaylist(o,h)}else(s.canBlockReload||s.canSkipUntil)&&(h=this.getDeliveryDirectives(s,t.deliveryDirectives,f,g));h&&void 0!==f&&s.canBlockReload&&(s.requestScheduled=r.loading.first+Math.max(u-2*a,u/2)),this.scheduleLoading(o,h,s)}else this.clearTimer()}scheduleLoading(e,t,i){const s=i||e.details;if(!s)return void this.loadingPlaylist(e,t);const r=self.performance.now(),n=s.requestScheduled;if(r>=n)return void this.loadingPlaylist(e,t);const a=n-r;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),a)}getDeliveryDirectives(e,t,i,s){let r=gt(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,s=t.part,r=ut),new pt(i,s,r)}checkRetry(e){const t=e.details,i=_t(e),s=e.errorAction,{action:r,retryCount:n=0,retryConfig:a}=s||{},o=!!s&&!!a&&(r===Kt||!s.resolved&&r===Gt);if(o){var l;if(n>=a.maxNumRetry)return!1;if(i&&null!=(l=e.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const e=Ut(a,n);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),e),this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" in ${e}ms`)}e.levelRetry=!0,s.resolved=!0}return o}}function Dn(e,t){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!xn(e[i].attrs,t[i].attrs))return!1;return!0}function xn(e,t,i){const s=e["STABLE-RENDITION-ID"];return s&&!i?s===t["STABLE-RENDITION-ID"]:!(i||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(i=>e[i]!==t[i])}function Cn(e,t){return t.label.toLowerCase()===e.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(e.lang||"").toLowerCase())}class _n{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,i){if(null===this.queues||null===this.tracks)return;const s=this.queues[t];s.push(e),1!==s.length||i||this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const i={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const i={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(i)}})}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const i=null==(t=e[0])?void 0:t.label;"async-blocker"!==i&&"async-blocker-prepend"!==i||(e[0].execute(),e.splice(0,1))})}unblockAudio(e){if(null===this.queues)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(null===this.queues||null===this.tracks)return;const t=this.queues[e];if(t.length){const s=t[0];try{s.execute()}catch(t){var i;if(s.onError(t),null===this.queues||null===this.tracks)return;const r=null==(i=this.tracks[e])?void 0:i.buffer;null!=r&&r.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){null!==this.queues&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return(null==(t=this.queues)?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return null===e||null===t?"<destroyed>":`\n${this.list("video")}\n${this.list("audio")}\n${this.list("audiovideo")}}`}list(e){var t,i;return null!=(t=this.queues)&&t[e]||null!=(i=this.tracks)&&i[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const i=null==(t=this.tracks)?void 0:t[e],s=null==i?void 0:i.buffer;return s?`SourceBuffer${s.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(e){var t;return(null==(t=this.queues)?void 0:t[e].map(e=>e.label).join(", "))||""}}const Mn=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,On="HlsJsTrackRemovedError";class Fn extends Error{constructor(e){super(e),this.name=On}}function Un(e){const t=e.querySelectorAll("source");[].slice.call(t).forEach(t=>{e.removeChild(t)})}function Nn(e){return"audio"===e?1:0}class Bn{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(P.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(P.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(P.MANIFEST_PARSED,this.onManifestParsed,this),e.on(P.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(P.BUFFER_CODECS,this.onBufferCodecs,this),e.on(P.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(P.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(P.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(P.MANIFEST_PARSED,this.onManifestParsed,this),e.off(P.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(P.BUFFER_CODECS,this.onBufferCodecs,this),e.off(P.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&L(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);const e=this.hls.levels;if(e.length){const t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const i=t.filter((t,i)=>this.isLevelAllowed(t)&&i<=e);return this.clientRect=null,Bn.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,t.width||t.height||(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch(e){}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(t=>e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height)}static getMaxLevelByMediaSize(e,t,i){if(null==e||!e.length)return-1;const s=(e,t)=>!t||(e.width!==t.width||e.height!==t.height);let r=e.length-1;const n=Math.max(t,i);for(let t=0;t<e.length;t+=1){const i=e[t];if((i.width>=n||i.height>=n)&&s(i,e[t+1])){r=t;break}}return r}}const $n={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Vn={HLS:"h"};class Gn{constructor(e,t){Array.isArray(e)&&(e=e.map(e=>e instanceof Gn?e:new Gn(e))),this.value=e,this.params=t}}function Hn(e,t,i,s){return new Error(`failed to ${e} "${r=t,Array.isArray(r)?JSON.stringify(r):r instanceof Map?"Map{}":r instanceof Set?"Set{}":"object"==typeof r?JSON.stringify(r):String(r)}" as ${i}`,{cause:s});var r}function Kn(e,t,i){return Hn("serialize",e,t,i)}class jn{constructor(e){this.description=e}}const Wn="Bare Item";function qn(e){if(!1===ArrayBuffer.isView(e))throw Kn(e,"Byte Sequence");return`:${t=e,btoa(String.fromCharCode(...t))}:`;var t}function Yn(e){if(function(e){return e<-999999999999999||999999999999999<e}(e))throw Kn(e,"Integer");return e.toString()}function zn(e,t){if(e<0)return-zn(-e,t);const i=Math.pow(10,t);if(Math.abs(e*i%1-.5)<Number.EPSILON){const t=Math.floor(e*i);return(t%2==0?t:t+1)/i}return Math.round(e*i)/i}function Xn(e){const t=zn(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw Kn(e,"Decimal");const i=t.toString();return i.includes(".")?i:`${i}.0`}const Qn=/[\x00-\x1f\x7f]+/;function Jn(e){const t=(i=e).description||i.toString().slice(7,-1);var i;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t))throw Kn(t,"Token");return t}function Zn(e){switch(typeof e){case"number":if(!L(e))throw Kn(e,Wn);return Number.isInteger(e)?Yn(e):Xn(e);case"string":return function(e){if(Qn.test(e))throw Kn(e,"String");return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(e);case"symbol":return Jn(e);case"boolean":return function(e){if("boolean"!=typeof e)throw Kn(e,"Boolean");return e?"?1":"?0"}(e);case"object":if(e instanceof Date)return function(e){return`@${Yn(e.getTime()/1e3)}`}(e);if(e instanceof Uint8Array)return qn(e);if(e instanceof jn)return Jn(e);default:throw Kn(e,Wn)}}function ea(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw Kn(e,"Key");return e}function ta(e){return null==e?"":Object.entries(e).map(([e,t])=>!0===t?`;${ea(e)}`:`;${ea(e)}=${Zn(t)}`).join("")}function ia(e){return e instanceof Gn?`${Zn(e.value)}${ta(e.params)}`:Zn(e)}function sa(e,t={whitespace:!0}){if("object"!=typeof e||null==e)throw Kn(e,"Dict");const i=e instanceof Map?e.entries():Object.entries(e),s=(null==t?void 0:t.whitespace)?" ":"";return Array.from(i).map(([e,t])=>{t instanceof Gn==!1&&(t=new Gn(t));let i=ea(e);var s;return!0===t.value?i+=ta(t.params):(i+="=",Array.isArray(t.value)?i+=`(${(s=t).value.map(ia).join(" ")})${ta(s.params)}`:i+=ia(t)),i}).join(`,${s}`)}function ra(e,t){return sa(e,t)}const na="CMCD-Object",aa="CMCD-Request",oa="CMCD-Session",la="CMCD-Status",da={br:na,ab:na,d:na,ot:na,tb:na,tpb:na,lb:na,tab:na,lab:na,url:na,pb:aa,bl:aa,tbl:aa,dl:aa,ltc:aa,mtp:aa,nor:aa,nrr:aa,rc:aa,sn:aa,sta:aa,su:aa,ttfb:aa,ttfbb:aa,ttlb:aa,cmsdd:aa,cmsds:aa,smrt:aa,df:aa,cs:aa,ts:aa,cid:oa,pr:oa,sf:oa,sid:oa,st:oa,v:oa,msd:oa,bs:la,bsd:la,cdn:la,rtp:la,bg:la,pt:la,ec:la,e:la},ca=aa;function ua(e,t){const i={};if(!e)return i;const s=Object.keys(e),r=t?(n=t,Object.keys(n).reduce((e,t)=>{var i;return null===(i=n[t])||void 0===i||i.forEach(i=>e[i]=t),e},{})):{};var n;return s.reduce((t,i)=>{var s;const n=da[i]||r[i]||ca;return(null!==(s=t[n])&&void 0!==s?s:t[n]={})[i]=e[i],t},i)}const ha="event";const fa=e=>Math.round(e),ga=(e,t)=>Array.isArray(e)?e.map(e=>ga(e,t)):e instanceof Gn&&"string"==typeof e.value?new Gn(ga(e.value,t),e.params):(t.baseUrl&&(e=function(e,t){const i=new URL(e),s=new URL(t);if(i.origin!==s.origin)return e;const r=i.pathname.split("/").slice(1),n=s.pathname.split("/").slice(1,-1);for(;r[0]===n[0];)r.shift(),n.shift();for(;n.length;)n.shift(),r.unshift("..");return r.join("/")+i.search+i.hash}(e,t.baseUrl)),1===t.version?encodeURIComponent(e):e),pa=e=>100*fa(e/100),ma={br:fa,d:fa,bl:pa,dl:pa,mtp:pa,nor:(e,t)=>{let i=e;return t.version>=2&&(e instanceof Gn&&"string"==typeof e.value?i=new Gn([e]):"string"==typeof e&&(i=[e])),ga(i,t)},rtp:pa,tb:fa},va="request",ya="response",Ta=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],Ea=["e"],Sa=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Aa(e){return Sa.test(e)}const ba=["d","dl","nor","ot","rtp","su"];const La=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];const Ra=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function Ia(e){return Ra.includes(e)||Aa(e)}const ka={[ya]:function(e){return Ta.includes(e)||ba.includes(e)||La.includes(e)||Aa(e)},[ha]:function(e){return Ta.includes(e)||Ea.includes(e)||Aa(e)},[va]:function(e){return Ta.includes(e)||ba.includes(e)||Aa(e)}};function wa(e,t={}){const i={};if(null==e||"object"!=typeof e)return i;const s=t.version||e.v||1,r=t.reportingMode||va,n=1===s?Ia:ka[r];let a=Object.keys(e).filter(n);const o=t.filter;"function"==typeof o&&(a=a.filter(o));const l=r===ya||r===ha;l&&!a.includes("ts")&&a.push("ts"),s>1&&!a.includes("v")&&a.push("v");const d=$({},ma,t.formatters),c={version:s,reportingMode:r,baseUrl:t.baseUrl};return a.sort().forEach(t=>{let r=e[t];const n=d[t];if("function"==typeof n&&(r=n(r,c)),"v"===t){if(1===s)return;r=s}"pr"==t&&1===r||(l&&"ts"===t&&!L(r)&&(r=Date.now()),function(e){return"number"==typeof e?L(e):null!=e&&""!==e&&!1!==e}(r)&&(function(e){return["ot","sf","st","e","sta"].includes(e)}(t)&&"string"==typeof r&&(r=new jn(r)),i[t]=r))}),i}function Pa(e,t,i){return $(e,function(e,t={}){const i={};if(!e)return i;const s=ua(wa(e,t),null==t?void 0:t.customHeaderMap);return Object.entries(s).reduce((e,[t,i])=>{const s=ra(i,{whitespace:!1});return s&&(e[t]=s),e},i)}(t,i))}function Da(e,t={}){if(!e)return"";const i=function(e,t={}){return e?ra(wa(e,t),{whitespace:!1}):""}(e,t);return encodeURIComponent(i)}const xa=/CMCD=[^&#]+/;function Ca(e,t,i){const s=function(e,t={}){return e?`CMCD=${Da(e,t)}`:""}(t,i);if(!s)return e;if(xa.test(e))return e.replace(xa,s);const r=e.includes("?")?"&":"?";return`${e}${r}${s}`}function _a(e,t,i,s){e&&Object.keys(t).forEach(r=>{const n=e.filter(e=>e.groupId===r).map(e=>{const n=$({},e);return n.details=void 0,n.attrs=new Ii(n.attrs),n.url=n.attrs.URI=Ma(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),n.groupId=n.attrs["GROUP-ID"]=t[r],n.attrs["PATHWAY-ID"]=s,n});e.push(...n)})}function Ma(e,t,i,s){const{HOST:r,PARAMS:n,[i]:a}=s;let o;t&&(o=null==a?void 0:a[t],o&&(e=o));const l=new self.URL(e);return r&&!o&&(l.host=r),n&&Object.keys(n).sort().forEach(e=>{e&&l.searchParams.set(e,n[e])}),l.href}class Oa extends H{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=Oa.CDMCleanupPromise?[Oa.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=e=>{const{initDataType:t,initData:i}=e,s=`"${e.type}" event: init data type: "${t}"`;if(this.debug(s),null!==i){if(!this.keyFormatPromise){let e=Object.keys(this.keySystemAccessPromises);e.length||(e=qi(this.config));const t=e.map(Wi).filter(e=>!!e);this.keyFormatPromise=this.getKeyFormatPromise(t)}this.keyFormatPromise.then(r=>{const n=ji(r);if("sinf"!==t||n!==$i.FAIRPLAY)return void this.log(`Ignoring "${e.type}" event with init data type: "${t}" for selected key-system ${n}`);let a;try{const e=ve(new Uint8Array(i)),t=xe(Oi(JSON.parse(e).sinf));if(!t)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");a=new Uint8Array(t.subarray(8,24))}catch(e){return void this.warn(`${s} Failed to parse sinf: ${e}`)}const o=Z(a),{keyIdToKeySessionPromise:l,mediaKeySessions:d}=this;let c=l[o];for(let e=0;e<d.length;e++){const s=d[e],r=s.decryptdata;if(!r.keyId)continue;const n=Z(r.keyId);if(xi(a,r.keyId)||-1!==r.uri.replace(/-/g,"").indexOf(o)){if(c=l[n],!c)continue;if(r.pssh)break;delete l[n],r.pssh=new Uint8Array(i),r.keyId=a,c=l[o]=c.then(()=>this.generateRequestWithPreferredKeySession(s,t,i,"encrypted-event-key-match")),c.catch(e=>this.handleError(e));break}}c||this.handleError(new Error(`Key ID ${o} not encountered in playlist. Key-system sessions ${d.length}.`))}).catch(e=>this.handleError(e))}},this.onWaitingForKey=e=>{this.log(`"${e.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(P.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(P.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(P.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(P.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(P.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(P.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(P.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(P.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(P.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(P.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:i}=this.config,s=null==t?void 0:t[e];return s?s.licenseUrl:e===$i.WIDEVINE&&i?i:void 0}getLicenseServerUrlOrThrow(e){const t=this.getLicenseServerUrl(e);if(void 0===t)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){const{drmSystems:t}=this.config,i=null==t?void 0:t[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,i=(e,t,i)=>!!e&&i.indexOf(e)===t,s=t.map(e=>e.audioCodec).filter(i),r=t.map(e=>e.videoCodec).filter(i);return s.length+r.length===0&&r.push("avc1.42e01e"),new Promise((t,i)=>{const n=e=>{const a=e.shift();this.getMediaKeysPromise(a,s,r).then(e=>t({keySystem:a,mediaKeys:e})).catch(t=>{e.length?n(e):i(t instanceof Na?t:new Na({type:k.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))})};n(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:i}=this.config;if("function"!=typeof i){let e=`Configured requestMediaKeySystemAccess is not a function ${i}`;return null===Yi&&"http:"===self.location.protocol&&(e=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(e))}return i(e,t)}getMediaKeysPromise(e,t,i){var s;const r=function(e,t,i,s){let r;switch(e){case $i.FAIRPLAY:r=["cenc","sinf"];break;case $i.WIDEVINE:case $i.PLAYREADY:r=["cenc"];break;case $i.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${e}`)}return function(e,t,i,s){return[{initDataTypes:e,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:t.map(e=>({contentType:`audio/mp4; codecs=${e}`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:i.map(e=>({contentType:`video/mp4; codecs=${e}`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}(r,t,i,s)}(e,t,i,this.config.drmSystemOptions||{});let n=this.keySystemAccessPromises[e],a=null==(s=n)?void 0:s.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${e}" key-system access with config: ${Tt(r)}`),a=this.requestMediaKeySystemAccess(e,r);const t=n=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch(t=>{this.log(`Failed to obtain access to key-system "${e}": ${t}`)}),a.then(i=>{this.log(`Access for key-system "${i.keySystem}" obtained`);const s=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const r=t.mediaKeys=i.createMediaKeys().then(i=>(this.log(`Media-keys created for "${e}"`),t.hasMediaKeys=!0,s.then(t=>t?this.setMediaKeysServerCertificate(i,e,t):i)));return r.catch(t=>{this.error(`Failed to create media-keys for "${e}"}: ${t}`)}),r})}return a.then(()=>n.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${Z(e.keyId||[])} keyUri: ${e.uri}`);const s=i.createSession(),r={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:s,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const i=this.createMediaKeySessionContext(e),s=Fa(t),r="cenc";this.keyIdToKeySessionPromise[s]=this.generateRequestWithPreferredKeySession(i,r,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){const i=e.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyId ${Z(e.decryptdata.keyId||[])}\n } (data length: ${t.byteLength})`),i.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>Wi(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:e,mediaKeys:t})=>this.attemptSetMediaKeys(e,t))}selectKeySystem(e){return new Promise((t,i)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:e})=>{const s=Wi(e);s?t(s):i(new Error(`Unable to find format for key-system "${e}"`))}).catch(i)})}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){const t=qi(this.config),i=e.map(ji).filter(e=>!!e&&-1!==t.indexOf(e));return this.selectKeySystem(i)}getKeyStatus(e){const{mediaKeySessions:t}=this;for(let i=0;i<t.length;i++){const s=Ua(e,t[i]);if(s)return s}}loadKey(e){const t=e.keyInfo.decryptdata,i=Fa(t),s=this.bannedKeyIds[i];if(s||"internal-error"===this.getKeyStatus(t)){const i=Ba(s||"internal-error",t);return this.handleError(i,e.frag),Promise.reject(i)}const r=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${r}`);const n=this.keyIdToKeySessionPromise[i];if(!n){const s=this.getKeySystemForKeyPromise(t).then(({keySystem:i,mediaKeys:s})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(i,s).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:i,mediaKeys:s,decryptdata:t}))))).then(e=>{const i=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(e,"cenc",i,"playlist-key")});return s.catch(t=>this.handleError(t,e.frag)),this.keyIdToKeySessionPromise[i]=s,s}return n.catch(i=>{if(i instanceof Na){const s=G({},i.data);"internal-error"===this.getKeyStatus(t)&&(s.decryptdata=t);const r=new Na(s,i.message);this.handleError(r,e.frag)}}),n}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof Na){t&&(e.data.frag=t);const i=e.data.decryptdata;this.error(`${e.message}${i?` (${Z(i.keyId||[])})`:""}`),this.hls.trigger(P.ERROR,e.data)}else this.error(e.message),this.hls.trigger(P.ERROR,{type:k.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=Fa(e),i=this.keyIdToKeySessionPromise[t];if(!i){const t=ji(e.keyFormat),i=t?[t]:qi(this.config);return this.attemptKeySystemAccess(i)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=qi(this.config)),0===e.length)throw new Na({type:k.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${Tt({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const s=Promise.all(i).then(()=>this.media?this.media.setMediaKeys(t):new Promise((e,i)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return i(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(e).catch(i)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(s),s.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(s),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(e=>-1===i.indexOf(e))})}generateRequestWithPreferredKeySession(e,t,i,s){var r;const n=null==(r=this.config.drmSystems)||null==(r=r[e.keySystem])?void 0:r.generateRequest;if(n)try{const s=n.call(this.hls,t,i,e);if(!s)throw new Error("Invalid response from configured generateRequest filter");t=s.initDataType,i=s.initData?s.initData:null,e.decryptdata.pssh=i?new Uint8Array(i):null}catch(e){if(this.warn(e.message),this.hls&&this.hls.config.debug)throw e}if(null===i)return this.log(`Skipping key-session request for "${s}" (no initData)`),Promise.resolve(e);const a=Fa(e.decryptdata),o=e.decryptdata.uri;this.log(`Generating key-session request for "${s}" keyId: ${a} URI: ${o} (init data type: ${t} length: ${i.byteLength})`);const l=new ir,d=e._onmessage=t=>{const i=e.mediaKeysSession;if(!i)return void l.emit("error",new Error("invalid state"));const{messageType:s,message:r}=t;this.log(`"${s}" message event for session "${i.sessionId}" message size: ${r.byteLength}`),"license-request"===s||"license-renewal"===s?this.renewLicense(e,r).catch(e=>{l.eventNames().length?l.emit("error",e):this.handleError(e)}):"license-release"===s?e.keySystem===$i.FAIRPLAY&&this.updateKeySession(e,Fi("acknowledged")).then(()=>this.removeSession(e)).catch(e=>this.handleError(e)):this.warn(`unhandled media key message type "${s}"`)},c=(e,t)=>{let i;t.keyStatus=e,e.startsWith("usable")?l.emit("resolved"):"internal-error"===e||"output-restricted"===e||"output-downscaled"===e?i=Ba(e,t.decryptdata):"expired"===e?i=new Error(`key expired (keyId: ${a})`):"released"===e?i=new Error("key released"):"status-pending"===e||this.warn(`unhandled key status change "${e}" (keyId: ${a})`),i&&(l.eventNames().length?l.emit("error",i):this.handleError(i))},u=e._onkeystatuseschange=t=>{if(!e.mediaKeysSession)return void l.emit("error",new Error("invalid state"));const i=this.getKeyStatuses(e);if(!Object.keys(i).some(e=>"status-pending"!==i[e]))return;if("expired"===i[a])return this.log(`Expired key ${Tt(i)} in key-session "${e.mediaKeysSession.sessionId}"`),void this.renewKeySession(e);let s=i[a];if(s)c(s,e);else{var r;const t=1e3;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(r=e.keyStatusTimeouts)[a]||(r[a]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;const i=this.getKeyStatus(e.decryptdata);if(i&&"status-pending"!==i)return this.log(`No status for keyId ${a} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${i} from other session.`),c(i,e);this.log(`key status for ${a} in key-session "${e.mediaKeysSession.sessionId}" timed out after ${t}ms`),s="internal-error",c(s,e)},t)),this.log(`No status for keyId ${a} (${Tt(i)}).`)}};Os(e.mediaKeysSession,"message",d),Os(e.mediaKeysSession,"keystatuseschange",u);const h=new Promise((e,t)=>{l.on("error",t),l.on("resolved",e)});return e.mediaKeysSession.generateRequest(t,i).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${a} URI: ${o}`)}).catch(t=>{throw new Na({type:k.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_SESSION,error:t,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${t}`)}).then(()=>h).catch(t=>(l.removeAllListeners(),this.removeSession(e).then(()=>{throw t}))).then(()=>(l.removeAllListeners(),e))}getKeyStatuses(e){const t={};return e.mediaKeysSession.keyStatuses.forEach((i,s)=>{if("string"==typeof s&&"object"==typeof i){const e=s;s=i,i=e}const r="buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s);e.keySystem===$i.PLAYREADY&&16===r.length&&Ui(r);const n=Z(r);"internal-error"===i&&(this.bannedKeyIds[n]=i),this.log(`key status change "${i}" for keyStatuses keyId: ${n} key-session "${e.mediaKeysSession.sessionId}"`),t[n]=i}),t}fetchServerCertificate(e){const t=this.config,i=new(0,t.loader)(t),s=this.getServerCertificateUrl(e);return s?(this.log(`Fetching server certificate for "${e}"`),new Promise((r,n)=>{const a={responseType:"arraybuffer",url:s},o=t.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(e,t,i,s)=>{r(e.data)},onError:(t,i,r,o)=>{n(new Na({type:k.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:G({url:a.url,data:void 0},t)},`"${e}" certificate request failed (${s}). Status: ${t.code} (${t.text})`))},onTimeout:(t,i,r)=>{n(new Na({type:k.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:{url:a.url,data:void 0}},`"${e}" certificate request timed out (${s})`))},onAbort:(e,t,i)=>{n(new Error("aborted"))}};i.load(a,l,d)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise((s,r)=>{e.setServerCertificate(i).then(r=>{this.log(`setServerCertificate ${r?"success":"not supported by CDM"} (${i.byteLength}) on "${t}"`),s(e)}).catch(e=>{r(new Na({type:k.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(t=>this.updateKeySession(e,new Uint8Array(t)).catch(t=>{throw new Na({type:k.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:t,fatal:!1},t.message)}))}unpackPlayReadyKeyMessage(e,t){const i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const s=(new DOMParser).parseFromString(i,"application/xml"),r=s.querySelectorAll("HttpHeader");if(r.length>0){let t;for(let i=0,s=r.length;i<s;i++){var n,a;t=r[i];const s=null==(n=t.querySelector("name"))?void 0:n.textContent,o=null==(a=t.querySelector("value"))?void 0:a.textContent;s&&o&&e.setRequestHeader(s,o)}}const o=s.querySelector("Challenge"),l=null==o?void 0:o.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return Fi(atob(l))}setupLicenseXHR(e,t,i,s){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return r.call(this.hls,e,t,i,s)}).catch(n=>{if(!i.decryptdata)throw n;return e.open("POST",t,!0),r.call(this.hls,e,t,i,s)}).then(i=>{e.readyState||e.open("POST",t,!0);return{xhr:e,licenseChallenge:i||s}}):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:s}))}requestLicense(e,t){const i=this.config.keyLoadPolicy.default;return new Promise((s,r)=>{const n=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${n}`);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return r(new Error("invalid state"));if(4===a.readyState)if(200===a.status){this._requestLicenseFailureCount=0;let t=a.response;this.log(`License received ${t instanceof ArrayBuffer?t.byteLength:t}`);const i=this.config.licenseResponseCallback;if(i)try{t=i.call(this.hls,a,n,e)}catch(e){this.error(e)}s(t)}else{const o=i.errorRetry,l=o?o.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||a.status>=400&&a.status<500)r(new Na({type:k.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:a,response:{url:n,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${n}). Status: ${a.status} (${a.statusText})`));else{const i=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${i} attempts left`),this.requestLicense(e,t).then(s,r)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=a,this.setupLicenseXHR(a,n,e,t).then(({xhr:t,licenseChallenge:i})=>{e.keySystem==$i.PLAYREADY&&(i=this.unpackPlayReadyKeyMessage(t,i)),t.send(i)}).catch(r)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const i=t.media;this.media=i,Os(i,"encrypted",this.onMediaEncrypted),Os(i,"waitingforkey",this.onWaitingForKey);const s=this.mediaResolved;s?s():this.mediaKeys=i.mediaKeys}onMediaDetached(){const e=this.media;e&&(Fs(e,"encrypted",this.onMediaEncrypted),Fs(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const t=this.mediaResolved;if(t&&t(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const i=this.media,s=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,Ji.clearKeyUriToKeyIdMap();const r=s.length;Oa.CDMCleanupPromise=Promise.all(s.map(e=>this.removeSession(e)).concat((null==i||null==(e=i.setMediaKeys(null))?void 0:e.catch(e=>{this.log(`Could not clear media keys: ${e}`),this.hls&&this.hls.trigger(P.ERROR,{type:k.OTHER_ERROR,details:w.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${e}`)})}))||Promise.resolve())).catch(e=>{this.log(`Could not close sessions and clear media keys: ${e}`),this.hls&&this.hls.trigger(P.ERROR,{type:k.OTHER_ERROR,details:w.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${e}`)})}).then(()=>{r&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(e,{sessionKeys:t}){if(t&&this.config.emeEnabled&&!this.keyFormatPromise){const e=t.reduce((e,t)=>(-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e),[]);this.log(`Selecting key-system from session-keys ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:i,decryptdata:s}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${Z((null==s?void 0:s.keyId)||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(e);r>-1&&this.mediaKeySessions.splice(r,1);const{keyStatusTimeouts:n}=e;n&&Object.keys(n).forEach(e=>self.clearTimeout(n[e]));const{drmSystemOptions:a}=this.config,o=function(e){var t;return!(!e||"persistent-license"!==e.sessionType&&(null==(t=e.sessionTypes)||!t.some(e=>"persistent-license"===e)))}(a)?new Promise((e,i)=>{self.setTimeout(()=>i(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(e).catch(i)}):Promise.resolve();return o.catch(e=>{this.log(`Could not remove session: ${e}`),this.hls&&this.hls.trigger(P.ERROR,{type:k.OTHER_ERROR,details:w.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${e}`)})}).then(()=>t.close()).catch(e=>{this.log(`Could not close session: ${e}`),this.hls&&this.hls.trigger(P.ERROR,{type:k.OTHER_ERROR,details:w.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${e}`)})})}return Promise.resolve()}}function Fa(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(null===e.keyId)throw new Error("keyId is null");return Z(e.keyId)}function Ua(e,t){return e.keyId&&t.mediaKeysSession.keyStatuses.has(e.keyId)?t.mediaKeysSession.keyStatuses.get(e.keyId):e.matches(t.decryptdata)?t.keyStatus:void 0}Oa.CDMCleanupPromise=void 0;class Na extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}function Ba(e,t){const i="output-restricted"===e,s=i?w.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:w.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Na({type:k.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:t},i?"HDCP level output restricted":`key status changed to "${e}"`)}function $a(e,t){let i;try{i=new Event("addtrack")}catch(e){i=document.createEvent("Event"),i.initEvent("addtrack",!1,!1)}i.track=e,t.dispatchEvent(i)}function Va(e,t){const i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error(`addCue is failed for: ${t}`)}catch(i){z.debug(`[texttrack-utils]: ${i}`);try{const i=new self.TextTrackCue(t.startTime,t.endTime,t.text);i.id=t.id,e.addCue(i)}catch(e){z.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${e}`)}}"disabled"===i&&(e.mode=i)}function Ga(e,t){const i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues)for(let i=e.cues.length;i--;)t&&e.cues[i].removeEventListener("enter",t),e.removeCue(e.cues[i]);"disabled"===i&&(e.mode=i)}function Ha(e,t,i,s){const r=e.mode;if("disabled"===r&&(e.mode="hidden"),e.cues&&e.cues.length>0){const r=function(e,t,i){const s=[],r=function(e,t){if(t<=e[0].startTime)return 0;const i=e.length-1;if(t>e[i].endTime)return-1;let s,r=0,n=i;for(;r<=n;)if(s=Math.floor((n+r)/2),t<e[s].startTime)n=s-1;else{if(!(t>e[s].startTime&&r<i))return s;r=s+1}return e[r].startTime-t<t-e[n].startTime?r:n}(e,t);if(r>-1)for(let n=r,a=e.length;n<a;n++){const r=e[n];if(r.startTime>=t&&r.endTime<=i)s.push(r);else if(r.startTime>i)return s}return s}(e.cues,t,i);for(let t=0;t<r.length;t++)s&&!s(r[t])||e.removeCue(r[t])}"disabled"===r&&(e.mode=r)}function Ka(e){const t=[];for(let i=0;i<e.length;i++){const s=e[i];"subtitles"!==s.kind&&"captions"!==s.kind||!s.label||t.push(e[i])}return t}function ja(e){let t=5381,i=e.length;for(;i;)t=33*t^e.charCodeAt(--i);return(t>>>0).toString()}const Wa=.025;let qa=function(e){return e[e.Point=0]="Point",e[e.Range=1]="Range",e}({});function Ya(e,t,i){return`${e.identifier}-${i+1}-${ja(t)}`}class za{constructor(e,t){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=t,this.dateRange=e,this.setDateRange(e)}setDateRange(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)}reset(){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)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;const i=this.playoutLimit;if(e<=0||isNaN(i))return!1;if(0===i)return!0;return((null==(t=this.assetList[e])?void 0:t.startOffset)||0)>i}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return Xa(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(0===this.startTime||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime;return t-Xa(t,e)<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=L(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const t=this.resumeAnchor;if(t)return Xa(e,t)}return e}get appendInPlace(){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)<Wa))}set appendInPlace(e){this.appendInPlaceStarted?this.resetOnResume=!e:this.appendInPlaceDisabled=!e}get timelineStart(){return null!==this._timelineStart?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let t;return t=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?qa.Range:qa.Point}get supplementsPrimary(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}get contentMayVary(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||null!==this.assetListResponse}toString(){return`["${(e=this).identifier}" ${e.cue.pre?"<pre>":e.cue.post?"<post>":""}${e.timelineStart.toFixed(2)}-${e.resumeTime.toFixed(2)}]`;var e}}function Xa(e,t){return e-t.start<t.duration/2&&!(Math.abs(e-(t.start+t.duration))<Wa)?t.start:t.start+t.duration}function Qa(e,t,i){const s=new self.URL(e,i);return"data:"!==s.protocol&&s.searchParams.set("_HLS_primary_id",t),s}function Ja(e,t){for(;null!=(i=e.assetList[++t])&&i.error;)var i;return t}function Za(e){const t=e.timelineStart,i=e.duration||0;return`["${e.identifier}" ${t.toFixed(2)}-${(t+i).toFixed(2)}]`}class eo{constructor(e,t,i,s){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=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(P.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new e(t);this.interstitial=i,this.assetItem=s;const n=()=>{this.hasDetails=!0};r.once(P.LEVEL_LOADED,n),r.once(P.AUDIO_TRACK_LOADED,n),r.once(P.SUBTITLE_TRACK_LOADED,n),r.on(P.MEDIA_ATTACHING,(e,{media:t})=>{this.removeMediaListeners(),this.mediaAttached=t;this.interstitial.playoutLimit&&(t.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(P.BUFFER_APPENDED,()=>{const e=this.bufferedEnd;this.reachedPlayout(e)&&(this._bufferedEosTime=e,r.trigger(P.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=Qa(t,e.config.primarySessionId||"").href}catch(e){}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if(null!=(t=this.hls)&&t.bufferedToEnd)return!0;if(!e)return!1;const i=Math.min(this._bufferedEosTime||1/0,this.duration),s=this.timelineOffset,r=yi.bufferInfo(e,s,0);return this.getAssetTime(r.end)>=i-.02}reachedPlayout(e){const t=this.interstitial.playoutLimit;return this.startOffset+e>=t}get destroyed(){var e;return!(null!=(e=this.hls)&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return(null==(e=this.hls)?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=yi.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;if(!e)return 0;const t=this.interstitial.playoutLimit;if(t){const i=t-this.startOffset;if(i>0&&i<e)return i}return e}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return(null==(e=this.hls)?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const i=e-t;if(Math.abs(i)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,e-t),i)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){var e;this.mediaAttached&&(null!=(e=this.hls)&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd))}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),null==(t=this.hls)||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,null==(e=this.hls)||e.detachMedia()}resumeBuffering(){var e;null==(e=this.hls)||e.resumeBuffering()}pauseBuffering(){var e;null==(e=this.hls)||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),(null==(e=this.hls)?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const t=e=>delete e.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,i){var s;null==(s=this.hls)||s.on(e,t)}once(e,t,i){var s;null==(s=this.hls)||s.once(e,t)}off(e,t,i){var s;null==(s=this.hls)||s.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${Za(this.assetItem)} ${null==(e=this.hls)?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}class to extends H{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((i,s)=>e<=s.startOffset&&t>s.startOffset?(delete s.error,i+1):i,0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let i=-1;e.nextEvent?i=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(i=this.findEventIndex(e.previousEvent.identifier)+1);const s=this.items;if(s)for(s[i]||(void 0===t&&(t=e.start),i=this.findItemIndexAtTime(t));i>=0&&null!=(r=s[i])&&r.event;){var r;i--}return i}findItemIndexAtTime(e,t){const i=this.items;if(i)for(let s=0;s<i.length;s++){let r=i[s];if(t&&"primary"!==t&&(r=r[t]),e===r.start||e>r.start&&e<r.end)return s}return-1}findJumpRestrictedIndex(e,t){const i=this.items;if(i)for(let s=e;s<=t&&i[s];s++){const e=i[s].event;if(null!=e&&e.restrictions.jump&&!e.appendInPlace)return s}return-1}findEventIndex(e){const t=this.items;if(t)for(let s=t.length;s--;){var i;if((null==(i=t[s].event)?void 0:i.identifier)===e)return s}return-1}findAssetIndex(e,t){const i=e.assetList,s=i.length;if(s>1)for(let e=0;e<s;e++){const r=i[e];if(!r.error){const i=r.timelineStart;if(t===i||t>i&&(t<i+(r.duration||0)||e===s-1))return e}}return 0}get assetIdAtEnd(){var e;const t=null==(e=this.items)||null==(e=e[this.length-1])?void 0:e.event;if(t){const e=t.assetList,i=e[e.length-1];if(i)return i.identifier}return null}parseInterstitialDateRanges(e,t){const i=e.main.details,{dateRanges:s}=i,r=this.events,n=this.parseDateRanges(s,{url:i.url},t),a=Object.keys(s),o=r?r.filter(e=>!a.includes(e.identifier)):[];n.length&&n.sort((e,t)=>{const i=e.cue.pre,s=e.cue.post,r=t.cue.pre,n=t.cue.post;if(i&&!r)return-1;if(r&&!i)return 1;if(s&&!n)return 1;if(n&&!s)return-1;if(!(i||r||s||n)){const i=e.startTime,s=t.startTime;if(i!==s)return i-s}return e.dateRange.tagOrder-t.dateRange.tagOrder}),this.events=n,o.forEach(e=>{this.removeEvent(e)}),this.updateSchedule(e,o)}updateSchedule(e,t=[],i=!1){const s=this.events||[];if(s.length||t.length||this.length<2){const r=this.items,n=this.parseSchedule(s,e);(i||t.length||(null==r?void 0:r.length)!==n.length||n.some((e,t)=>Math.abs(e.playout.start-r[t].playout.start)>.005||Math.abs(e.playout.end-r[t].playout.end)>.005))&&(this.items=n,this.onScheduleUpdate(t,r))}}parseDateRanges(e,t,i){const s=[],r=Object.keys(e);for(let n=0;n<r.length;n++){const a=r[n],o=e[a];if(o.isInterstitial){let e=this.eventMap[a];e?e.setDateRange(o):(e=new za(o,t),this.eventMap[a]=e,!1===i&&(e.appendInPlace=i)),s.push(e)}}return s}parseSchedule(e,t){const i=[],s=t.main.details,r=s.live?1/0:s.edge;let n=0;if((e=e.filter(e=>!(e.error||e.cue.once&&e.hasPlayed))).length){this.resolveOffsets(e,t);let s=0,o=0;if(e.forEach((t,a)=>{const l=t.cue.pre,d=t.cue.post,c=e[a-1]||null,u=t.appendInPlace,h=d?r:t.startOffset,f=t.duration,g=t.timelineOccupancy===qa.Range?f:0,p=t.resumptionOffset,m=(null==c?void 0:c.startTime)===h,v=h+t.cumulativeDuration;let y=u?v+f:h+p;if(l||!d&&h<=0){const e=o;o+=g,t.timelineStart=v;const s=n;n+=f,i.push({event:t,start:v,end:y,playout:{start:s,end:n},integrated:{start:e,end:o}})}else{if(!(h<=r))return;{if(!m){const r=h-s;if(r>.033){const l=s,d=o;o+=r;const c=n;n+=r;const u={previousEvent:e[a-1]||null,nextEvent:t,start:l,end:l+r,playout:{start:c,end:n},integrated:{start:d,end:o}};i.push(u)}else r>0&&c&&(c.cumulativeDuration+=r,i[i.length-1].end=h)}d&&(y=v),t.timelineStart=v;const r=o;o+=g;const l=n;n+=f,i.push({event:t,start:v,end:y,playout:{start:l,end:n},integrated:{start:r,end:o}})}}const T=t.resumeTime;s=d||T>r?r:T}),s<r){var a;const e=s,t=o,l=r-s;o+=l;const d=n;n+=l,i.push({previousEvent:(null==(a=i[i.length-1])?void 0:a.event)||null,nextEvent:null,start:s,end:e+l,playout:{start:d,end:n},integrated:{start:t,end:o}})}this.setDurations(r,n,o)}else{const e=0;i.push({previousEvent:null,nextEvent:null,start:e,end:r,playout:{start:e,end:r},integrated:{start:e,end:r}}),this.setDurations(r,r,r)}return i}setDurations(e,t,i){this.durations={primary:e,playout:t,integrated:i}}resolveOffsets(e,t){const i=t.main.details,s=i.live?1/0:i.edge;let r=0,n=-1;e.forEach((a,o)=>{const l=a.cue.pre,d=a.cue.post,c=l?0:d?s:a.startTime;this.updateAssetDurations(a);if(n===c?a.cumulativeDuration=r:(r=0,n=c),!d&&a.snapOptions.in&&(a.resumeAnchor=Pt(null,i.fragments,a.startOffset+a.resumptionOffset,0,0)||void 0),a.appendInPlace&&!a.appendInPlaceStarted){this.primaryCanResumeInPlaceAt(a,t)||(a.appendInPlace=!1)}if(!a.appendInPlace&&o+1<e.length){e[o+1].startTime-e[o].resumeTime<.033&&(e[o+1].appendInPlace=!1,e[o+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${a}`))}const u=L(a.resumeOffset)?a.resumeOffset:a.duration;r+=u})}primaryCanResumeInPlaceAt(e,t){const i=e.resumeTime,s=e.startTime+e.resumptionOffset;if(Math.abs(i-s)>Wa)return this.log(`"${e.identifier}" resumption ${i} not aligned with estimated timeline end ${s}`),!1;return!Object.keys(t).some(s=>{const r=t[s].details,n=r.edge;if(i>=n)return this.log(`"${e.identifier}" resumption ${i} past ${s} playlist end ${n}`),!1;const a=Pt(null,r.fragments,i);if(!a)return this.log(`"${e.identifier}" resumption ${i} does not align with any fragments in ${s} playlist (${r.fragStart}-${r.fragmentEnd})`),!0;const o="audio"===s?.175:0;return!(Math.abs(a.start-i)<Wa+o||Math.abs(a.end-i)<Wa+o)&&(this.log(`"${e.identifier}" resumption ${i} not aligned with ${s} fragment bounds (${a.start}-${a.end} sn: ${a.sn} cc: ${a.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let i=0,s=!1,r=!1;for(let n=0;n<e.assetList.length;n++){const a=e.assetList[n],o=t+i;a.startOffset=i,a.timelineStart=o,s||(s=null===a.duration),r||(r=!!a.error);i+=a.error?0:a.duration||0}e.duration=s&&!r?Math.max(i,e.duration):i}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function io(e){return`[${e.event?'"'+e.event.identifier+'"':"primary"}: ${e.start.toFixed(2)}-${e.end.toFixed(2)}]`}class so{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const i=e.assetListUrl;let s;try{s=Qa(i,this.hls.sessionId,e.baseUrl)}catch(t){const s=this.assignAssetListError(e,w.ASSET_LIST_LOAD_ERROR,t,i);return void this.hls.trigger(P.ERROR,s)}t&&"data:"!==s.protocol&&s.searchParams.set("_HLS_start_offset",""+t);const r=this.hls.config,n=new(0,r.loader)(r),a={responseType:"json",url:s.href},o=r.interstitialAssetListLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(t,i,s,r)=>{const n=t.data,a=null==n?void 0:n.ASSETS;if(!Array.isArray(a)){const t=this.assignAssetListError(e,w.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),s.url,i,r);return void this.hls.trigger(P.ERROR,t)}e.assetListResponse=n,this.hls.trigger(P.ASSET_LIST_LOADED,{event:e,assetListResponse:n,networkDetails:r})},onError:(t,i,s,r)=>{const n=this.assignAssetListError(e,w.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${t.code} ${t.text} (${i.url})`),i.url,r,s);this.hls.trigger(P.ERROR,n)},onTimeout:(t,i,s)=>{const r=this.assignAssetListError(e,w.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${i.url})`),i.url,t,s);this.hls.trigger(P.ERROR,r)}};return n.load(a,l,d),this.hls.trigger(P.ASSET_LIST_LOADING,{event:e}),n}assignAssetListError(e,t,i,s,r,n){return e.error=i,{type:k.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:s,error:i,networkDetails:n,stats:r}}}function ro(e){var t;null==e||null==(t=e.play())||t.catch(()=>{})}function no(e,t){return`[${e}] Advancing timeline position to ${t}`}class ao{constructor(e){this.buffered=void 0;const t=(t,i,s)=>{if((i>>>=0)>s-1)throw new DOMException(`Failed to execute '${t}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${s})`);return e[i][t]};this.buffered={get length(){return e.length},end:i=>t("end",i,e.length),start:i=>t("start",i,e.length)}}}const oo={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},lo=e=>String.fromCharCode(oo[e]||e),co=15,uo=100,ho={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},fo={17:2,18:4,21:6,22:8,23:10,19:13,20:15},go={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},po={25:2,26:4,29:6,30:8,31:10,27:13,28:15},mo=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class vo{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const i="function"==typeof t?t():t;z.log(`${this.time} [${e}] ${i}`)}}}const yo=function(e){const t=[];for(let i=0;i<e.length;i++)t.push(e[i].toString(16));return t};class To{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let i=0;i<t.length;i++){const s=t[i];e.hasOwnProperty(s)&&(this[s]=e[s])}}isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class Eo{constructor(){this.uchar=" ",this.penState=new To}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return" "===this.uchar&&this.penState.isDefault()}}class So{constructor(e){this.chars=[],this.pos=0,this.currPenState=new To,this.cueStartTime=null,this.logger=void 0;for(let e=0;e<uo;e++)this.chars.push(new Eo);this.logger=e}equals(e){for(let t=0;t<uo;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<uo;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<uo;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>uo&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=uo)}moveCursor(e){const t=this.pos+e;if(e>1)for(let e=this.pos+1;e<t+1;e++)this.chars[e].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=lo(e);this.pos>=uo?this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!"):(this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1))}clearFromPos(e){let t;for(t=e;t<uo;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let i=0;i<uo;i++){const s=this.chars[i].uchar;" "!==s&&(t=!1),e.push(s)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e);this.chars[this.pos].setPenState(this.currPenState)}}class Ao{constructor(e){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<co;t++)this.rows.push(new So(e));this.logger=e}reset(){for(let e=0;e<co;e++)this.rows[e].clear();this.currRow=14}equals(e){let t=!0;for(let i=0;i<co;i++)if(!this.rows[i].equals(e.rows[i])){t=!1;break}return t}copy(e){for(let t=0;t<co;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<co;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e);this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+Tt(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let e=0;e<co;e++)this.rows[e].clear();const e=this.currRow+1-this.nrRollUpRows,i=this.lastOutputScreen;if(i){const s=i.rows[e].cueStartTime,r=this.logger.time;if(null!==s&&null!==r&&s<r)for(let s=0;s<this.nrRollUpRows;s++)this.rows[t-this.nrRollUpRows+s+1].copy(i.rows[e+s])}}this.currRow=t;const i=this.rows[this.currRow];if(null!==e.indent){const t=e.indent,s=Math.max(t-1,0);i.setCursor(e.indent),e.color=i.chars[s].penState.foreground}const s={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(s)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+Tt(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let i="",s=-1;for(let i=0;i<co;i++){const r=this.rows[i].getTextString();r&&(s=i+1,e?t.push("Row "+s+": '"+r+"'"):t.push(r.trim()))}return t.length>0&&(i=e?"["+t.join(" | ")+"]":t.join("\n")),i}getTextAndFormat(){return this.rows}}class bo{constructor(e,t,i){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=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new Ao(i),this.nonDisplayedMemory=new Ao(i),this.lastOutputScreen=new Ao(i),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}reset(){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}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"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)}insertChars(e){for(let t=0;t<e.length;t++)this.writeScreen.insertChar(e[t]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2==1,t.italics=e>=46,t.italics)t.foreground="white";else{const i=Math.floor(e/2)-16,s=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=s[i]}this.logger.log(2,"MIDROW: "+Tt(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const 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))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class Lo{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;const s=this.logger=new vo;this.channels=[null,new bo(e,t,s),new bo(e+1,i,s)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let e=0;e<t.length;e+=2){const i=127&t[e],s=127&t[e+1];let r=!1,n=null;if(0===i&&0===s)continue;this.logger.log(3,()=>"["+yo([t[e],t[e+1]])+"] -> ("+yo([i,s])+")");const a=this.cmdHistory;if(i>=16&&i<=31){if(Io(i,s,a)){Ro(null,null,a),this.logger.log(3,()=>"Repeated command ("+yo([i,s])+") is dropped");continue}Ro(i,s,this.cmdHistory),r=this.parseCmd(i,s),r||(r=this.parseMidrow(i,s)),r||(r=this.parsePAC(i,s)),r||(r=this.parseBackgroundAttributes(i,s))}else Ro(null,null,a);if(!r&&(n=this.parseChars(i,s),n)){const e=this.currentChannel;if(e&&e>0){this.channels[e].insertChars(n)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}r||n||this.logger.log(2,()=>"Couldn't parse cleaned data "+yo([i,s])+" orig: "+yo([t[e],t[e+1]]))}}parseCmd(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;const i=20===e||21===e||23===e?1:2,s=this.channels[i];return 20===e||21===e||28===e||29===e?32===t?s.ccRCL():33===t?s.ccBS():34===t?s.ccAOF():35===t?s.ccAON():36===t?s.ccDER():37===t?s.ccRU(2):38===t?s.ccRU(3):39===t?s.ccRU(4):40===t?s.ccFON():41===t?s.ccRDC():42===t?s.ccTR():43===t?s.ccRTD():44===t?s.ccEDM():45===t?s.ccCR():46===t?s.ccENM():47===t&&s.ccEOC():s.ccTO(t-32),this.currentChannel=i,!0}parseMidrow(e,t){let i=0;if((17===e||25===e)&&t>=32&&t<=47){if(i=17===e?1:2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const s=this.channels[i];return!!s&&(s.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+yo([e,t])+")"),!0)}return!1}parsePAC(e,t){let i;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127)&&!((16===e||24===e)&&t>=64&&t<=95))return!1;const s=e<=23?1:2;i=t>=64&&t<=95?1===s?ho[e]:go[e]:1===s?fo[e]:po[e];const r=this.channels[s];return!!r&&(r.setPAC(this.interpretPAC(i,t)),this.currentChannel=s,!0)}interpretPAC(e,t){let i;const s={color:null,italics:!1,indent:null,underline:!1,row:e};return i=t>95?t-96:t-64,s.underline=!(1&~i),i<=13?s.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(s.italics=!0,s.color="white"):s.indent=4*Math.floor((i-16)/2),s}parseChars(e,t){let i,s=null,r=null;if(e>=25?(i=2,r=e-8):(i=1,r=e),r>=17&&r<=19){let e;e=17===r?t+80:18===r?t+112:t+144,this.logger.log(2,()=>"Special char '"+lo(e)+"' in channel "+i),s=[e]}else e>=32&&e<=127&&(s=0===t?[e]:[e,t]);return s&&this.logger.log(3,()=>"Char codes = "+yo(s).join(",")),s}parseBackgroundAttributes(e,t){if(!((16===e||24===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=45&&t<=47))return!1;let i;const s={};16===e||24===e?(i=Math.floor((t-32)/2),s.background=mo[i],t%2==1&&(s.background=s.background+"_semi")):45===t?s.background="transparent":(s.foreground="black",47===t&&(s.underline=!0));const r=e<=23?1:2;return this.channels[r].setBkgData(s),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}Ro(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const i=this.channels[t];i&&i.cueSplitAtTime(e)}}}function Ro(e,t,i){i.a=e,i.b=t}function Io(e,t,i){return i.a===e&&i.b===t}var ko=function(){if(null!=Bi&&Bi.VTTCue)return self.VTTCue;const e=["","lr","rl"],t=["start","middle","end","left","right"];function i(e,t){if("string"!=typeof t)return!1;if(!Array.isArray(e))return!1;const i=t.toLowerCase();return!!~e.indexOf(i)&&i}function s(e){return i(t,e)}function r(e,...t){let i=1;for(;i<arguments.length;i++){const t=arguments[i];for(const i in t)e[i]=t[i]}return e}function n(t,n,a){const o=this,l={enumerable:!0};o.hasBeenReset=!1;let d="",c=!1,u=t,h=n,f=a,g=null,p="",m=!0,v="auto",y="start",T=50,E="middle",S=50,A="middle";Object.defineProperty(o,"id",r({},l,{get:function(){return d},set:function(e){d=""+e}})),Object.defineProperty(o,"pauseOnExit",r({},l,{get:function(){return c},set:function(e){c=!!e}})),Object.defineProperty(o,"startTime",r({},l,{get:function(){return u},set:function(e){if("number"!=typeof e)throw new TypeError("Start time must be set to a number.");u=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",r({},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",r({},l,{get:function(){return f},set:function(e){f=""+e,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",r({},l,{get:function(){return g},set:function(e){g=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",r({},l,{get:function(){return p},set:function(t){const s=function(t){return i(e,t)}(t);if(!1===s)throw new SyntaxError("An invalid or illegal string was specified.");p=s,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",r({},l,{get:function(){return m},set:function(e){m=!!e,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",r({},l,{get:function(){return v},set:function(e){if("number"!=typeof e&&"auto"!==e)throw new SyntaxError("An invalid number or illegal string was specified.");v=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",r({},l,{get:function(){return y},set:function(e){const t=s(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");y=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",r({},l,{get:function(){return T},set:function(e){if(e<0||e>100)throw new Error("Position must be between 0 and 100.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",r({},l,{get:function(){return E},set:function(e){const t=s(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");E=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",r({},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",r({},l,{get:function(){return A},set:function(e){const t=s(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");A=t,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}();class wo{decode(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Po(e){function t(e,t,i,s){return 3600*(0|e)+60*(0|t)+(0|i)+parseFloat(s||0)}const i=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return i?parseFloat(i[2])>59?t(i[2],i[3],0,i[4]):t(i[1],i[2],i[3],i[4]):null}class Do{constructor(){this.values=Object.create(null)}set(e,t){this.get(e)||""===t||(this.values[e]=t)}get(e,t,i){return i?this.has(e)?this.values[e]:t[i]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,i){for(let s=0;s<i.length;++s)if(t===i[s]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const i=parseFloat(t);if(i>=0&&i<=100)return this.set(e,i),!0}return!1}}function xo(e,t,i,s){const r=s?e.split(s):[e];for(const e in r){if("string"!=typeof r[e])continue;const s=r[e].split(i);if(2!==s.length)continue;t(s[0],s[1])}}const Co=new ko(0,0,""),_o="middle"===Co.align?"middle":"center";function Mo(e,t,i){const s=e;function r(){const t=Po(e);if(null===t)throw new Error("Malformed timestamp: "+s);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function n(){e=e.replace(/^\s+/,"")}if(n(),t.startTime=r(),n(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+s);e=e.slice(3),n(),t.endTime=r(),n(),function(e,t){const s=new Do;xo(e,function(e,t){let r;switch(e){case"region":for(let r=i.length-1;r>=0;r--)if(i[r].id===t){s.set(e,i[r].region);break}break;case"vertical":s.alt(e,t,["rl","lr"]);break;case"line":r=t.split(","),s.integer(e,r[0]),s.percent(e,r[0])&&s.set("snapToLines",!1),s.alt(e,r[0],["auto"]),2===r.length&&s.alt("lineAlign",r[1],["start",_o,"end"]);break;case"position":r=t.split(","),s.percent(e,r[0]),2===r.length&&s.alt("positionAlign",r[1],["start",_o,"end","line-left","line-right","auto"]);break;case"size":s.percent(e,t);break;case"align":s.alt(e,t,["start",_o,"end","left","right"])}},/:/,/\s/),t.region=s.get("region",null),t.vertical=s.get("vertical","");let r=s.get("line","auto");"auto"===r&&-1===Co.line&&(r=-1),t.line=r,t.lineAlign=s.get("lineAlign","start"),t.snapToLines=s.get("snapToLines",!0),t.size=s.get("size",100),t.align=s.get("align",_o);let n=s.get("position","auto");"auto"===n&&50===Co.position&&(n="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=n}(e,t)}function Oo(e){return e.replace(/<br(?: \/)?>/gi,"\n")}class Fo{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new wo,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;function i(){let e=t.buffer,i=0;for(e=Oo(e);i<e.length&&"\r"!==e[i]&&"\n"!==e[i];)++i;const s=e.slice(0,i);return"\r"===e[i]&&++i,"\n"===e[i]&&++i,t.buffer=e.slice(i),s}function s(e){xo(e,function(e,t){},/:/)}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{let e="";if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;e=i();const s=e.match(/^()?WEBVTT([ \t].*)?$/);if(null==s||!s[0])throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let r=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(r?r=!1:e=i(),t.state){case"HEADER":/:/.test(e)?s(e):e||(t.state="ID");continue;case"NOTE":e||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(e)){t.state="NOTE";break}if(!e)continue;if(t.cue=new ko(0,0,""),t.state="CUE",-1===e.indexOf("--\x3e")){t.cue.id=e;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{Mo(e,t.cue,t.regionList)}catch(e){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const i=-1!==e.indexOf("--\x3e");if(!e||i&&(r=!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+=e}continue;case"BADCUE":e||(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}flush(){const 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}}const Uo=/\r\n|\n\r|\n|\r/g,No=function(e,t,i=0){return e.slice(i,i+t.length)===t};function Bo(e,t,i){return ja(e.toString())+ja(t.toString())+ja(i)}function $o(e,t,i,s,r,n,a){const o=new Fo,l=J(new Uint8Array(e)).trim().replace(Uo,"\n").split("\n"),d=[],c=t?function(e,t=1){return ln(e,9e4,1/t)}(t.baseTime,t.timescale):0;let u,h="00:00.000",f=0,g=0,p=!0;o.oncue=function(e){const n=i[s];let a=i.ccOffset;const o=(f-c)/9e4;if(null!=n&&n.new&&(void 0!==g?a=i.ccOffset=n.start:function(e,t,i){let s=e[t],r=e[s.prevCC];if(!r||!r.new&&s.new)return e.ccOffset=e.presentationOffset=s.start,void(s.new=!1);for(;null!=(n=r)&&n.new;){var n;e.ccOffset+=s.start-r.start,s.new=!1,s=r,r=e[s.prevCC]}e.presentationOffset=i}(i,s,o)),o){if(!t)return void(u=new Error("Missing initPTS for VTT MPEGTS"));a=o-i.presentationOffset}const l=e.endTime-e.startTime,h=mn(9e4*(e.startTime+a-g),9e4*r)/9e4;e.startTime=Math.max(h,0),e.endTime=Math.max(h+l,0);const p=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(p)),e.id||(e.id=Bo(e.startTime,e.endTime,p)),e.endTime>0&&d.push(e)},o.onparsingerror=function(e){u=e},o.onflush=function(){u?a(u):n(d)},l.forEach(e=>{if(p){if(No(e,"X-TIMESTAMP-MAP=")){p=!1,e.slice(16).split(",").forEach(e=>{No(e,"LOCAL:")?h=e.slice(6):No(e,"MPEGTS:")&&(f=parseInt(e.slice(7)))});try{g=function(e){let t=parseInt(e.slice(-3));const i=parseInt(e.slice(-6,-4)),s=parseInt(e.slice(-9,-7)),r=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(L(t)&&L(i)&&L(s)&&L(r)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=6e4*s,t+=36e5*r,t}(h)/1e3}catch(e){u=e}return}""===e&&(p=!1)}o.parse(e+"\n")}),o.flush()}const Vo="stpp.ttml.im1t",Go=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Ho=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Ko={left:"start",center:"center",right:"end",start:"start",end:"end"};function jo(e,t,i,s){const r=Ae(new Uint8Array(e),["mdat"]);if(0===r.length)return void s(new Error("Could not parse IMSC1 mdat"));const n=r.map(e=>J(e)),a=function(e,t,i=1,s=!1){return ln(e,t,1/i,s)}(t.baseTime,1,t.timescale);try{n.forEach(e=>i(function(e,t){const i=(new DOMParser).parseFromString(e,"text/xml"),s=i.getElementsByTagName("tt")[0];if(!s)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(r).reduce((e,t)=>(e[t]=s.getAttribute(`ttp:${t}`)||r[t],e),{}),a="preserve"!==s.getAttribute("xml:space"),o=qo(Wo(s,"styling","style")),l=qo(Wo(s,"layout","region")),d=Wo(s,"body","[begin]");return[].map.call(d,e=>{const i=Yo(e,a);if(!i||!e.hasAttribute("begin"))return null;const s=Qo(e.getAttribute("begin"),n),r=Qo(e.getAttribute("dur"),n);let d=Qo(e.getAttribute("end"),n);if(null===s)throw Xo(e);if(null===d){if(null===r)throw Xo(e);d=s+r}const c=new ko(s-t,d-t,i);c.id=Bo(c.startTime,c.endTime,c.text);const u=function(e,t,i){const s="http://www.w3.org/ns/ttml#styling";let r=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;a&&i.hasOwnProperty(a)&&(r=i[a]);return n.reduce((i,n)=>{const a=zo(t,s,n)||zo(e,s,n)||zo(r,s,n);return a&&(i[n]=a),i},{})}(l[e.getAttribute("region")],o[e.getAttribute("style")],o),{textAlign:h}=u;if(h){const e=Ko[h];e&&(c.lineAlign=e),c.align=h}return $(c,u),c}).filter(e=>null!==e)}(e,a)))}catch(e){s(e)}}function Wo(e,t,i){const s=e.getElementsByTagName(t)[0];return s?[].slice.call(s.querySelectorAll(i)):[]}function qo(e){return e.reduce((e,t)=>{const i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function Yo(e,t){return[].slice.call(e.childNodes).reduce((e,i,s)=>{var r;return"br"===i.nodeName&&s?e+"\n":null!=(r=i.childNodes)&&r.length?Yo(i,t):t?e+i.textContent.trim().replace(/\s+/g," "):e+i.textContent},"")}function zo(e,t,i){return e&&e.hasAttributeNS(t,i)?e.getAttributeNS(t,i):null}function Xo(e){return new Error(`Could not parse ttml timestamp ${e}`)}function Qo(e,t){if(!e)return null;let i=Po(e);return null===i&&(Go.test(e)?i=function(e,t){const i=Go.exec(e),s=(0|i[4])+(0|i[5])/t.subFrameRate;return 3600*(0|i[1])+60*(0|i[2])+(0|i[3])+s/t.frameRate}(e,t):Ho.test(e)&&(i=function(e,t){const i=Ho.exec(e),s=Number(i[1]);switch(i[2]){case"h":return 3600*s;case"m":return 60*s;case"ms":return 1e3*s;case"f":return s/t.frameRate;case"t":return s/t.tickRate}return s}(e,t))),i}class Jo{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,i){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}function Zo(e){return e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function el(e,t){return!!e&&e.kind===Zo(t)&&Cn(t,e)}function tl(e,t,i,s){return Math.min(t,s)-Math.max(e,i)}const il=/\s/,sl={newCue(e,t,i,s){const r=[];let n,a,o,l,d;const c=self.VTTCue||self.TextTrackCue;for(let h=0;h<s.rows.length;h++)if(n=s.rows[h],o=!0,l=0,d="",!n.isEmpty()){var u;for(let e=0;e<n.chars.length;e++)il.test(n.chars[e].uchar)&&o?l++:(d+=n.chars[e].uchar,o=!1);n.cueStartTime=t,t===i&&(i+=1e-4),l>=16?l--:l++;const s=Oo(d.trim()),f=Bo(t,i,s);null!=e&&null!=(u=e.cues)&&u.getCueById(f)||(a=new c(t,i,s),a.id=f,a.line=h+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),r.push(a))}return e&&r.length&&(r.sort((e,t)=>"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line),r.forEach(t=>Va(e,t))),r}};const rl=/(\d+)-(\d+)\/(\d+)/;class nl{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||al,this.controller=new self.AbortController,this.stats=new ne}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,i){const s=this.stats;if(s.loading.start)throw new Error("Loader can only be used once.");s.loading.start=self.performance.now();const r=function(e,t){const i={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers($({},e.headers))};e.rangeEnd&&i.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return i}(e,this.controller.signal),n="arraybuffer"===e.responseType,a=n?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,r),self.clearTimeout(this.requestTimeout),t.timeout=o&&L(o)?o:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,e,this.response))},t.timeout);(Ln(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(i=>{var r;this.response=this.loader=i;const a=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,e,this.response))},l-(a-s.loading.start)),!i.ok){const{status:e,statusText:t}=i;throw new ol(t||"fetch, bad network response",e,i)}s.loading.first=a,s.total=function(e){const t=e.get("Content-Range");if(t){const e=function(e){const t=rl.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(L(e))return e}const i=e.get("Content-Length");if(i)return parseInt(i)}(i.headers)||s.total;const o=null==(r=this.callbacks)?void 0:r.onProgress;return o&&L(t.highWaterMark)?this.loadProgressively(i,s,e,t.highWaterMark,o):n?i.arrayBuffer():"json"===e.responseType?i.json():i.text()}).then(i=>{var r,n;const o=this.response;if(!o)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const l=i[a];l&&(s.loaded=s.total=l);const d={url:o.url,data:i,code:o.status},c=null==(r=this.callbacks)?void 0:r.onProgress;c&&!L(t.highWaterMark)&&c(s,e,i,o),null==(n=this.callbacks)||n.onSuccess(d,s,e,o)}).catch(t=>{var i;if(self.clearTimeout(this.requestTimeout),s.aborted)return;const r=t&&t.code||0,n=t?t.message:null;null==(i=this.callbacks)||i.onError({code:r,text:n},e,t?t.details:null,s)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,i,s=0,r){const n=new Js,a=e.body.getReader(),o=()=>a.read().then(a=>{if(a.done)return n.dataLength&&r(t,i,n.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const l=a.value,d=l.length;return t.loaded+=d,d<s||n.dataLength?(n.push(l),n.dataLength>=s&&r(t,i,n.flush().buffer,e)):r(t,i,l.buffer,e),o()}).catch(()=>Promise.reject());return o()}}function al(e,t){return new self.Request(e.url,t)}class ol extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}const ll=/^age:\s*[\d.]+\s*$/im;class dl{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new ne,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const i=this.loader=new self.XMLHttpRequest,s=this.stats;s.loading.first=0,s.loaded=0,s.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(this.loader===i&&!this.stats.aborted)return r(i,t.url)}).catch(e=>{if(this.loader===i&&!this.stats.aborted)return i.open("GET",t.url,!0),r(i,t.url)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(e=>{var r;null==(r=this.callbacks)||r.onError({code:i.status,text:e.message},t,i,s)}):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);const s=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:n}=i.loadPolicy;if(s)for(const t in s)e.setRequestHeader(t,s[t]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=r&&L(r)?r:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:i}=this;if(!e||!t)return;const s=t.readyState,r=this.config;if(!i.aborted&&s>=2&&(0===i.loading.first&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),4===s)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const s=t.status,l="text"===t.responseType?t.responseText:null;if(s>=200&&s<300){const r=null!=l?l:t.response;if(null!=r){var n,a;i.loading.end=Math.max(self.performance.now(),i.loading.first);const o="arraybuffer"===t.responseType?r.byteLength:r.length;i.loaded=i.total=o,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first);const l=null==(n=this.callbacks)?void 0:n.onProgress;l&&l(i,e,r,t);const d={url:t.responseURL,data:r,code:s};return void(null==(a=this.callbacks)||a.onSuccess(d,i,e,t))}}const d=r.loadPolicy.errorRetry;var o;if(Bt(d,i.retry,!1,{url:e.url,data:void 0,code:s}))this.retry(d);else z.error(`${s} while loading ${e.url}`),null==(o=this.callbacks)||o.onError({code:s,text:t.statusText},e,t,i)}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry;if(Bt(e,this.stats.retry,!0))this.retry(e);else{var t;z.warn(`timeout while loading ${null==(t=this.context)?void 0:t.url}`);const e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:i}=this;this.retryDelay=Ut(e,i.retry),i.retry++,z.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==t?void 0:t.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&ll.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const cl=G(G({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:dl,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class extends H{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=e=>{var t;const{fragCurrent:i,partCurrent:s,hls:r}=this,{autoLevelEnabled:n,media:a}=r;if(!i||!a)return;const o=performance.now(),l=s?s.stats:i.stats,d=s?s.duration:i.duration,c=o-l.loading.start,u=r.minAutoLevel,h=i.level,f=this._nextAutoLevel;if(l.aborted||l.loaded&&l.loaded===l.total||h<=u)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!n)return;const g=f>-1&&f!==h,p=!!e||g;if(!p&&(a.paused||!a.playbackRate||!a.readyState))return;const m=r.mainForwardBufferInfo;if(!p&&null===m)return;const v=this.bwEstimator.getEstimateTTFB(),y=Math.abs(a.playbackRate);if(c<=Math.max(v,d/(2*y)*1e3))return;const T=m?m.len/y:0,E=l.loading.first?l.loading.first-l.loading.start:-1,S=l.loaded&&E>-1,A=this.getBwEstimate(),b=r.levels,R=b[h],I=Math.max(l.loaded,Math.round(d*(i.bitrate||R.averageBitrate)/8));let k=S?c-E:c;k<1&&S&&(k=Math.min(c,8*l.loaded/A));const w=S?1e3*l.loaded/k:0,D=v/1e3,x=w?(I-l.loaded)/w:8*I/A+D;if(x<=T)return;const C=w?8*w:A,_=!0===(null==(t=(null==e?void 0:e.details)||this.hls.latestLevelDetails)?void 0:t.live),M=this.hls.config.abrBandWidthUpFactor;let O,F=Number.POSITIVE_INFINITY;for(O=h-1;O>u;O--){const e=b[O].maxBitrate,t=!b[O].details||_;if(F=this.getTimeToLoadFrag(D,C,d*e,t),F<Math.min(T,d+D))break}if(F>=x)return;if(F>10*d)return;S?this.bwEstimator.sample(c-Math.min(v,E),l.loaded):this.bwEstimator.sampleTTFB(c);const U=b[O].maxBitrate;this.getBwEstimate()*M>U&&this.resetEstimator(U);const N=this.findBestLevel(U,u,O,0,T,1,1);N>-1&&(O=N),this.warn(`Fragment ${i.sn}${s?" part "+s.index:""} of level ${h} is loading too slowly;\n Fragment duration: ${i.duration.toFixed(3)}\n Time to underbuffer: ${T.toFixed(3)} s\n Estimated load time for current fragment: ${x.toFixed(3)} s\n Estimated load time for down switch fragment: ${F.toFixed(3)} s\n TTFB estimate: ${0|E} ms\n Current BW estimate: ${L(A)?0|A:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${O} @ ${0|U} bps`),r.nextLoadLevel=r.nextAutoLevel=O,this.clearTimer();const B=()=>{if(this.clearTimer(),this.fragCurrent===i&&this.hls.loadLevel===O&&O>0){const e=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${O>0?"and switching down":""}\n Fragment duration: ${i.duration.toFixed(3)} s\n Time to underbuffer: ${e.toFixed(3)} s`),i.abortRequests(),this.fragCurrent=this.partCurrent=null,O>u){let t=this.findBestLevel(this.hls.levels[u].bitrate,u,O,0,e,1,1);-1===t&&(t=u),this.hls.nextLoadLevel=this.hls.nextAutoLevel=t,this.resetEstimator(this.hls.levels[t].bitrate)}}};g||x>2*F?B():this.timer=self.setInterval(B,1e3*F),r.trigger(P.FRAG_LOAD_EMERGENCY_ABORTED,{frag:i,part:s,stats:l})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new N(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(P.MANIFEST_LOADING,this.onManifestLoading,this),e.on(P.FRAG_LOADING,this.onFragLoading,this),e.on(P.FRAG_LOADED,this.onFragLoaded,this),e.on(P.FRAG_BUFFERED,this.onFragBuffered,this),e.on(P.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(P.LEVEL_LOADED,this.onLevelLoaded,this),e.on(P.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(P.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(P.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(P.MANIFEST_LOADING,this.onManifestLoading,this),e.off(P.FRAG_LOADING,this.onFragLoading,this),e.off(P.FRAG_LOADED,this.onFragLoaded,this),e.off(P.FRAG_BUFFERED,this.onFragBuffered,this),e.off(P.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(P.LEVEL_LOADED,this.onLevelLoaded,this),e.off(P.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(P.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(P.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const i=t.frag;if(!this.ignoreFragment(i)){var s;if(!i.bitrateTest)this.fragCurrent=i,this.partCurrent=null!=(s=t.part)?s:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case w.BUFFER_ADD_CODEC_ERROR:case w.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case w.FRAG_LOAD_TIMEOUT:{const e=t.frag,{fragCurrent:i,partCurrent:s}=this;if(e&&i&&e.sn===i.sn&&e.level===i.level){const t=performance.now(),i=s?s.stats:e.stats,r=t-i.loading.start,n=i.loading.first?i.loading.first-i.loading.start:-1;if(i.loaded&&n>-1){const e=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(r-Math.min(e,n),i.loaded)}else this.bwEstimator.sampleTTFB(r)}break}}}getTimeToLoadFrag(e,t,i,s){return e+i/t+(s?e+this.lastLevelLoadSec:0)}onLevelLoaded(e,t){const i=this.hls.config,{loading:s}=t.stats,r=s.end-s.first;L(r)&&(this.lastLevelLoadSec=r/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:i}){const s=i?i.stats:t.stats;if(t.type===M&&this.bwEstimator.sampleTTFB(s.loading.first-s.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const e=i?i.duration:t.duration,r=this.hls.levels[t.level],n=(r.loaded?r.loaded.bytes:0)+s.loaded,a=(r.loaded?r.loaded.duration:0)+e;r.loaded={bytes:n,duration:a},r.realBitrate=Math.round(8*n/a)}if(t.bitrateTest){const e={stats:s,frag:t,part:i,id:t.type};this.onFragBuffered(P.FRAG_BUFFERED,e),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:i,part:s}=t,r=null!=s&&s.stats.loaded?s.stats:i.stats;if(r.aborted)return;if(this.ignoreFragment(i))return;const n=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,r.loaded),r.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==M||"initSegment"===e.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,i=this.getBwEstimate(),s=this.hls.config.maxStarvationDelay,r=this.findBestLevel(i,t,e,0,s,1,1);if(r>-1)return r;const n=this.hls.firstLevel,a=Math.min(Math.max(n,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&i&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;const s=t&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){const t=this.hls.levels;if(t.length>Math.max(e,s)&&t[e].loadError<=t[s].loadError)return e}return this._nextAutoLevel=s,this.nextAutoLevelKey=this.getAutoLevelKey(),s}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:i}=this;if(i.levels.length<=1)return i.loadLevel;const{maxAutoLevel:s,config:r,minAutoLevel:n}=i,a=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let d=r.abrBandWidthFactor,c=r.abrBandWidthUpFactor;if(l){const e=this.findBestLevel(o,n,s,l,0,d,c);if(e>=0)return this.rebufferNotice=-1,e}let u=a?Math.min(a,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const e=this.bitrateTestDelay;if(e){u=(a?Math.min(a,r.maxLoadingDelay):r.maxLoadingDelay)-e,this.info(`bitrate test took ${Math.round(1e3*e)}ms, set first fragment max fetchDuration to ${Math.round(1e3*u)} ms`),d=c=1}}const h=this.findBestLevel(o,n,s,l,u,d,c);if(this.rebufferNotice!==h&&(this.rebufferNotice=h,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${h}`)),h>-1)return h;const f=i.levels[n],g=i.loadLevelObj;return g&&(null==f?void 0:f.bitrate)<g.bitrate?n:i.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const i=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,s=e.mainForwardBufferInfo;return(s?s.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,i,s,r,n,a){var o;const l=s+r,d=this.lastLoadedFragLevel,c=-1===d?this.hls.firstLevel:d,{fragCurrent:u,partCurrent:h}=this,{levels:f,allAudioTracks:g,loadLevel:p,config:m}=this.hls;if(1===f.length)return 0;const v=f[c],y=!(null==(o=this.hls.latestLevelDetails)||!o.live),T=-1===p||-1===d;let E,S="SDR",A=(null==v?void 0:v.frameRate)||0;const{audioPreference:b,videoPreference:R}=m,I=this.audioTracksByGroup||(this.audioTracksByGroup=St(g));let k=-1;if(T){if(-1!==this.firstSelection)return this.firstSelection;const s=this.codecTiers||(this.codecTiers=function(e,t,i,s){return e.slice(i,s+1).reduce((e,i,s)=>{if(!i.codecSet)return e;const r=i.audioGroups;let n=e[i.codecSet];n||(e[i.codecSet]=n={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:s,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!r,fragmentError:0}),n.minBitrate=Math.min(n.minBitrate,i.bitrate);const a=Math.min(i.height,i.width);return n.minHeight=Math.min(n.minHeight,a),n.minFramerate=Math.min(n.minFramerate,i.frameRate),n.minIndex=Math.min(n.minIndex,s),n.maxScore=Math.max(n.maxScore,i.score),n.fragmentError+=i.fragmentError,n.videoRanges[i.videoRange]=(n.videoRanges[i.videoRange]||0)+1,r&&r.forEach(e=>{if(!e)return;const i=t.groups[e];i&&(n.hasDefaultAudio=n.hasDefaultAudio||t.hasDefaultAudio?i.hasDefault:i.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(i.channels).forEach(e=>{n.channels[e]=(n.channels[e]||0)+i.channels[e]}))}),e},{})}(f,I,t,i)),r=function(e,t,i,s,r){const n=Object.keys(e),a=null==s?void 0:s.channels,o=null==s?void 0:s.audioCodec,l=null==r?void 0:r.videoCodec,d=a&&2===parseInt(a);let c=!1,u=!1,h=1/0,f=1/0,g=1/0,p=1/0,m=0,v=[];const{preferHDR:y,allowedVideoRanges:T}=yt(t,r);for(let t=n.length;t--;){const i=e[n[t]];c||(c=i.channels[2]>0),h=Math.min(h,i.minHeight),f=Math.min(f,i.minFramerate),g=Math.min(g,i.minBitrate),T.filter(e=>i.videoRanges[e]>0).length>0&&(u=!0)}h=L(h)?h:0,f=L(f)?f:0;const E=Math.max(1080,h),S=Math.max(30,f);g=L(g)?g:i,i=Math.max(g,i),u||(t=void 0);const A=n.length>1;return{codecSet:n.reduce((t,s)=>{const r=e[s];if(s===t)return t;if(v=u?T.filter(e=>r.videoRanges[e]>0):[],A){if(r.minBitrate>i)return Et(s,`min bitrate of ${r.minBitrate} > current estimate of ${i}`),t;if(!r.hasDefaultAudio)return Et(s,"no renditions with default or auto-select sound found"),t;if(o&&s.indexOf(o.substring(0,4))%5!=0)return Et(s,`audio codec preference "${o}" not found`),t;if(a&&!d){if(!r.channels[a])return Et(s,`no renditions with ${a} channel sound found (channels options: ${Object.keys(r.channels)})`),t}else if((!o||d)&&c&&0===r.channels[2])return Et(s,"no renditions with stereo sound found"),t;if(r.minHeight>E)return Et(s,`min resolution of ${r.minHeight} > maximum of ${E}`),t;if(r.minFramerate>S)return Et(s,`min framerate of ${r.minFramerate} > maximum of ${S}`),t;if(!v.some(e=>r.videoRanges[e]>0))return Et(s,`no variants with VIDEO-RANGE of ${Tt(v)} found`),t;if(l&&s.indexOf(l.substring(0,4))%5!=0)return Et(s,`video codec preference "${l}" not found`),t;if(r.maxScore<m)return Et(s,`max score of ${r.maxScore} < selected max of ${m}`),t}return t&&(qe(s)>=qe(t)||r.fragmentError>e[t].fragmentError)?t:(p=r.minIndex,m=r.maxScore,s)},void 0),videoRanges:v,preferHDR:y,minFramerate:f,minBitrate:g,minIndex:p}}(s,S,e,b,R),{codecSet:n,videoRanges:a,minFramerate:o,minBitrate:l,minIndex:d,preferHDR:c}=r;k=d,E=n,S=c?a[a.length-1]:a[0],A=o,e=Math.max(e,l),this.log(`picked start tier ${Tt(r)}`)}else E=null==v?void 0:v.codecSet,S=null==v?void 0:v.videoRange;const w=h?h.duration:u?u.duration:0,P=this.bwEstimator.getEstimateTTFB()/1e3,D=[];for(let o=i;o>=t;o--){var x;const t=f[o],u=o>c;if(!t)continue;if(m.useMediaCapabilities&&!t.supportedResult&&!t.supportedPromise){const i=navigator.mediaCapabilities;"function"==typeof(null==i?void 0:i.decodingInfo)&&nt(t,I,S,A,e,b)?(t.supportedPromise=at(t,I,i,this.supportedCache),t.supportedPromise.then(e=>{if(!this.hls)return;t.supportedResult=e;const i=this.hls.levels,s=i.indexOf(t);e.error?this.warn(`MediaCapabilities decodingInfo error: "${e.error}" for level ${s} ${Tt(e)}`):e.supported?e.decodingInfoResults.some(e=>!1===e.smooth||!1===e.powerEfficient)&&this.log(`MediaCapabilities decodingInfo for level ${s} not smooth or powerEfficient: ${Tt(e)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${s} ${Tt(e)}`),s>-1&&i.length>1&&(this.log(`Removing unsupported level ${s}`),this.hls.removeLevel(s),-1===this.hls.loadLevel&&(this.hls.nextLoadLevel=0)))}).catch(e=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${e}`)})):t.supportedResult=st}if((E&&t.codecSet!==E||S&&t.videoRange!==S||u&&A>t.frameRate||!u&&A>0&&A<t.frameRate||null!=(x=t.supportedResult)&&null!=(x=x.decodingInfoResults)&&x.some(e=>!1===e.smooth))&&(!T||o!==k)){D.push(o);continue}const g=t.details,v=(h?null==g?void 0:g.partTarget:null==g?void 0:g.averagetargetduration)||w;let R;R=u?a*e:n*e;const C=w&&s>=2*w&&0===r?t.averageBitrate:t.maxBitrate,_=this.getTimeToLoadFrag(P,R,C*v,void 0===g);if(R>=C&&(o===d||0===t.loadError&&0===t.fragmentError)&&(_<=P||!L(_)||y&&!this.bitrateTestDelay||_<l)){const e=this.forcedAutoLevel;return o===p||-1!==e&&e===p||(D.length&&this.trace(`Skipped level(s) ${D.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${f[D[0]].codecs}" ${f[D[0]].videoRange}; not compatible with "${E}" ${S}`),this.info(`switch candidate:${c}->${o} adjustedbw(${Math.round(R)})-bitrate=${Math.round(R-C)} ttfb:${P.toFixed(1)} avgDuration:${v.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${_.toFixed(1)} firstSelection:${T} codecSet:${t.codecSet} videoRange:${t.videoRange} hls.loadLevel:${p}`)),T&&(this.firstSelection=o),o}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:i}=this.hls;return Math.min(Math.max(e,i),t)}},bufferController:class extends H{constructor(e,t){var i;super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=e=>{var t;this.hls&&"open"===(null==(t=this.mediaSource)?void 0:t.readyState)&&this.hls.pauseBuffering()},this._onStartStreaming=e=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=e=>{const{media:t,mediaSource:i}=this;e&&this.log("Media source opened"),t&&i&&(i.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(P.MEDIA_ATTACHED,{media:t,mediaSource:i}),null!==this.mediaSource&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:e,_objectUrl:t}=this;e!==t&&this.error(`Media element src was set while attaching MediaSource (${t} > ${e})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=(i=X(e.config.preferManagedMediaSource),"undefined"!=typeof self&&i===self.ManagedMediaSource),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:e}=this;e.on(P.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(P.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(P.MANIFEST_LOADING,this.onManifestLoading,this),e.on(P.MANIFEST_PARSED,this.onManifestParsed,this),e.on(P.BUFFER_RESET,this.onBufferReset,this),e.on(P.BUFFER_APPENDING,this.onBufferAppending,this),e.on(P.BUFFER_CODECS,this.onBufferCodecs,this),e.on(P.BUFFER_EOS,this.onBufferEos,this),e.on(P.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(P.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(P.FRAG_PARSED,this.onFragParsed,this),e.on(P.FRAG_CHANGED,this.onFragChanged,this),e.on(P.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(P.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(P.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(P.MANIFEST_LOADING,this.onManifestLoading,this),e.off(P.MANIFEST_PARSED,this.onManifestParsed,this),e.off(P.BUFFER_RESET,this.onBufferReset,this),e.off(P.BUFFER_APPENDING,this.onBufferAppending,this),e.off(P.BUFFER_CODECS,this.onBufferCodecs,this),e.off(P.BUFFER_EOS,this.onBufferEos,this),e.off(P.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(P.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(P.FRAG_PARSED,this.onFragParsed,this),e.off(P.FRAG_CHANGED,this.onFragChanged,this),e.off(P.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const i={};if(this.operationQueue){const e=this.isUpdating();e||this.operationQueue.removeBlockers();const t=this.isQueued();(e||t)&&this.warn(`Transfering MediaSource with${t?" operations in queue":""}${e?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const s=this.transferData;return!this.sourceBufferCount&&s&&s.mediaSource===t?$(i,s.tracks):this.sourceBuffers.forEach(e=>{const[t]=e;t&&(i[t]=$({},this.tracks[t]),this.removeBuffer(t)),e[0]=e[1]=null}),{media:e,mediaSource:t,tracks:i}}initTracks(){this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var i;let s=2;(t.audio&&!t.video||!t.altAudio)&&(s=1),this.bufferCodecEventsTotal=s,this.log(`${s} bufferCodec event(s) expected.`),null!=(i=this.transferData)&&i.mediaSource&&this.sourceBufferCount&&s&&this.bufferCreated()}onMediaAttaching(e,t){const i=this.media=t.media;this.transferData=this.overrides=void 0;const s=X(this.appendSource);if(s){const e=!!t.mediaSource;(e||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const r=this.mediaSource=t.mediaSource||new s;if(this.assignMediaSource(r),e)this._objectUrl=i.src,this.attachTransferred();else{const e=this._objectUrl=self.URL.createObjectURL(r);if(this.appendSource)try{i.removeAttribute("src");const t=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||t&&r instanceof t,Un(i),function(e,t){const i=self.document.createElement("source");i.type="video/mp4",i.src=t,e.appendChild(i)}(i,e),i.load()}catch(t){i.src=e}else i.src=e}i.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,i;this.log(`${(null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${null==(i=e.constructor)?void 0:i.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const i=this.tracks,s=t.tracks,r=s?Object.keys(s):null,n=r?r.length:0,a=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(s&&r&&n){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})\nrequired tracks: ${Tt(i,(e,t)=>"initSegment"===e?void 0:t)};\ntransfer tracks: ${Tt(s,(e,t)=>"initSegment"===e?void 0:t)}}`),!Q(s,i)){t.mediaSource=null,t.tracks=void 0;const r=e.currentTime,n=this.details,a=Math.max(r,(null==n?void 0:n.fragments[0].start)||0);return a-r>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${r} -> ${a}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(s)}"->"${Object.keys(i)}") start time: ${a} currentTime: ${r}`),this.onMediaDetaching(P.MEDIA_DETACHING,{}),this.onMediaAttaching(P.MEDIA_ATTACHING,t),void(e.currentTime=a))}this.transferData=void 0,r.forEach(e=>{const t=e,i=s[t];if(i){const e=i.buffer;if(e){const s=this.fragmentTracker,r=i.id;if(s.hasFragments(r)||s.hasParts(r)){const i=yi.getBuffered(e);s.detectEvictedFragments(t,i,r,null,!0)}const n=Nn(t),a=[t,e];this.sourceBuffers[n]=a,e.updating&&this.operationQueue&&this.operationQueue.prependBlocker(t),this.trackSourceBuffer(t,i)}}}),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var e;const t=null==(e=this.mediaSource)?void 0:e.readyState;return"open"===t||"ended"===t}onMediaDetaching(e,t){const i=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:s,mediaSource:r,_objectUrl:n}=this;if(r){if(this.log("media source "+(i?"transferring":"detaching")),i)this.sourceBuffers.forEach(([e])=>{e&&this.removeBuffer(e)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const e="open"===r.readyState;try{const t=r.sourceBuffers;for(let i=t.length;i--;)e&&t[i].abort(),r.removeSourceBuffer(t[i]);e&&r.endOfStream()}catch(e){this.warn(`onMediaDetaching: ${e.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}r.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("sourceended",this._onMediaSourceEnded),r.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(r.removeEventListener("startstreaming",this._onStartStreaming),r.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}s&&(s.removeEventListener("emptied",this._onMediaEmptied),i||(n&&self.URL.revokeObjectURL(n),this.mediaSrc===n?(s.removeAttribute("src"),this.appendSource&&Un(s),s.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(P.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const i=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),i)try{var s;null!=(s=this.mediaSource)&&s.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(t){this.warn(`onBufferReset ${e}`,t)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[Nn(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new _n(this.tracks)}onBufferCodecs(e,t){var i;const s=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in t&&(s.audio||s.video)||s.audiovideo&&("audio"in t||"video"in t),a=!n&&this.sourceBufferCount&&this.media&&r.some(e=>!s[e]);n||a?this.warn(`Unsupported transition between "${Object.keys(s)}" and "${r}" SourceBuffers`):(r.forEach(e=>{var i,r;const n=t[e],{id:a,codec:o,levelCodec:l,container:d,metadata:c,supplemental:u}=n;let h=s[e];const f=null==(i=this.transferData)||null==(i=i.tracks)?void 0:i[e],g=null!=f&&f.buffer?f:h,p=(null==g?void 0:g.pendingCodec)||(null==g?void 0:g.codec),m=null==g?void 0:g.levelCodec;h||(h=s[e]={buffer:void 0,listeners:[],codec:o,supplemental:u,container:d,levelCodec:l,metadata:c,id:a});const v=Qe(p,m),y=null==v?void 0:v.replace(Mn,"$1");let T=Qe(o,l);const E=null==(r=T)?void 0:r.replace(Mn,"$1");T&&v&&y!==E&&("audio"===e.slice(0,5)&&(T=Xe(T,this.appendSource)),this.log(`switching codec ${p} to ${T}`),T!==(h.pendingCodec||h.codec)&&(h.pendingCodec=T),h.container=d,this.appendChangeType(e,d,T))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&"main"===(null==(i=t.audio)?void 0:i.id)&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks()))}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const i=this.tracks[t];return e[t]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},e},{})}appendChangeType(e,t,i){const s=`${t};codecs=${i}`,r={label:`change-type=${s}`,execute:()=>{const r=this.tracks[e];if(r){const n=r.buffer;null!=n&&n.changeType&&(this.log(`changing ${e} sourceBuffer type to ${s}`),n.changeType(s),r.codec=i,r.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn(`Failed to change ${e} SourceBuffer type`,t)}};this.append(r,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const i=e.start,s=i+.05*e.duration;if(!0===(null==(t=this.fragmentTracker.getAppendedFrag(i,M))?void 0:t.gap))return;const r={label:"block-audio",execute:()=>{var e;const t=this.tracks.video;(this.lastVideoAppendEnd>s||null!=t&&t.buffer&&yi.isBuffered(t.buffer,s)||!0===(null==(e=this.fragmentTracker.getAppendedFrag(s,M))?void 0:e.gap))&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn("Error executing block-audio operation",e)}};this.blockedAudioAppend={op:r,frag:e},this.append(r,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:i}=this,{data:s,type:r,parent:n,frag:a,part:o,chunkMeta:l,offset:d}=t,c=l.buffering[r],{sn:u,cc:h}=a,f=self.performance.now();c.start=f;const g=a.stats.buffering,p=o?o.stats.buffering:null;0===g.start&&(g.start=f),p&&0===p.start&&(p.start=f);const m=i.audio;let v=!1;"audio"===r&&"audio/mpeg"===(null==m?void 0:m.container)&&(v=!this.lastMpegAudioChunk||1===l.id||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const y=i.video,T=null==y?void 0:y.buffer;if(T&&"initSegment"!==u){const e=o||a,t=this.blockedAudioAppend;if("audio"!==r||"main"===n||this.blockedAudioAppend||y.ending||y.ended){if("video"===r){const i=e.end;if(t){const e=t.frag.start;(i>e||i<this.lastVideoAppendEnd||yi.isBuffered(T,e))&&this.unblockAudio()}this.lastVideoAppendEnd=i}}else{const t=e.start+.05*e.duration,i=T.buffered,s=this.currentOp("video");i.length||s?!s&&!yi.isBuffered(T,t)&&this.lastVideoAppendEnd<t&&this.blockAudio(e):this.blockAudio(e)}}const E=(o||a).start,S={label:`append-${r}`,execute:()=>{var e;c.executeStart=self.performance.now();const t=null==(e=this.tracks[r])?void 0:e.buffer;t&&(v?this.updateTimestampOffset(t,E,.1,r,u,h):void 0!==d&&L(d)&&this.updateTimestampOffset(t,d,1e-6,r,u,h)),this.appendExecutor(s,r)},onStart:()=>{},onComplete:()=>{const e=self.performance.now();c.executeEnd=c.end=e,0===g.first&&(g.first=e),p&&0===p.first&&(p.first=e);const t={};this.sourceBuffers.forEach(([e,i])=>{e&&(t[e]=yi.getBuffered(i))}),this.appendErrors[r]=0,"audio"===r||"video"===r?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(P.BUFFER_APPENDED,{type:r,frag:a,part:o,chunkMeta:l,parent:a.type,timeRanges:t})},onError:e=>{var t;const i={type:k.MEDIA_ERROR,parent:a.type,details:w.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:a,part:o,chunkMeta:l,error:e,err:e,fatal:!1},s=null==(t=this.media)?void 0:t.error;if(e.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==e.name||"quota"in e)i.details=w.BUFFER_FULL_ERROR;else if(e.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!s)i.errorAction=zt(!0);else if(e.name===On&&0===this.sourceBufferCount)i.errorAction=zt(!0);else{const e=++this.appendErrors[r];this.warn(`Failed ${e}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${s||"no media error"})`),(e>=this.hls.config.appendErrorMaxRetry||s)&&(i.fatal=!0)}this.hls.trigger(P.ERROR,i)}};this.log(`queuing "${r}" append sn: ${u}${o?" p: "+o.index:""} of ${a.type===M?"level":"track"} ${a.level} cc: ${h}`),this.append(S,r,this.isPending(this.tracks[r]))}getFlushOp(e,t,i){return this.log(`queuing "${e}" remove ${t}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,i)},onStart:()=>{},onComplete:()=>{this.hls.trigger(P.BUFFER_FLUSHED,{type:e})},onError:s=>{this.warn(`Failed to remove ${t}-${i} from "${e}" SourceBuffer`,s)}}}onBufferFlushing(e,t){const{type:i,startOffset:s,endOffset:r}=t;i?this.append(this.getFlushOp(i,s,r),i):this.sourceBuffers.forEach(([e])=>{e&&this.append(this.getFlushOp(e,s,r),e)})}onFragParsed(e,t){const{frag:i,part:s}=t,r=[],n=s?s.elementaryStreams:i.elementaryStreams;n[le]?r.push("audiovideo"):(n[ae]&&r.push("audio"),n[oe]&&r.push("video"));0===r.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(()=>{const e=self.performance.now();i.stats.buffering.end=e,s&&(s.stats.buffering.end=e);const t=s?s.stats:i.stats;this.hls.trigger(P.FRAG_BUFFERED,{frag:i,part:s,stats:t,id:i.type})},r).catch(e=>{this.warn(`Fragment buffered callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){const t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var i;this.sourceBuffers.forEach(([e])=>{if(e){const i=this.tracks[e];t.type&&t.type!==e||(i.ending=!0,i.ended||(i.ended=!0,this.log(`${e} buffer reached EOS`)))}});const s=!1!==(null==(i=this.overrides)?void 0:i.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{var t;return e&&!(null!=(t=this.tracks[e])&&t.ended)})?s?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:e}=this;e&&"open"===e.readyState?(this.log("Calling mediaSource.endOfStream()"),e.endOfStream(),this.hls.trigger(P.BUFFERED_TO_END,void 0)):e&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${e.readyState}`)})):(this.tracksEnded(),this.hls.trigger(P.BUFFERED_TO_END,void 0)):"video"===t.type&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(null!==e){const t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===w.BUFFER_APPEND_ERROR&&t.frag){var i;const e=null==(i=t.errorAction)?void 0:i.nextAutoLevel;L(e)&&e!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:i}=this;if(!i||null===t)return;if(!this.sourceBufferCount)return;const s=e.config,r=i.currentTime,n=t.levelTargetDuration,a=t.live&&null!==s.liveBackBufferLength?s.liveBackBufferLength:s.backBufferLength;if(L(a)&&a>=0){const e=Math.max(a,n),t=Math.floor(r/n)*n-e;this.flushBackBuffer(r,n,t)}const o=s.frontBufferFlushThreshold;if(L(o)&&o>0){const e=Math.max(s.maxBufferLength,o),t=Math.max(e,n),i=Math.floor(r/n)*n+t;this.flushFrontBuffer(r,n,i)}}flushBackBuffer(e,t,i){this.sourceBuffers.forEach(([e,t])=>{if(t){const r=yi.getBuffered(t);if(r.length>0&&i>r.start(0)){var s;this.hls.trigger(P.BACK_BUFFER_REACHED,{bufferEnd:i});const t=this.tracks[e];if(null!=(s=this.details)&&s.live)this.hls.trigger(P.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(null!=t&&t.ended)return void this.log(`Cannot flush ${e} back buffer while SourceBuffer is in ended state`);this.hls.trigger(P.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:e})}}})}flushFrontBuffer(e,t,i){this.sourceBuffers.forEach(([t,s])=>{if(s){const r=yi.getBuffered(s),n=r.length;if(n<2)return;const a=r.start(n-1),o=r.end(n-1);if(i>a||e>=a&&e<=o)return;this.hls.trigger(P.BUFFER_FLUSHING,{startOffset:a,endOffset:1/0,type:t})}})}getDurationAndRange(){var e;const{details:t,mediaSource:i}=this;if(!t||!this.media||"open"!==(null==i?void 0:i.readyState))return null;const s=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&i.setLiveSeekableRange){const e=Math.max(0,t.fragmentStart);return{duration:1/0,start:e,end:Math.max(e,s)}}return{duration:1/0}}const r=null==(e=this.overrides)?void 0:e.duration;if(r)return L(r)?{duration:r}:null;const n=this.media.duration;return s>(L(i.duration)?i.duration:0)&&s>n||!L(n)?{duration:s}:null}updateMediaSource({duration:e,start:t,end:i}){const s=this.mediaSource;this.media&&s&&"open"===s.readyState&&(s.duration!==e&&(L(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),s.duration=e),void 0!==t&&void 0!==i&&(this.log(`MediaSource duration is set to ${s.duration}. Setting seekable range to ${t}-${i}.`),s.setLiveSeekableRange(t,i)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${Tt(i)}`),this.tracksReady){var s;const e=null==(s=this.transferData)?void 0:s.tracks;e&&Object.keys(e).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,i])=>{if(t){const s=this.tracks[t];e[t]={buffer:i,container:s.container,codec:s.codec,supplemental:s.supplemental,levelCodec:s.levelCodec,id:s.id,metadata:s.metadata}}}),this.hls.trigger(P.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([e])=>{this.executeNext(e)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(P.ERROR,{type:k.MEDIA_ERROR,details:w.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:i}=this;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(const r in e){const n=r,a=e[n];if(this.isPending(a)){const e=this.getTrackCodec(a,n),r=`${a.container};codecs=${e}`;a.codec=e,this.log(`creating sourceBuffer(${r})${this.currentOp(n)?" Queued":""} ${Tt(a)}`);try{const e=i.addSourceBuffer(r),s=Nn(n),o=[n,e];t[s]=o,a.buffer=e}catch(e){var s;return this.error(`error while trying to add sourceBuffer: ${e.message}`),this.shiftAndExecuteNext(n),null==(s=this.operationQueue)||s.removeBlockers(),delete this.tracks[n],void this.hls.trigger(P.ERROR,{type:k.MEDIA_ERROR,details:w.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:n,mimeType:r,parent:a.id})}this.trackSourceBuffer(n,a)}}this.bufferCreated()}getTrackCodec(e,t){const i=e.supplemental;let s=e.codec;i&&("video"===t||"audiovideo"===t)&&He(i,"video")&&(s=function(e,t){const i=[];if(e){const t=e.split(",");for(let e=0;e<t.length;e++)Ge(t[e],"video")||i.push(t[e])}return t&&i.push(t),i.join(",")}(s,i));const r=Qe(s,e.levelCodec);return r?"audio"===t.slice(0,5)?Xe(r,this.appendSource):r:""}trackSourceBuffer(e,t){const i=t.buffer;if(!i)return;const s=this.getTrackCodec(t,e);this.tracks[e]={buffer:i,codec:s,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(e,t)=>{const i=t.removedRanges;null!=i&&i.length&&this.hls.trigger(P.BUFFER_FLUSHED,{type:e})})}get mediaSrc(){var e,t;const i=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==i?void 0:i.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if("closed"===(null==(t=this.mediaSource)?void 0:t.readyState))return void this.resetBuffer(e);const i=this.currentOp(e);i&&(i.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var i;const s=new Error(`${e} SourceBuffer error. MediaSource readyState: ${null==(i=this.mediaSource)?void 0:i.readyState}`);this.error(`${s}`,t),this.hls.trigger(P.ERROR,{type:k.MEDIA_ERROR,details:w.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:s,fatal:!1});const r=this.currentOp(e);r&&r.onError(s)}updateTimestampOffset(e,t,i,s,r,n){const a=t-e.timestampOffset;Math.abs(a)>=i&&(this.log(`Updating ${s} SourceBuffer timestampOffset to ${t} (sn: ${r} cc: ${n})`),e.timestampOffset=t)}removeExecutor(e,t,i){const{media:s,mediaSource:r}=this,n=this.tracks[e],a=null==n?void 0:n.buffer;if(!s||!r||!a)return this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),void this.shiftAndExecuteNext(e);const o=L(s.duration)?s.duration:1/0,l=L(r.duration)?r.duration:1/0,d=Math.max(0,t),c=Math.min(i,o,l);c>d&&(!n.ending||n.ended)?(n.ended=!1,this.log(`Removing [${d},${c}] from the ${e} SourceBuffer`),a.remove(d,c)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const i=this.tracks[t],s=null==i?void 0:i.buffer;if(!s)throw new Fn(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);i.ending=!1,i.ended=!1,s.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(e=>{this.warn(`SourceBuffer blocked callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(e){this.warn(`Callback run without blocking ${this.operationQueue} ${e}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:i}=this,s=t.map(e=>this.appendBlocker(e));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(s).then(t=>{i===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(e=>{var t;const i=null==(t=this.tracks[e])?void 0:t.buffer;i&&!i.updating&&this.shiftAndExecuteNext(e)})}append(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,i){const s=this.tracks[e];if(!s)return;const r=s.buffer;if(!r)return;const n=i.bind(this,e);s.listeners.push({event:t,listener:n}),r.addEventListener(t,n)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const i=t.buffer;i&&(t.listeners.forEach(e=>{i.removeEventListener(e.event,e.listener)}),t.listeners.length=0)}},capLevelController:Bn,errorController:class extends H{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(P.ERROR,this.onError,this),e.on(P.MANIFEST_LOADING,this.onManifestLoading,this),e.on(P.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(P.ERROR,this.onError,this),e.off(P.ERROR,this.onErrorOut,this),e.off(P.MANIFEST_LOADING,this.onManifestLoading,this),e.off(P.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(null==e?void 0:e.type)===M?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,i=t.currentLevel;return null!=(e=t.loadLevelObj)&&e.details||-1===i?t.loadLevel:i}variantHasKey(e,t){if(e){var i;if(null!=(i=e.details)&&i.hasKey(t))return!0;const s=e.audioGroups;if(s){return this.hls.allAudioTracks.filter(e=>s.indexOf(e.groupId)>=0).some(e=>{var i;return null==(i=e.details)?void 0:i.hasKey(t)})}}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var i;if(t.fatal)return;const s=this.hls,r=t.context;switch(t.details){case w.FRAG_LOAD_ERROR:case w.FRAG_LOAD_TIMEOUT:case w.KEY_LOAD_ERROR:case w.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case w.FRAG_PARSING_ERROR:if(null!=(i=t.frag)&&i.gap)return void(t.errorAction=zt());case w.FRAG_GAP:case w.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=Gt);case w.LEVEL_EMPTY_ERROR:case w.LEVEL_PARSING_ERROR:{var n;const e=t.parent===M?t.level:s.loadLevel;t.details===w.LEVEL_EMPTY_ERROR&&null!=(n=t.context)&&null!=(n=n.levelDetails)&&n.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case w.LEVEL_LOAD_ERROR:case w.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==r?void 0:r.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.level)));case w.AUDIO_TRACK_LOAD_ERROR:case w.AUDIO_TRACK_LOAD_TIMEOUT:case w.SUBTITLE_LOAD_ERROR:case w.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const e=s.loadLevelObj;if(e&&(r.type===C&&e.hasAudioGroup(r.groupId)||r.type===_&&e.hasSubtitleGroup(r.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.loadLevel),t.errorAction.action=Gt,void(t.errorAction.flags=Wt)}return;case w.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(t.errorAction={action:Gt,flags:qt});case w.KEY_SYSTEM_SESSION_UPDATE_FAILED:case w.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case w.KEY_SYSTEM_NO_SESSION:return void(t.errorAction={action:Gt,flags:Yt});case w.BUFFER_ADD_CODEC_ERROR:case w.REMUX_ALLOC_ERROR:case w.BUFFER_APPEND_ERROR:var a;if(!t.errorAction)t.errorAction=this.getLevelSwitchAction(t,null!=(a=t.level)?a:s.loadLevel);return;case w.INTERNAL_EXCEPTION:case w.BUFFER_APPENDING_ERROR:case w.BUFFER_FULL_ERROR:case w.LEVEL_SWITCH_ERROR:case w.BUFFER_STALLED_ERROR:case w.BUFFER_SEEK_OVER_HOLE:case w.BUFFER_NUDGE_ON_STALL:return void(t.errorAction=zt())}t.type===k.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=zt())}getPlaylistRetryOrSwitchAction(e,t){const i=Ft(this.hls.config.playlistLoadPolicy,e),s=this.playlistError++;if(Bt(i,s,_t(e),e.response))return{action:Kt,flags:jt,retryConfig:i,retryCount:s};const r=this.getLevelSwitchAction(e,t);return i&&(r.retryConfig=i,r.retryCount=s),r}getFragRetryOrSwitchAction(e){const t=this.hls,i=this.getVariantLevelIndex(e.frag),s=t.levels[i],{fragLoadPolicy:r,keyLoadPolicy:n}=t.config,a=Ft(Mt(e)?n:r,e),o=t.levels.reduce((e,t)=>e+t.fragmentError,0);if(s&&(e.details!==w.FRAG_GAP&&s.fragmentError++,!Ot(e))){if(Bt(a,o,_t(e),e.response))return{action:Kt,flags:jt,retryConfig:a,retryCount:o}}const l=this.getLevelSwitchAction(e,i);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(e,t){const i=this.hls;null==t&&(t=i.loadLevel);const s=this.hls.levels[t];if(s){var r,n;const t=e.details;s.loadError++,t===w.BUFFER_APPEND_ERROR&&s.fragmentError++;let l=-1;const{levels:d,loadLevel:c,minAutoLevel:u,maxAutoLevel:h}=i;i.autoLevelEnabled||i.config.preserveManualLevelOnError||(i.loadLevel=-1);const f=null==(r=e.frag)?void 0:r.type,g=(f===O&&t===w.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&(t===w.BUFFER_ADD_CODEC_ERROR||t===w.BUFFER_APPEND_ERROR))&&d.some(({audioCodec:e})=>s.audioCodec!==e),p="video"===e.sourceBufferName&&(t===w.BUFFER_ADD_CODEC_ERROR||t===w.BUFFER_APPEND_ERROR)&&d.some(({codecSet:e,audioCodec:t})=>s.codecSet!==e&&s.audioCodec===t),{type:m,groupId:v}=null!=(n=e.context)?n:{};for(let i=d.length;i--;){const r=(i+c)%d.length;if(r!==c&&r>=u&&r<=h&&0===d[r].loadError){var a,o;const i=d[r];if(t===w.FRAG_GAP&&f===M&&e.frag){const t=d[r].details;if(t){const i=Pt(e.frag,t.fragments,e.frag.start);if(null!=i&&i.gap)continue}}else{if(m===C&&i.hasAudioGroup(v)||m===_&&i.hasSubtitleGroup(v))continue;if(f===O&&null!=(a=s.audioGroups)&&a.some(e=>i.hasAudioGroup(e))||f===F&&null!=(o=s.subtitleGroups)&&o.some(e=>i.hasSubtitleGroup(e))||g&&s.audioCodec===i.audioCodec||p&&s.codecSet===i.codecSet||!g&&s.codecSet!==i.codecSet)continue}l=r;break}}if(l>-1&&i.loadLevel!==l)return e.levelRetry=!0,this.playlistError=0,{action:Gt,flags:jt,nextAutoLevel:l}}return{action:Gt,flags:Wt}}onErrorOut(e,t){var i;switch(null==(i=t.errorAction)?void 0:i.action){case Vt:break;case Gt:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===w.FRAG_GAP?/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):t.fatal=!0}t.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(e){const t=this.hls,i=e.errorAction;if(!i)return;const{flags:s}=i,r=i.nextAutoLevel;switch(s){case jt:this.switchLevel(e,r);break;case qt:{const s=this.getVariantLevelIndex(e.frag),r=t.levels[s],n=null==r?void 0:r.attrs["HDCP-LEVEL"];if(i.hdcpLevel=n,"NONE"===n)this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(n){t.maxHdcpLevel=dt[dt.indexOf(n)-1],i.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case Yt:{const t=e.decryptdata;if(t){const s=this.hls.levels,r=s.length;for(let i=r;i--;){var n,a;if(this.variantHasKey(s[i],t))this.log(`Banned key found in level ${i} (${s[i].bitrate}bps) or audio group "${null==(n=s[i].audioGroups)?void 0:n.join(",")}" (${null==(a=e.frag)?void 0:a.type} fragment) ${Z(t.keyId||[])}`),s[i].fragmentError++,s[i].loadError++,this.log(`Removing level ${i} with key error (${e.error})`),this.hls.removeLevel(i)}const o=e.frag;if(this.hls.levels.length<r)i.resolved=!0;else if(o&&o.type!==M){const e=o.decryptdata;e&&!t.matches(e)&&(i.resolved=!0)}}break}}i.resolved||this.switchLevel(e,r)}switchLevel(e,t){if(void 0!==t&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===w.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&"audiovideo"!==e.sourceBufferName)){const t=tt(e.mimeType),i=this.hls.levels;for(let s=i.length;s--;)i[s][`${e.sourceBufferName}Codec`]===t&&(this.log(`Removing level ${s} for ${e.details} ("${t}" not supported)`),this.hls.removeLevel(s))}}},fpsController:class{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(P.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(P.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(P.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(P.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const i=this.hls.config;if(i.capLevelOnFPSDrop){const e=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=e,e&&"function"==typeof e.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,i){const s=performance.now();if(t){if(this.lastTime){const e=s-this.lastTime,r=i-this.lastDroppedFrames,n=t-this.lastDecodedFrames,a=1e3*r/e,o=this.hls;if(o.trigger(P.FPS_DROP,{currentDropped:r,currentDecoded:n,totalDroppedFrames:i}),a>0&&r>o.config.fpsDroppedMonitoringThreshold*n){let e=o.currentLevel;o.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+e),e>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=e)&&(e-=1,o.trigger(P.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:o.currentLevel}),o.autoLevelCapping=e,this.streamController.nextLevelSwitch())}}this.lastTime=s,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}},stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:Yi,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},{cueHandler:sl,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:class extends Xs{constructor(e,t,i){super(e,t,i,"subtitle-stream-controller",F),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(P.LEVEL_LOADED,this.onLevelLoaded,this),e.on(P.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(P.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(P.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(P.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(P.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(P.LEVEL_LOADED,this.onLevelLoaded,this),e.off(P.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(P.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(P.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(P.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(P.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=Bs,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:i,success:s}=t;if(this.fragContextChanged(i)||(ce(i)&&(this.fragPrevious=i),this.state=Bs),!s)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let n;const a=i.start;for(let e=0;e<r.length;e++)if(a>=r[e].start&&a<=r[e].end){n=r[e];break}const o=i.start+i.duration;n?n.end=o:(n={start:a,end:o},r.push(n)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:i,endOffset:s}=t;if(0===i&&s!==Number.POSITIVE_INFINITY){const e=s-1;if(e<=0)return;t.endOffsetSubtitles=Math.max(0,e),this.tracksBuffered.forEach(t=>{for(let i=0;i<t.length;)if(t[i].end<=e)t.shift();else{if(!(t[i].start<e))break;t[i].start=e,i++}}),this.fragmentTracker.removeFragmentsInRange(i,e,F)}}onError(e,t){const i=t.frag;(null==i?void 0:i.type)===F&&(t.details===w.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==Ns&&(this.state=Bs))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){this.levels&&Dn(this.levels,t)?this.levels=t.map(e=>new mt(e)):(this.tracksBuffered=[],this.levels=t.map(e=>{const t=new mt(e);return this.tracksBuffered[t.id]=[],t}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,F),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,null==(i=this.levels)||!i.length||-1===this.currentTrackId)return void this.clearInterval();const s=this.levels[this.currentTrackId];null!=s&&s.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,s&&this.state!==Ns&&this.setInterval(500)}onSubtitleTrackLoaded(e,t){var i;const{currentTrackId:s,levels:r}=this,{details:n,id:a}=t;if(!r)return void this.warn(`Subtitle tracks were reset while loading level ${a}`);const o=r[a];if(a>=r.length||!o)return;this.log(`Subtitle track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(n.live||null!=(i=o.details)&&i.live){if(n.deltaUpdateFailed)return;const e=this.mainDetails;if(!e)return void(this.startFragRequested=!1);const t=e.fragments[0];var d;if(o.details)l=this.alignPlaylists(n,o.details,null==(d=this.levelLastLoaded)?void 0:d.details),0===l&&t&&(l=t.start,As(n,l));else n.hasProgramDateTime&&e.hasProgramDateTime?(Ms(n,e),l=n.fragmentStart):t&&(l=t.start,As(n,l));e&&!this.startFragRequested&&this.setStartPosition(e,l)}if(o.details=n,this.levelLastLoaded=o,a===s&&(this.hls.trigger(P.SUBTITLE_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===Bs)){Pt(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)}}_handleFragmentLoadComplete(e){const{frag:t,payload:i}=e,s=t.decryptdata,r=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>0&&null!=s&&s.key&&s.iv&&_i(s.method)){const e=performance.now();this.decrypter.decrypt(new Uint8Array(i),s.key.buffer,s.iv.buffer,Mi(s.method)).catch(e=>{throw r.trigger(P.ERROR,{type:k.MEDIA_ERROR,details:w.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e}).then(i=>{const s=performance.now();r.trigger(P.FRAG_DECRYPTED,{frag:t,payload:i,stats:{tstart:e,tdecrypt:s}})}).catch(e=>{this.warn(`${e.name}: ${e.message}`),this.state=Bs})}}doTick(){if(this.media){if(this.state===Bs){const{currentTrackId:e,levels:t}=this,i=null==t?void 0:t[e];if(!i||!t.length||!i.details)return;if(this.waitForLive(i))return;const{config:s}=this,r=this.getLoadPosition(),n=yi.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,s.maxBufferHole),{end:a,len:o}=n,l=i.details;if(o>this.hls.maxBufferLength+l.levelTargetDuration)return;const d=l.fragments,c=d.length,u=l.edge;let h=null;const f=this.fragPrevious;if(a<u){const e=s.maxFragLookUpTolerance,t=a>u-e?0:e;h=Pt(f,d,Math.max(d[0].start,a),t),!h&&f&&f.start<d[0].start&&(h=d[0])}else h=d[c-1];if(h=this.filterReplacedPrimary(h,i.details),!h)return;const g=d[h.sn-l.startSN-1];if(g&&g.cc===h.cc&&this.fragmentTracker.getState(g)===Xt&&(h=g),this.fragmentTracker.getState(h)===Xt){const e=this.mapToInitFragWhenRequired(h);e&&this.loadFragment(e,i,a)}}}else this.state=Bs}loadFragment(e,t,i){ce(e)?super.loadFragment(e,t,i):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new ao(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class extends Pn{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=null;const t=Ka(this.media.textTracks);for(let i=0;i<t.length;i++)if("hidden"===t[i].mode)e=t[i];else if("showing"===t[i].mode){e=t[i];break}const i=this.findTrackForTextTrack(e);this.subtitleTrack!==i&&this.setSubtitleTrack(i)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(P.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(P.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(P.MANIFEST_LOADING,this.onManifestLoading,this),e.on(P.MANIFEST_PARSED,this.onManifestParsed,this),e.on(P.LEVEL_LOADING,this.onLevelLoading,this),e.on(P.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(P.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(P.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(P.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(P.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(P.MANIFEST_LOADING,this.onManifestLoading,this),e.off(P.MANIFEST_PARSED,this.onManifestParsed,this),e.off(P.LEVEL_LOADING,this.onLevelLoading,this),e.off(P.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(P.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(P.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const i=this.media;if(!i)return;const s=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,s)return;Ka(i.textTracks).forEach(e=>{Ga(e)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:i,groupId:s,details:r}=t,n=this.tracksInGroup[i];if(!n||n.groupId!==s)return void this.warn(`Subtitle track with id:${i} and group:${s} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=t.details,this.log(`Subtitle track ${i} "${n.name}" lang:${n.lang} group:${s} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.subtitleGroups||null,s=this.groupIds;let r=this.currentTrack;if(!i||(null==s?void 0:s.length)!==(null==i?void 0:i.length)||null!=i&&i.some(e=>-1===(null==s?void 0:s.indexOf(e)))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const e=this.tracks.filter(e=>!i||-1!==i.indexOf(e.groupId));if(e.length)this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),e.forEach((e,t)=>{e.id=t});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=e;const t=this.hls.config.subtitlePreference;if(!r&&t){this.selectDefaultTrack=!1;const i=bt(t,e);if(i>-1)r=e[i];else{const e=bt(t,this.tracks);r=this.tracks[e]}}let s=this.findTrackId(r);-1===s&&r&&(s=this.findTrackId(null));const n={subtitleTracks:e};this.log(`Updating subtitle tracks, ${e.length} track(s) found in "${null==i?void 0:i.join(",")}" group-id`),this.hls.trigger(P.SUBTITLE_TRACKS_UPDATED,n),-1!==s&&-1===this.trackId&&this.setSubtitleTrack(s)}}findTrackId(e){const t=this.tracksInGroup,i=this.selectDefaultTrack;for(let s=0;s<t.length;s++){const r=t[s];if((!i||r.default)&&(i||e)&&(!e||Lt(r,e)))return s}if(e){for(let i=0;i<t.length;i++){const s=t[i];if(xn(e.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){const s=t[i];if(xn(e.attrs,s.attrs,["LANGUAGE"]))return i}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){if(Cn(t[i],e))return i}}return-1}onError(e,t){!t.fatal&&t.context&&(t.context.type!==_||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(-1===e.id)return this.setSubtitleTrack(-1),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const i=this.currentTrack;if(i&&Lt(e,i))return i;const s=bt(e,this.tracksInGroup);if(s>-1){const e=this.tracksInGroup[s];return this.setSubtitleTrack(s),e}if(i)return null;{const i=bt(e,t);if(i>-1)return t[i]}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=e.id,s=e.groupId,r=this.getUrlWithDirectives(e.url,t),n=e.details,a=null==n?void 0:n.age;this.log(`Loading subtitle ${i} "${e.name}" lang:${e.lang} group:${s}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(P.SUBTITLE_TRACK_LOADING,{url:r,id:i,groupId:s,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=Ka(e.textTracks),i=this.currentTrack;let s;if(i&&(s=t.filter(e=>Cn(i,e))[0],s||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(t).forEach(e=>{"disabled"!==e.mode&&e!==s&&(e.mode="disabled")}),s){const e=this.subtitleDisplay?"showing":"hidden";s.mode!==e&&(s.mode=e)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=e);if(e<-1||e>=t.length||!L(e))return void this.warn(`Invalid subtitle track id: ${e}`);this.selectDefaultTrack=!1;const i=this.currentTrack,s=t[e]||null;if(this.trackId=e,this.currentTrack=s,this.toggleTrackModes(),!s)return void this.hls.trigger(P.SUBTITLE_TRACK_SWITCH,{id:e});const r=!!s.details&&!s.details.live;if(e===this.trackId&&s===i&&r)return;this.log(`Switching to subtitle-track ${e}`+(s?` "${s.name}" lang:${s.lang} group:${s.groupId}`:""));const{id:n,groupId:a="",name:o,type:l,url:d}=s;this.hls.trigger(P.SUBTITLE_TRACK_SWITCH,{id:n,groupId:a,name:o,type:l,url:d});const c=this.switchParams(s.url,null==i?void 0:i.details,s.details);this.loadPlaylist(c)}},timelineController:class{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(P.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(P.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(P.MANIFEST_LOADING,this.onManifestLoading,this),e.on(P.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(P.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(P.FRAG_LOADING,this.onFragLoading,this),e.on(P.FRAG_LOADED,this.onFragLoaded,this),e.on(P.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(P.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(P.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(P.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(P.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(P.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(P.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(P.MANIFEST_LOADING,this.onManifestLoading,this),e.off(P.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(P.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(P.FRAG_LOADING,this.onFragLoading,this),e.off(P.FRAG_LOADED,this.onFragLoaded,this),e.off(P.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(P.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(P.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(P.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(P.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new Jo(this,"textTrack1"),t=new Jo(this,"textTrack2"),i=new Jo(this,"textTrack3"),s=new Jo(this,"textTrack4");this.cea608Parser1=new Lo(1,e,t),this.cea608Parser2=new Lo(3,i,s)}addCues(e,t,i,s,r){let n=!1;for(let e=r.length;e--;){const s=r[e],a=tl(s[0],s[1],t,i);if(a>=0&&(s[0]=Math.min(s[0],t),s[1]=Math.max(s[1],i),n=!0,a/(i-t)>.5))return}if(n||r.push([t,i]),this.config.renderTextTracksNatively){const r=this.captionsTracks[e];this.Cues.newCue(r,t,i,s)}else{const r=this.Cues.newCue(null,t,i,s);this.hls.trigger(P.CUES_PARSED,{type:"captions",cues:r,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:s,timescale:r,trackId:n}){const{unparsedVttFrags:a}=this;i===M&&(this.initPTS[t.cc]={baseTime:s,timescale:r,trackId:n}),a.length&&(this.unparsedVttFrags=[],a.forEach(e=>{this.initPTS[e.frag.cc]?this.onFragLoaded(P.FRAG_LOADED,e):this.hls.trigger(P.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){const{media:i}=this;if(i)for(let s=0;s<i.textTracks.length;s++){const r=i.textTracks[s];if(el(r,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return r}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:i,media:s}=this,{label:r,languageCode:n}=t[e],a=this.getExistingTrack(r,n);if(a)i[e]=a,Ga(i[e]),$a(i[e],s);else{const t=this.createTextTrack("captions",r,n);t&&(t[e]=!0,i[e]=t)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const i={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(P.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}createTextTrack(e,t,i){const s=this.media;if(s)return s.addTextTrack(e,t,i)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){const i=!!t.transferMedia;if(this.media=null,i)return;const{captionsTracks:s}=this;Object.keys(s).forEach(e=>{Ga(s[e]),delete s[e]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let e=0;e<t.length;e++)Ga(t[e])}onSubtitleTracksUpdated(e,t){const i=t.subtitleTracks||[],s=i.some(e=>e.textCodec===Vo);if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(Dn(this.tracks,i))return void(this.tracks=i);if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const e=this.media,t=e?Ka(e.textTracks):null;if(this.tracks.forEach((e,i)=>{let s;if(t){let i=null;for(let s=0;s<t.length;s++)if(t[s]&&el(t[s],e)){i=t[s],t[s]=null;break}i&&(s=i)}if(s)Ga(s);else{const t=Zo(e);s=this.createTextTrack(t,e.name,e.lang),s&&(s.mode="disabled")}s&&this.textTracks.push(s)}),null!=t&&t.length){const e=t.filter(e=>null!==e).map(e=>e.label);e.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${e.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const e=this.tracks.map(e=>({label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e}));this.hls.trigger(P.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:e})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(e=>{const t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(!t)return;const i=`textTrack${t[1]}`,s=this.captionsProperties[i];s&&(s.label=e.name,e.lang&&(s.languageCode=e.lang),s.media=e)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===M){var i,s;const{cea608Parser1:e,cea608Parser2:r,lastSn:n}=this,{cc:a,sn:o}=t.frag,l=null!=(i=null==(s=t.part)?void 0:s.index)?i:-1;e&&r&&(o!==n+1||o===n&&l!==this.lastPartIndex+1||a!==this.lastCc)&&(e.reset(),r.reset()),this.lastCc=a,this.lastSn=o,this.lastPartIndex=l}}onFragLoaded(e,t){const{frag:i,payload:s}=t;if(i.type===F)if(s.byteLength){const e=i.decryptdata,r="stats"in t;if(null==e||!e.encrypted||r){const e=this.tracks[i.level],r=this.vttCCs;r[i.cc]||(r[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),e&&e.textCodec===Vo?this._parseIMSC1(i,s):this._parseVTTs(t)}}else this.hls.trigger(P.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const i=this.hls;jo(t,this.initPTS[e.cc],t=>{this._appendCues(t,e.level),i.trigger(P.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},t=>{i.logger.log(`Failed to parse IMSC1: ${t}`),i.trigger(P.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})})}_parseVTTs(e){var t;const{frag:i,payload:s}=e,{initPTS:r,unparsedVttFrags:n}=this,a=r.length-1;if(!r[i.cc]&&-1===a)return void n.push(e);const o=this.hls;$o(null!=(t=i.initSegment)&&t.data?Ce(i.initSegment.data,new Uint8Array(s)).buffer:s,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,e=>{this._appendCues(e,i.level),o.trigger(P.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},t=>{const r="Missing initPTS for VTT MPEGTS"===t.message;r?n.push(e):this._fallbackToIMSC1(i,s),o.logger.log(`Failed to parse VTT cue: ${t}`),r&&a>i.cc||o.trigger(P.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:t})})}_fallbackToIMSC1(e,t){const i=this.tracks[e.level];i.textCodec||jo(t,this.initPTS[e.cc],()=>{i.textCodec=Vo,this._parseIMSC1(e,t)},()=>{i.textCodec="wvtt"})}_appendCues(e,t){const i=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[t];if(!i||"disabled"===i.mode)return;e.forEach(e=>Va(i,e))}else{const s=this.tracks[t];if(!s)return;const r=s.default?"default":"subtitles"+t;i.trigger(P.CUES_PARSED,{type:"subtitles",cues:e,track:r})}}onFragDecrypted(e,t){const{frag:i}=t;i.type===F&&this.onFragLoaded(P.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:i,samples:s}=t;if(i.type!==M||"NONE"!==this.closedCaptionsForLevel(i))for(let e=0;e<s.length;e++){const t=s[e].bytes;if(t){this.cea608Parser1||this.initCea608Parsers();const i=this.extractCea608Data(t);this.cea608Parser1.addData(s[e].pts,i[0]),this.cea608Parser2.addData(s[e].pts,i[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:i,endOffsetSubtitles:s,type:r}){const{media:n}=this;if(n&&!(n.currentTime<i)){if(!r||"video"===r){const{captionsTracks:e}=this;Object.keys(e).forEach(s=>Ha(e[s],t,i))}if(this.config.renderTextTracksNatively&&0===t&&void 0!==s){const{textTracks:e}=this;Object.keys(e).forEach(i=>Ha(e[i],t,s))}}}extractCea608Data(e){const t=[[],[]],i=31&e[0];let s=2;for(let r=0;r<i;r++){const i=e[s++],r=127&e[s++],n=127&e[s++];if(0===r&&0===n)continue;if(!!(4&i)){const e=3&i;0!==e&&1!==e||(t[e].push(r),t[e].push(n))}}return t}},audioStreamController:class extends Xs{constructor(e,t,i){super(e,t,i,"audio-stream-controller",O),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(P.LEVEL_LOADED,this.onLevelLoaded,this),e.on(P.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(P.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(P.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(P.BUFFER_RESET,this.onBufferReset,this),e.on(P.BUFFER_CREATED,this.onBufferCreated,this),e.on(P.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(P.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(P.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(P.FRAG_LOADING,this.onFragLoading,this),e.on(P.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(P.LEVEL_LOADED,this.onLevelLoaded,this),e.off(P.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(P.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(P.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(P.BUFFER_RESET,this.onBufferReset,this),e.off(P.BUFFER_CREATED,this.onBufferCreated,this),e.off(P.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(P.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(P.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(P.FRAG_LOADING,this.onFragLoading,this),e.off(P.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:i,initPTS:s,timescale:r,trackId:n}){if(i===M){const e=t.cc,i=this.fragCurrent;if(this.initPTS[e]={baseTime:s,timescale:r,trackId:n},this.log(`InitPTS for cc: ${e} found from main: ${s/r} (${s}/${r}) trackId: ${n}`),this.mainAnchor=t,this.state===Ys){const i=this.waitingData;(!i&&!this.loadingParts||i&&i.frag.cc!==e)&&this.syncWithAnchor(t,null==i?void 0:i.frag)}else!this.hls.hasEnoughToStart&&i&&i.cc!==e?(i.abortRequests(),this.syncWithAnchor(t,i)):this.state===Bs&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var i;const s=(null==(i=this.mainFragLoading)?void 0:i.frag)||null;if(t&&(null==s?void 0:s.cc)===t.cc)return;const r=(s||e).cc,n=Ct(this.getLevelDetails(),r,this.getLoadPosition());n&&(this.log(`Syncing with main frag at ${n.start} cc ${n.cc}`),this.startFragRequested=!1,this.nextLoadPosition=n.start,this.resetLoadingState(),this.state===Bs&&this.doTickIdle())}startLoad(e,t){if(!this.levels)return this.startPosition=e,void(this.state=Ns);const i=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),i>0&&-1===e?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i,this.state=Bs):this.state=Hs,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case Bs:this.doTickIdle();break;case Hs:{const{levels:e,trackId:t}=this,i=null==e?void 0:e[t],s=null==i?void 0:i.details;if(s&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(s))break;this.state=Ys}break}case Gs:this.checkRetryDate();break;case Ys:{const e=this.waitingData;if(e){const{frag:t,part:i,cache:s,complete:r}=e,n=this.mainAnchor;if(void 0!==this.initPTS[t.cc]){this.waitingData=null,this.state=Vs;const e={frag:t,part:i,payload:s.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(e),r&&super._handleFragmentLoadComplete(e)}else n&&n.cc!==e.frag.cc&&this.syncWithAnchor(n,e.frag)}else this.state=Bs}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:i,media:s,trackId:r}=this,n=t.config;if(!this.buffering||!s&&!this.primaryPrefetch&&(this.startFragRequested||!n.startFragPrefetch)||null==i||!i[r])return;const a=i[r],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o))return this.state=Hs,void(this.startFragRequested=!1);const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,ae,O));const d=this.getFwdBufferInfo(l,O);if(null===d)return;if(!this.switchingTrack&&this._streamEnded(d,o))return t.trigger(P.BUFFER_EOS,{type:"audio"}),void(this.state=Ws);const c=d.len,u=t.maxBufferLength,h=o.fragments,f=h[0].start,g=this.getLoadPosition(),p=this.flushing?g:d.end;if(this.switchingTrack&&s){const e=g;o.PTSKnown&&e<f&&(d.end>f||d.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),s.currentTime=f+.05)}if(c>=u&&!this.switchingTrack&&p<h[h.length-1].start)return;let m=this.getNextFragment(p,o);if(m&&this.isLoopLoading(m,p)&&(m=this.getNextFragmentLoopLoading(m,o,d,M,u)),!m)return void(this.bufferFlushed=!0);let v=(null==(e=this.mainFragLoading)?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&v&&ce(m)&&!m.endList&&(!o.live||!this.loadingParts&&p<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(v)===Zt&&(this.mainFragLoading=v=null),v&&ce(v))){if(m.start>v.end){const e=this.fragmentTracker.getFragAtPos(p,M);e&&e.end>v.end&&(v=e,this.mainFragLoading={frag:e,targetBufferTime:null})}if(m.start>v.end)return}this.loadFragment(m,a,p)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(e=>new mt(e))}onAudioTrackSwitching(e,t){const i=!!t.url;this.trackId=t.id;const{fragCurrent:s}=this;s&&(s.abortRequests(),this.removeUnbufferedFrags(s.start)),this.resetLoadingState(),i?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==Ns&&(this.setInterval(100),this.state=Bs,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(P.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(e,t){var i;const{levels:s}=this,{details:r,id:n,groupId:a,track:o}=t;if(!s)return void this.warn(`Audio tracks reset while loading track ${n} "${o.name}" of "${a}"`);const l=this.mainDetails;if(!l||r.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=t,void(this.state!==Ns&&(this.state=Hs));this.cachedTrackLoadedData=null,this.log(`Audio track ${n} "${o.name}" of "${a}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const d=s[n];let c=0;if(r.live||null!=(i=d.details)&&i.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;var u;if(d.details)c=this.alignPlaylists(r,d.details,null==(u=this.levelLastLoaded)?void 0:u.details);r.alignedSliding||(_s(r,l),r.alignedSliding||Ms(r,l),c=r.fragmentStart)}d.details=r,this.levelLastLoaded=d,this.startFragRequested||this.setStartPosition(l,c),this.hls.trigger(P.AUDIO_TRACK_UPDATED,{details:r,id:n,groupId:t.groupId}),this.state!==Hs||this.waitForCdnTuneIn(r)||(this.state=Bs),this.tick()}_handleFragmentLoadProgress(e){var t;const i=e.frag,{part:s,payload:r}=e,{config:n,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);const l=o[a];if(!l)return void this.warn("Audio track is undefined on fragment load progress");const d=l.details;if(!d)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(i.start);const c=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let u=this.transmuxer;u||(u=this.transmuxer=new wn(this.hls,O,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const h=this.initPTS[i.cc],f=null==(t=i.initSegment)?void 0:t.data;if(void 0!==h){const e=!1,t=s?s.index:-1,n=-1!==t,a=new mi(i.level,i.sn,i.stats.chunkCount,r.byteLength,t,n);u.push(r,f,c,"",i,s,d.totalduration,e,a,h)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${d.startSN} ,${d.endSN}],track ${a}`);const{cache:e}=this.waitingData=this.waitingData||{frag:i,part:s,cache:new Js,complete:!1};e.push(new Uint8Array(r)),this.state!==Ns&&(this.state=Ys)}}_handleFragmentLoadComplete(e){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;const i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===M&&ce(t.frag)&&(this.mainFragLoading=t,this.state===Bs&&this.tick())}onFragBuffered(e,t){const{frag:i,part:s}=t;if(i.type===O)if(this.fragContextChanged(i))this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if(ce(i)){this.fragPrevious=i;const e=this.switchingTrack;e&&(this.bufferedTrack=e,this.switchingTrack=null,this.hls.trigger(P.AUDIO_TRACK_SWITCHED,G({},e)))}this.fragBufferedComplete(i,s),this.media&&this.tick()}else this.audioOnly||i.type!==M||i.elementaryStreams.video||i.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}onError(e,t){var i;if(t.fatal)this.state=qs;else switch(t.details){case w.FRAG_GAP:case w.FRAG_PARSING_ERROR:case w.FRAG_DECRYPT_ERROR:case w.FRAG_LOAD_ERROR:case w.FRAG_LOAD_TIMEOUT:case w.KEY_LOAD_ERROR:case w.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(O,t);break;case w.AUDIO_TRACK_LOAD_ERROR:case w.AUDIO_TRACK_LOAD_TIMEOUT:case w.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==Hs||(null==(i=t.context)?void 0:i.type)!==C||(this.state=Bs);break;case w.BUFFER_ADD_CODEC_ERROR:case w.BUFFER_APPEND_ERROR:if("audio"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case w.BUFFER_FULL_ERROR:if("audio"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case w.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onBufferFlushing(e,{type:t}){t!==oe&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==oe){this.flushing=!1,this.bufferFlushed=!0,this.state===Ws&&(this.state=Bs);const e=this.mediaBuffer||this.media;e&&(this.afterBufferFlushed(e,t,O),this.tick())}}_handleTransmuxComplete(e){var t;const i="audio",{hls:s}=this,{remuxResult:r,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:d}=a,{details:c}=d,{audio:u,text:h,id3:f,initSegment:g}=r;if(!this.fragContextChanged(o)&&c){if(this.state=Ks,this.switchingTrack&&u&&this.completeAudioSwitch(this.switchingTrack),null!=g&&g.tracks){const e=o.initSegment||o;if(this.unhandledEncryptionError(g,o))return;this._bufferInitSegment(d,g.tracks,e,n),s.trigger(P.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:i,tracks:g.tracks})}if(u){const{startPTS:e,endPTS:t,startDTS:i,endDTS:s}=u;l&&(l.elementaryStreams[ae]={startPTS:e,endPTS:t,startDTS:i,endDTS:s}),o.setElementaryStreamInfo(ae,e,t,i,s),this.bufferFragmentData(u,o,l,n)}if(null!=f&&null!=(t=f.samples)&&t.length){const e=$({id:i,frag:o,details:c},f);s.trigger(P.FRAG_PARSING_METADATA,e)}if(h){const e=$({id:i,frag:o,details:c},h);s.trigger(P.FRAG_PARSING_USERDATA,e)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(e,t,i,s){if(this.state!==Ks)return;if(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio)return;const r=t.audio;r.id=O;const n=e.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${n}/${r.codec}]`),n&&1===n.split(",").length&&(r.levelCodec=n),this.hls.trigger(P.BUFFER_CODECS,t);const a=r.initSegment;if(null!=a&&a.byteLength){const e={type:"audio",frag:i,part:null,chunkMeta:s,parent:i.type,data:a};this.hls.trigger(P.BUFFER_APPENDING,e)}this.tickImmediate()}loadFragment(e,t,i){const s=this.fragmentTracker.getState(e);var r;if(this.switchingTrack||s===Xt||s===Jt)if(ce(e))if(null!=(r=t.details)&&r.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=Ys;const i=this.mainDetails;i&&i.fragmentStart!==t.details.fragmentStart&&Ms(t.details,i)}else super.loadFragment(e,t,i);else this._loadInitSegment(e,t);else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:i,assocLang:s,characteristics:r,audioCodec:n,channels:a}=this.bufferedTrack;Lt({name:t,lang:i,assocLang:s,characteristics:r,audioCodec:n,channels:a},e,Rt)||(kt(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(P.AUDIO_TRACK_SWITCHED,G({},e))}},audioTrackController:class extends Pn{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(P.MANIFEST_LOADING,this.onManifestLoading,this),e.on(P.MANIFEST_PARSED,this.onManifestParsed,this),e.on(P.LEVEL_LOADING,this.onLevelLoading,this),e.on(P.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(P.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(P.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(P.MANIFEST_LOADING,this.onManifestLoading,this),e.off(P.MANIFEST_PARSED,this.onManifestParsed,this),e.off(P.LEVEL_LOADING,this.onLevelLoading,this),e.off(P.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(P.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(P.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:i,groupId:s,details:r}=t,n=this.tracksInGroup[i];if(!n||n.groupId!==s)return void this.warn(`Audio track with id:${i} and group:${s} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=t.details,this.log(`Audio track ${i} "${n.name}" lang:${n.lang} group:${s} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.audioGroups||null,s=this.groupIds;let r=this.currentTrack;if(!i||(null==s?void 0:s.length)!==(null==i?void 0:i.length)||null!=i&&i.some(e=>-1===(null==s?void 0:s.indexOf(e)))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const e=this.tracks.filter(e=>!i||-1!==i.indexOf(e.groupId));if(e.length)this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),e.forEach((e,t)=>{e.id=t});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=e;const t=this.hls.config.audioPreference;if(!r&&t){const i=bt(t,e,Rt);if(i>-1)r=e[i];else{const e=bt(t,this.tracks);r=this.tracks[e]}}let s=this.findTrackId(r);-1===s&&r&&(s=this.findTrackId(null));const a={audioTracks:e};this.log(`Updating audio tracks, ${e.length} track(s) found in group(s): ${null==i?void 0:i.join(",")}`),this.hls.trigger(P.AUDIO_TRACKS_UPDATED,a);const o=this.trackId;if(-1!==s&&-1===o)this.setAudioTrack(s);else if(e.length&&-1===o){var n;const t=new Error(`No audio track selected for current audio group-ID(s): ${null==(n=this.groupIds)?void 0:n.join(",")} track count: ${e.length}`);this.warn(t.message),this.hls.trigger(P.ERROR,{type:k.MEDIA_ERROR,details:w.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:t})}}}onError(e,t){!t.fatal&&t.context&&(t.context.type!==C||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){const s=this.currentTrack;if(s&&Lt(e,s,Rt))return s;const r=bt(e,this.tracksInGroup,Rt);if(r>-1){const e=this.tracksInGroup[r];return this.setAudioTrack(r),e}if(s){let s=t.loadLevel;-1===s&&(s=t.firstAutoLevel);const r=function(e,t,i,s,r){const n=t[s],a=t.reduce((e,t,i)=>{const s=t.uri;return(e[s]||(e[s]=[])).push(i),e},{})[n.uri];a.length>1&&(s=Math.max.apply(Math,a));const o=n.videoRange,l=n.frameRate,d=n.codecSet.substring(0,4),c=It(t,s,t=>{if(t.videoRange!==o||t.frameRate!==l||t.codecSet.substring(0,4)!==d)return!1;const s=t.audioGroups,n=i.filter(e=>!s||-1!==s.indexOf(e.groupId));return bt(e,n,r)>-1});return c>-1?c:It(t,s,t=>{const s=t.audioGroups,n=i.filter(e=>!s||-1!==s.indexOf(e.groupId));return bt(e,n,r)>-1})}(e,t.levels,i,s,Rt);if(-1===r)return null;t.nextLoadLevel=r}if(e.channels||e.audioCodec){const t=bt(e,i);if(t>-1)return i[t]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length)return void this.warn(`Invalid audio track id: ${e}`);this.selectDefaultTrack=!1;const i=this.currentTrack,s=t[e],r=s.details&&!s.details.live;if(e===this.trackId&&s===i&&r)return;if(this.log(`Switching to audio-track ${e} "${s.name}" lang:${s.lang} group:${s.groupId} channels:${s.channels}`),this.trackId=e,this.currentTrack=s,this.hls.trigger(P.AUDIO_TRACK_SWITCHING,G({},s)),r)return;const n=this.switchParams(s.url,null==i?void 0:i.details,s.details);this.loadPlaylist(n)}findTrackId(e){const t=this.tracksInGroup;for(let i=0;i<t.length;i++){const s=t[i];if((!this.selectDefaultTrack||s.default)&&(!e||Lt(e,s,Rt)))return i}if(e){const{name:i,lang:s,assocLang:r,characteristics:n,audioCodec:a,channels:o}=e;for(let e=0;e<t.length;e++){if(Lt({name:i,lang:s,assocLang:r,characteristics:n,audioCodec:a,channels:o},t[e],Rt))return e}for(let i=0;i<t.length;i++){const s=t[i];if(xn(e.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){const s=t[i];if(xn(e.attrs,s.attrs,["LANGUAGE"]))return i}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&kt(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=e.id,s=e.groupId,r=this.getUrlWithDirectives(e.url,t),n=e.details,a=null==n?void 0:n.age;this.log(`Loading audio-track ${i} "${e.name}" lang:${e.lang} group:${s}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(P.AUDIO_TRACK_LOADING,{url:r,id:i,groupId:s,deliveryDirectives:t||null,track:e})}},emeController:Oa,cmcdController:class{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=e=>{try{this.apply(e,{ot:$n.MANIFEST,su:!this.initialized})}catch(e){this.hls.logger.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=e=>{try{const{frag:t,part:i}=e,s=this.hls.levels[t.level],r=this.getObjectType(t),n={d:1e3*(i||t).duration,ot:r};r!==$n.VIDEO&&r!==$n.AUDIO&&r!=$n.MUXED||(n.br=s.bitrate/1e3,n.tb=this.getTopBandwidth(r)/1e3,n.bl=this.getBufferLength(r));const a=i?this.getNextPart(i):this.getNextFrag(t);null!=a&&a.url&&a.url!==t.url&&(n.nor=a.url),this.apply(e,n)}catch(e){this.hls.logger.warn("Could not generate segment CMCD data.",e)}},this.hls=e;const t=this.config=e.config,{cmcd:i}=t;null!=i&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||e.sessionId,this.cid=i.contentId,this.useHeaders=!0===i.useHeaders,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(P.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(P.MEDIA_DETACHED,this.onMediaDetached,this),e.on(P.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(P.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(P.MEDIA_DETACHED,this.onMediaDetached,this),e.off(P.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var i,s;this.audioBuffer=null==(i=t.tracks.audio)?void 0:i.buffer,this.videoBuffer=null==(s=t.tracks.video)?void 0:s.buffer}createData(){var e;return{v:1,sf:Vn.HLS,sid:this.sid,cid:this.cid,pr:null==(e=this.media)?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){$(t,this.createData());const i=t.ot===$n.INIT||t.ot===$n.VIDEO||t.ot===$n.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering);const{includeKeys:s}=this;s&&(t=Object.keys(t).reduce((e,i)=>(s.includes(i)&&(e[i]=t[i]),e),{}));const r={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),Pa(e.headers,t,r)):e.url=Ca(e.url,t,r)}getNextFrag(e){var t;const i=null==(t=this.hls.levels[e.level])?void 0:t.details;if(i){const t=e.sn-i.startSN;return i.fragments[t+1]}}getNextPart(e){var t;const{index:i,fragment:s}=e,r=null==(t=this.hls.levels[s.level])||null==(t=t.details)?void 0:t.partList;if(r){const{sn:e}=s;for(let t=r.length-1;t>=0;t--){const s=r[t];if(s.index===i&&s.fragment.sn===e)return r[t+1]}}}getObjectType(e){const{type:t}=e;return"subtitle"===t?$n.TIMED_TEXT:"initSegment"===e.sn?$n.INIT:"audio"===t?$n.AUDIO:"main"===t?this.hls.audioTracks.length?$n.VIDEO:$n.MUXED:void 0}getTopBandwidth(e){let t,i=0;const s=this.hls;if(e===$n.AUDIO)t=s.audioTracks;else{const e=s.maxAutoLevel,i=e>-1?e+1:s.levels.length;t=s.levels.slice(0,i)}return t.forEach(e=>{e.bitrate>i&&(i=e.bitrate)}),i>0?i:NaN}getBufferLength(e){const t=this.media,i=e===$n.AUDIO?this.audioBuffer:this.videoBuffer;if(!i||!t)return NaN;return 1e3*yi.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new i(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,i,s){t(e),this.loader.load(e,i,s)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new i(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,i,s){t(e),this.loader.load(e,i,s)}}}},contentSteeringController:class extends H{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(P.MANIFEST_LOADING,this.onManifestLoading,this),e.on(P.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(P.MANIFEST_PARSED,this.onManifestParsed,this),e.on(P.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(P.MANIFEST_LOADING,this.onManifestLoading,this),e.off(P.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(P.MANIFEST_PARSED,this.onManifestParsed,this),e.off(P.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(t=>t!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:i}=t;null!==i&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:i}=t;if((null==i?void 0:i.action)===Gt&&i.flags===Wt){const e=this.levels;let s=this._pathwayPriority,r=this.pathwayId;if(t.context){const{groupId:i,pathwayId:s,type:n}=t.context;i&&e?r=this.getPathwayForGroupId(i,n,r):s&&(r=s)}r in this.penalizedPathways||(this.penalizedPathways[r]=performance.now()),!s&&e&&(s=this.pathways()),s&&s.length>1&&(this.updatePathwayPriority(s),i.resolved=this.pathwayId!==r),t.details!==w.BUFFER_APPEND_ERROR||t.fatal?i.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${r} levels: ${e?e.length:e} priorities: ${Tt(s)} penalized: ${Tt(this.penalizedPathways)}`):i.resolved=!0}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){const i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return null===this.levels?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){let t;this._pathwayPriority=e;const i=this.penalizedPathways,s=performance.now();Object.keys(i).forEach(e=>{s-i[e]>3e5&&delete i[e]});for(let s=0;s<e.length;s++){const r=e[s];if(r in i)continue;if(r===this.pathwayId)return;const n=this.hls.nextLoadLevel,a=this.hls.levels[n];if(t=this.getLevelsForPathway(r),t.length>0){this.log(`Setting Pathway to "${r}"`),this.pathwayId=r,ks(t),this.hls.trigger(P.LEVELS_UPDATED,{levels:t});const e=this.hls.levels[n];a&&e&&this.levels&&(e.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&e.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${e.bitrate}`),this.hls.nextLoadLevel=n);break}}}getPathwayForGroupId(e,t,i){const s=this.getLevelsForPathway(i).concat(this.levels||[]);for(let i=0;i<s.length;i++)if(t===C&&s[i].hasAudioGroup(e)||t===_&&s[i].hasSubtitleGroup(e))return s[i].pathwayId;return i}clonePathways(e){const t=this.levels;if(!t)return;const i={},s={};e.forEach(e=>{const{ID:r,"BASE-ID":n,"URI-REPLACEMENT":a}=e;if(t.some(e=>e.pathwayId===r))return;const o=this.getLevelsForPathway(n).map(e=>{const t=new Ii(e.attrs);t["PATHWAY-ID"]=r;const n=t.AUDIO&&`${t.AUDIO}_clone_${r}`,o=t.SUBTITLES&&`${t.SUBTITLES}_clone_${r}`;n&&(i[t.AUDIO]=n,t.AUDIO=n),o&&(s[t.SUBTITLES]=o,t.SUBTITLES=o);const l=Ma(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),d=new mt({attrs:t,audioCodec:e.audioCodec,bitrate:e.bitrate,height:e.height,name:e.name,url:l,videoCodec:e.videoCodec,width:e.width});if(e.audioGroups)for(let t=1;t<e.audioGroups.length;t++)d.addGroupId("audio",`${e.audioGroups[t]}_clone_${r}`);if(e.subtitleGroups)for(let t=1;t<e.subtitleGroups.length;t++)d.addGroupId("text",`${e.subtitleGroups[t]}_clone_${r}`);return d});t.push(...o),_a(this.audioTracks,i,a,r),_a(this.subtitleTracks,s,a,r)})}loadSteeringManifest(e){const t=this.hls.config,i=t.loader;let s;this.loader&&this.loader.destroy(),this.loader=new i(t);try{s=new self.URL(e)}catch(t){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${e}`)}if("data:"!==s.protocol){const e=0|(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate);s.searchParams.set("_HLS_pathway",this.pathwayId),s.searchParams.set("_HLS_throughput",""+e)}const r={responseType:"json",url:s.href},n=t.steeringManifestLoadPolicy.default,a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(e,t,i,r)=>{this.log(`Loaded steering manifest: "${s}"`);const n=e.data;if(1!==(null==n?void 0:n.VERSION))return void this.log(`Steering VERSION ${n.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=n.TTL;const{"RELOAD-URI":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":l}=n;if(a)try{this.uri=new self.URL(a,s).href}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||i.url),o&&this.clonePathways(o);const d={steeringManifest:n,url:s.toString()};this.hls.trigger(P.STEERING_MANIFEST_LOADED,d),l&&this.updatePathwayPriority(l)},onError:(e,t,i,s)=>{if(this.log(`Error loading steering manifest: ${e.code} ${e.text} (${t.url})`),this.stopLoad(),410===e.code)return this.enabled=!1,void this.log(`Steering manifest ${t.url} no longer available`);let r=1e3*this.timeToLoad;if(429===e.code){const e=this.loader;if("function"==typeof(null==e?void 0:e.getResponseHeader)){const t=e.getResponseHeader("Retry-After");t&&(r=1e3*parseFloat(t))}return void this.log(`Steering manifest ${t.url} rate limited`)}this.scheduleRefresh(this.uri||t.url,r)},onTimeout:(e,t,i)=>{this.log(`Timeout loading steering manifest (${t.url})`),this.scheduleRefresh(this.uri||t.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(r,o,l)}scheduleRefresh(e,t=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var t;const i=null==(t=this.hls)?void 0:t.media;!i||i.ended?this.scheduleRefresh(e,1e3*this.timeToLoad):this.loadSteeringManifest(e)},t)}},interstitialsController:class extends H{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const e=this.currentTime;if(void 0===e||this.playbackDisabled||!this.schedule)return;const t=e-this.timelinePos;if(Math.abs(t)<1/7056e5)return;const i=t<=-.01;this.timelinePos=e,this.bufferedPos=e;const s=this.playingItem;if(!s)return void this.checkBuffer();if(i){this.schedule.resetErrorsInRange(e,e-t)&&this.updateSchedule(!0)}if(this.checkBuffer(),i&&e<s.start||e>=s.end){var r;const t=this.findItemIndex(s);let n=this.schedule.findItemIndexAtTime(e);if(-1===n&&(n=t+(i?-1:1),this.log(`seeked ${i?"back ":""}to position not covered by schedule ${e} (resolving from ${t} to ${n})`)),!this.isInterstitial(s)&&null!=(r=this.media)&&r.paused&&(this.shouldPlay=!1),!i&&n>t){const e=this.schedule.findJumpRestrictedIndex(t+1,n);if(e>t)return void this.setSchedulePosition(e)}return void this.setSchedulePosition(n)}const n=this.playingAsset;if(!n){if(this.playingLastItem&&this.isInterstitial(s)){const t=s.event.assetList[0];t&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(e,t))}return}const a=n.timelineStart,o=n.duration||0;var l;(i&&e<a||e>=a+o)&&(null!=(l=s.event)&&l.appendInPlace&&(this.clearInterstitial(s.event,s),this.flushFrontBuffer(e)),this.setScheduleToAssetAtTime(e,n))},this.onTimeupdate=()=>{const e=this.currentTime;if(void 0===e||this.playbackDisabled)return;if(!(e>this.timelinePos))return;this.timelinePos=e,e>this.bufferedPos&&this.checkBuffer();const t=this.playingItem;if(!t||this.playingLastItem)return;if(e>=t.end){this.timelinePos=t.end;const e=this.findItemIndex(t);this.setSchedulePosition(e+1)}const i=this.playingAsset;if(!i)return;e>=i.timelineStart+(i.duration||0)&&this.setScheduleToAssetAtTime(e,i)},this.onScheduleUpdate=(e,t)=>{const i=this.schedule;if(!i)return;const s=this.playingItem,r=i.events||[],n=i.items||[],a=i.durations,o=e.map(e=>e.identifier),l=!(!r.length&&!o.length);(l||t)&&this.log(`INTERSTITIALS_UPDATED (${r.length}): ${r}\nSchedule: ${n.map(e=>io(e))} pos: ${this.timelinePos}`),o.length&&this.log(`Removed events ${o}`);let d=null,c=null;s&&(d=this.updateItem(s,this.timelinePos),this.itemsMatch(s,d)?this.playingItem=d:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const u=this.bufferingItem;if(u&&(c=this.updateItem(u,this.bufferedPos),this.itemsMatch(u,c)?this.bufferingItem=c:u.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(u.event,null))),e.forEach(e=>{e.assetList.forEach(e=>{this.clearAssetPlayer(e.identifier,null)})}),this.playerQueue.forEach(e=>{if(e.interstitial.appendInPlace){const t=e.assetItem.timelineStart,i=e.timelineOffset-t;if(i)try{e.timelineOffset=t}catch(s){Math.abs(i)>Wa&&this.warn(`${s} ("${e.assetId}" ${e.timelineOffset}->${t})`)}}}),l||t){if(this.hls.trigger(P.INTERSTITIALS_UPDATED,{events:r.slice(0),schedule:n.slice(0),durations:a,removedIds:o}),this.isInterstitial(s)&&o.includes(s.event.identifier))return this.warn(`Interstitial "${s.event.identifier}" removed while playing`),void this.primaryFallback(s.event);s&&this.trimInPlace(d,s),u&&c!==d&&this.trimInPlace(c,u),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new so(e),this.schedule=new to(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(P.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(P.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(P.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(P.MANIFEST_LOADING,this.onManifestLoading,this),e.on(P.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(P.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(P.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(P.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(P.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(P.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(P.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(P.BUFFER_APPENDED,this.onBufferAppended,this),e.on(P.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(P.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(P.MEDIA_ENDED,this.onMediaEnded,this),e.on(P.ERROR,this.onError,this),e.on(P.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(P.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(P.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(P.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(P.MANIFEST_LOADING,this.onManifestLoading,this),e.off(P.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(P.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(P.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(P.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(P.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(P.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(P.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(P.BUFFER_CODECS,this.onBufferCodecs,this),e.off(P.BUFFER_APPENDED,this.onBufferAppended,this),e.off(P.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(P.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(P.MEDIA_ENDED,this.onMediaEnded,this),e.off(P.ERROR,this.onError,this),e.off(P.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;null==(e=this.getBufferingPlayer())||e.resumeBuffering()}pauseBuffering(){var e;null==(e=this.getBufferingPlayer())||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){Fs(e,"play",this.onPlay),Fs(e,"pause",this.onPause),Fs(e,"seeking",this.onSeeking),Fs(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const i=this.media=t.media;Os(i,"seeking",this.onSeeking),Os(i,"timeupdate",this.onTimeupdate),Os(i,"play",this.onPlay),Os(i,"pause",this.onPause)}onMediaAttached(e,t){const i=this.effectivePlayingItem,s=this.detachedData;if(this.detachedData=null,null===i)this.checkStart();else if(!s){this.clearScheduleState();const e=this.findItemIndex(i);this.setSchedulePosition(e)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const i=!!t.transferMedia,s=this.media;if(this.media=null,!i&&(s&&this.removeMediaListeners(s),this.detachedData)){const e=this.getBufferingPlayer();e&&(this.log(`Removing schedule state for detachedData and ${e}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,e.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const e=this,t=()=>e.bufferingItem||e.waitingItem,i=t=>t?e.getAssetPlayer(t.identifier):t,s=(t,s,n,a,o)=>{if(t){let l=t[s].start;const d=t.event;if(d){if("playout"===s||d.timelineOccupancy!==qa.Point){const e=i(n);(null==e?void 0:e.interstitial)===d&&(l+=e.assetItem.startOffset+e[o])}}else{l+=("bufferedPos"===a?r():e[a])-t.start}return l}return 0},r=()=>{const t=e.bufferedPos;return t===Number.MAX_VALUE?n("primary"):Math.max(t,0)},n=t=>{var i,s;return null!=(i=e.primaryDetails)&&i.live?e.primaryDetails.edge:(null==(s=e.schedule)?void 0:s.durations[t])||0},a=(t,r)=>{var n,a;const o=e.effectivePlayingItem;if(null!=o&&null!=(n=o.event)&&n.restrictions.skip||!e.schedule)return;e.log(`seek to ${t} "${r}"`);const l=e.effectivePlayingItem,d=e.schedule.findItemIndexAtTime(t,r),c=null==(a=e.schedule.items)?void 0:a[d],u=e.getBufferingPlayer(),h=null==u?void 0:u.interstitial,f=null==h?void 0:h.appendInPlace,g=l&&e.itemsMatch(l,c);if(l&&(f||g)){const n=i(e.playingAsset),a=(null==n?void 0:n.media)||e.primaryMedia;if(a){const i="primary"===r?a.currentTime:s(l,r,e.playingAsset,"timelinePos","currentTime"),o=t-i,d=(f?i:a.currentTime)+o;if(d>=0&&(!n||f||d<=n.duration))return void(a.currentTime=d)}}if(c){let i=t;if("primary"!==r){const e=t-c[r].start;i=c.start+e}const s=!e.isInterstitial(c);if(e.isInterstitial(l)&&!l.event.appendInPlace||!s&&!c.event.appendInPlace){if(l){const n=e.findItemIndex(l);if(d>n){const t=e.schedule.findJumpRestrictedIndex(n+1,d);if(t>n)return void e.setSchedulePosition(t)}let a=0;if(s)e.timelinePos=i,e.checkBuffer();else{const e=c.event.assetList,i=t-(c[r]||c).start;for(let t=e.length;t--;){const s=e[t];if(s.duration&&i>=s.startOffset&&i<s.startOffset+s.duration){a=t;break}}}e.setSchedulePosition(d,a)}}else{const t=e.media||(f?null==u?void 0:u.media:null);t&&(t.currentTime=i)}}},o=()=>{const i=e.effectivePlayingItem;if(e.isInterstitial(i))return i;const s=t();return e.isInterstitial(s)?s:null},l={get bufferedEnd(){const i=t(),r=e.bufferingItem;var n;return r&&r===i&&(s(r,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-r.playout.start||(null==(n=e.bufferingAsset)?void 0:n.startOffset))||0},get currentTime(){const t=o(),i=e.effectivePlayingItem;return i&&i===t?s(i,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-i.playout.start:0},set currentTime(t){const i=o(),s=e.effectivePlayingItem;s&&s===i&&a(t+s.playout.start,"playout")},get duration(){const e=o();return e?e.playout.end-e.playout.start:0},get assetPlayers(){var t;const i=null==(t=o())?void 0:t.event.assetList;return i?i.map(t=>e.getAssetPlayer(t.identifier)):[]},get playingIndex(){var t;const i=null==(t=o())?void 0:t.event;return i&&e.effectivePlayingAsset?i.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return o()}};return this.manager={get events(){var t;return(null==(t=e.schedule)||null==(t=t.events)?void 0:t.slice(0))||[]},get schedule(){var t;return(null==(t=e.schedule)||null==(t=t.items)?void 0:t.slice(0))||[]},get interstitialPlayer(){return o()?l:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const i=t();return e.findItemIndex(i)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const t=e.effectivePlayingItem;return e.findItemIndex(t)},primary:{get bufferedEnd(){return r()},get currentTime(){const t=e.timelinePos;return t>0?t:0},set currentTime(e){a(e,"primary")},get duration(){return n("primary")},get seekableStart(){var t;return(null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0}},integrated:{get bufferedEnd(){return s(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return s(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(e){a(e,"integrated")},get duration(){return n("integrated")},get seekableStart(){var t;return((t,i)=>{var s;if(0!==t&&"primary"!==i&&null!=(s=e.schedule)&&s.length){var r;const s=e.schedule.findItemIndexAtTime(t),n=null==(r=e.schedule.items)?void 0:r[s];if(n)return t+(n[i].start-n.start)}return t})((null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0,"integrated")}},skip:()=>{const t=e.effectivePlayingItem,i=null==t?void 0:t.event;if(i&&!i.restrictions.skip){const s=e.findItemIndex(t);if(i.appendInPlace){const e=t.playout.start+t.event.duration;a(e+.001,"playout")}else e.advanceAfterAssetEnded(i,s,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,i=null==(e=this.schedule)?void 0:e.items;return!!(this.playbackStarted&&t&&i)&&this.findItemIndex(t)===i.length-1}get playbackStarted(){return null!==this.effectivePlayingItem}get currentTime(){var e,t;if(null===this.mediaSelection)return;const i=this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&!i.event.appendInPlace)return;let s=this.media;!s&&null!=(e=this.bufferingItem)&&null!=(e=e.event)&&e.appendInPlace&&(s=this.primaryMedia);const r=null==(t=s)?void 0:t.currentTime;return void 0!==r&&L(r)?r:void 0}get primaryMedia(){var e;return this.media||(null==(e=this.detachedData)?void 0:e.media)||null}isInterstitial(e){return!(null==e||!e.event)}retreiveMediaSource(e,t){const i=this.getAssetPlayer(e);i&&this.transferMediaFromPlayer(i,t)}transferMediaFromPlayer(e,t){const i=e.interstitial.appendInPlace,s=e.media;if(i&&s===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&s)return void(this.detachedData={media:s});const i=e.transferMedia();this.log(`transfer MediaSource from ${e} ${Tt(i)}`),this.detachedData=i}else t&&s&&(this.shouldPlay||(this.shouldPlay=!s.paused))}transferMediaTo(e,t){var i,s;if(e.media===t)return;let r=null;const n=this.hls,a=e!==n,o=a&&e.interstitial.appendInPlace,l=null==(i=this.detachedData)?void 0:i.mediaSource;let d;if(n.media)o&&(r=n.transferMedia(),this.detachedData=r),d="Primary";else if(l){const e=this.getBufferingPlayer();e?(r=e.transferMedia(),d=`${e}`):d="detached MediaSource"}else d="detached media";if(!r)if(l)r=this.detachedData,this.log(`using detachedData: MediaSource ${Tt(r)}`);else if(!this.detachedData||n.media===t){const e=this.playerQueue;e.length>1&&e.forEach(e=>{if(a&&e.interstitial.appendInPlace!==o){const t=e.interstitial;this.clearInterstitial(e.interstitial,null),t.appendInPlace=!1,t.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${t}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}const c=r&&"mediaSource"in r&&"closed"!==(null==(s=r.mediaSource)?void 0:s.readyState),u=c&&r?r:t;this.log(`${c?"transfering MediaSource":"attaching media"} to ${a?e:"Primary"} from ${d} (media.currentTime: ${t.currentTime})`);const h=this.schedule;if(u===r&&h){const t=a&&e.assetId===h.assetIdAtEnd;u.overrides={duration:h.duration,endOfStream:!a||t,cueRemoval:!a}}e.attachMedia(u)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=null==e?void 0:e.events;if(!t||this.playbackDisabled||!this.media)return;-1===this.bufferedPos&&(this.bufferedPos=0);const i=this.timelinePos,s=this.effectivePlayingItem;if(-1===i){const i=this.hls.startPosition;if(this.log(no("checkStart",i)),this.timelinePos=i,t.length&&t[0].cue.pre){const i=e.findEventIndex(t[0].identifier);this.setSchedulePosition(i)}else if(i>=0||!this.primaryLive){const t=this.timelinePos=i>0?i:0,s=e.findItemIndexAtTime(t);this.setSchedulePosition(s)}}else if(s&&!this.playingItem){const t=e.findItemIndex(s);this.setSchedulePosition(t)}}advanceAssetBuffering(e,t){const i=e.event,s=i.findAssetIndex(t),r=Ja(i,s);if(i.isAssetPastPlayoutLimit(r)){if(this.schedule){var n;const t=null==(n=this.schedule.items)?void 0:n[this.findItemIndex(e)+1];t&&this.bufferedToItem(t)}}else this.bufferedToEvent(e,r)}advanceAfterAssetEnded(e,t,i){const s=Ja(e,i);if(e.isAssetPastPlayoutLimit(s)){if(this.schedule){const i=this.schedule.items;if(i){const s=t+1;if(s>=i.length)return void this.setSchedulePosition(-1);const r=e.resumeTime;this.timelinePos<r&&(this.log(no("advanceAfterAssetEnded",r)),this.timelinePos=r,e.appendInPlace&&this.advanceInPlace(r),this.checkBuffer(this.bufferedPos<r)),this.setSchedulePosition(s)}}}else{if(e.appendInPlace){const t=e.assetList[s];t&&this.advanceInPlace(t.timelineStart)}this.setSchedulePosition(t,s)}}setScheduleToAssetAtTime(e,t){const i=this.schedule;if(!i)return;const s=t.parentIdentifier,r=i.getEvent(s);if(r){const t=i.findEventIndex(s),n=i.findAssetIndex(r,e);this.advanceAfterAssetEnded(r,t,n-1)}}setSchedulePosition(e,t){var i;const s=null==(i=this.schedule)?void 0:i.items;if(!s||this.playbackDisabled)return;const r=e>=0?s[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${r?io(r):r}) pos: ${this.timelinePos}`);const n=this.waitingItem||this.playingItem,a=this.playingLastItem;if(this.isInterstitial(n)){const i=n.event,d=this.playingAsset,c=null==d?void 0:d.identifier,u=c?this.getAssetPlayer(c):null;if(u&&c&&(!this.eventItemsMatch(n,r)||void 0!==t&&c!==i.assetList[t].identifier)){var o;const t=i.findAssetIndex(d);if(this.log(`INTERSTITIAL_ASSET_ENDED ${t+1}/${i.assetList.length} ${Za(d)}`),this.endedAsset=d,this.playingAsset=null,this.hls.trigger(P.INTERSTITIAL_ASSET_ENDED,{asset:d,assetListIndex:t,event:i,schedule:s.slice(0),scheduleIndex:e,player:u}),n!==this.playingItem)return void(this.itemsMatch(n,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(i,this.findItemIndex(this.playingItem),t));this.retreiveMediaSource(c,r),!u.media||null!=(o=this.detachedData)&&o.mediaSource||u.detachMedia()}if(!this.eventItemsMatch(n,r)&&(this.endedItem=n,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${i} ${io(n)}`),i.hasPlayed=!0,this.hls.trigger(P.INTERSTITIAL_ENDED,{event:i,schedule:s.slice(0),scheduleIndex:e}),i.cue.once)){var l;this.updateSchedule();const e=null==(l=this.schedule)?void 0:l.items;if(r&&e){const i=this.findItemIndex(r);this.advanceSchedule(i,e,t,n,a)}return}}this.advanceSchedule(e,s,t,n,a)}advanceSchedule(e,t,i,s,r){const n=this.schedule;if(!n)return;const a=t[e]||null,o=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach(t=>{const i=t.interstitial,s=n.findEventIndex(i.identifier);(s<e||s>e+1)&&this.clearInterstitial(i,a)}),this.isInterstitial(a)){this.timelinePos=Math.min(Math.max(this.timelinePos,a.start),a.end);const r=a.event;if(void 0===i){const t=Ja(r,(i=n.findAssetIndex(r,this.timelinePos))-1);if(r.isAssetPastPlayoutLimit(t)||r.appendInPlace&&this.timelinePos===a.end)return void this.advanceAfterAssetEnded(r,e,i);i=t}const l=this.waitingItem;this.assetsBuffered(a,o)||this.setBufferingItem(a);let d=this.preloadAssets(r,i);if(this.eventItemsMatch(a,l||s)||(this.waitingItem=a,this.log(`INTERSTITIAL_STARTED ${io(a)} ${r.appendInPlace?"append in place":""}`),this.hls.trigger(P.INTERSTITIAL_STARTED,{event:r,schedule:t.slice(0),scheduleIndex:e})),!r.assetListLoaded)return void this.log(`Waiting for ASSET-LIST to complete loading ${r}`);if(r.assetListLoader&&(r.assetListLoader.destroy(),r.assetListLoader=void 0),!o)return void this.log(`Waiting for attachMedia to start Interstitial ${r}`);this.waitingItem=this.endedItem=null,this.playingItem=a;const c=r.assetList[i];if(!c)return void this.advanceAfterAssetEnded(r,e,i||0);if(d||(d=this.getAssetPlayer(c.identifier)),null===d||d.destroyed){const e=r.assetList.length;this.warn(`asset ${i+1}/${e} player destroyed ${r}`),d=this.createAssetPlayer(r,c,i),d.loadSource()}if(!this.eventItemsMatch(a,this.bufferingItem)&&r.appendInPlace&&this.isAssetBuffered(c))return;this.startAssetPlayer(d,i,t,e,o),this.shouldPlay&&ro(d.media)}else a?(this.resumePrimary(a,e,s),this.shouldPlay&&ro(this.hls.media)):r&&this.isInterstitial(s)&&(this.endedItem=null,this.playingItem=s,s.event.appendInPlace||this.attachPrimary(n.durations.primary,null))}get playbackDisabled(){return!1===this.hls.config.enableInterstitialPlayback}get primaryDetails(){var e;return null==(e=this.mediaSelection)?void 0:e.main.details}get primaryLive(){var e;return!(null==(e=this.primaryDetails)||!e.live)}resumePrimary(e,t,i){var s,r;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${io(e)}`),null==(s=this.detachedData)||!s.mediaSource){let i=this.timelinePos;(i<e.start||i>=e.end)&&(i=this.getPrimaryResumption(e,t),this.log(no("resumePrimary",i)),this.timelinePos=i),this.attachPrimary(i,e)}if(!i)return;const n=null==(r=this.schedule)?void 0:r.items;n&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${io(e)}`),this.hls.trigger(P.INTERSTITIALS_PRIMARY_RESUMED,{schedule:n.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const i=e.start;if(this.primaryLive){const e=this.primaryDetails;if(0===t)return this.hls.startPosition;if(e&&(i<e.fragmentStart||i>e.edge))return this.hls.liveSyncPosition||-1}return i}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);if(null!=t&&t.hls)return t.hls.bufferedToEnd;return yi.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,i){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const s=this.primaryMedia;if(!s)return;const r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,s),i&&this.startLoadingPrimaryAt(e,i)),i||(this.log(no("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,i))}startLoadingPrimaryAt(e,t){var i;const s=this.hls;!s.loadingEnabled||!s.media||Math.abs(((null==(i=s.mainForwardBufferInfo)?void 0:i.start)||s.media.currentTime)-e)>.5?s.startLoad(e,t):s.bufferingEnabled||s.resumeBuffering()}onManifestLoading(){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(P.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(P.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(-1===t.level||!this.schedule)return;const i=this.hls.levels[t.level];if(!i.details)return;const s=G(G({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=s,this.schedule.parseInterstitialDateRanges(s,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const i=this.hls.audioTracks[t.id],s=this.mediaSelection;if(!s)return void(this.altSelection=G(G({},this.altSelection),{},{audio:i}));const r=G(G({},s),{},{audio:i});this.mediaSelection=r}onSubtitleTrackUpdated(e,t){const i=this.hls.subtitleTracks[t.id],s=this.mediaSelection;if(!s)return void(this.altSelection=G(G({},this.altSelection),{},{subtitles:i}));const r=G(G({},s),{},{subtitles:i});this.mediaSelection=r}onAudioTrackSwitching(e,t){const i=At(t);this.playerQueue.forEach(({hls:e})=>e&&(e.setAudioOption(t)||e.setAudioOption(i)))}onSubtitleTrackSwitch(e,t){const i=At(t);this.playerQueue.forEach(({hls:e})=>e&&(e.setSubtitleOption(t)||-1!==t.id&&e.setSubtitleOption(i)))}onBufferCodecs(e,t){const i=t.tracks;i&&(this.requiredTracks=i)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){const e=this.timelinePos;this.bufferedPos=e,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let e=0;e<t.length;e++){const s=t[e];if(s.cue.post){var i;const e=this.schedule.findEventIndex(s.identifier),t=null==(i=this.schedule.items)?void 0:i[e];this.isInterstitial(t)&&this.eventItemsMatch(t,this.bufferingItem)&&this.bufferedToItem(t,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const e=this.findItemIndex(t);this.setSchedulePosition(e+1)}else this.shouldPlay=!1}updateItem(e,t){var i;const s=null==(i=this.schedule)?void 0:i.items;if(e&&s){return s[this.findItemIndex(e,t)]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((t,i)=>{e.event.isAssetPastPlayoutLimit(i)&&this.clearAssetPlayer(t.identifier,null)});const i=e.end+.25,s=yi.bufferInfo(this.primaryMedia,i,0);if(s.end>i||(s.nextStart||0)>i){this.log(`trim buffered interstitial ${io(e)} (was ${io(t)})`);const s=!0;this.attachPrimary(i,null,s),this.flushFrontBuffer(i)}}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var i;return!!t&&(e===t||e.event.identifier===(null==(i=t.event)?void 0:i.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;const i=this.mediaSelection;i&&(null==(t=this.schedule)||t.updateSchedule(i,[],e))}checkBuffer(e){var t;const i=null==(t=this.schedule)?void 0:t.items;if(!i)return;const s=yi.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=s.len<1),this.updateBufferedPos(s.end,i,e)}updateBufferedPos(e,t,i){const s=this.schedule,r=this.bufferingItem;if(this.bufferedPos>e||!s)return;if(1===t.length&&this.itemsMatch(t[0],r))return void(this.bufferedPos=e);const n=this.playingItem,a=this.findItemIndex(n);let o=s.findItemIndexAtTime(e);if(this.bufferedPos<e){var l;const i=this.findItemIndex(r),s=Math.min(i+1,t.length-1),n=t[s];if((-1===o&&r&&e>=r.end||null!=(l=n.event)&&l.appendInPlace&&e+.01>=n.start)&&(o=s),this.isInterstitial(r)){const e=r.event;if(s-a>1&&!1===e.appendInPlace)return;if(0===e.assetList.length&&e.assetListLoader)return}if(this.bufferedPos=e,o>i&&o>a)this.bufferedToItem(n);else{const t=this.primaryDetails;this.primaryLive&&t&&e>t.edge-t.targetduration&&n.start<t.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(n)&&this.preloadAssets(n.event,0)}}else i&&n&&!this.itemsMatch(n,r)&&(o===a?this.bufferedToItem(n):o===a+1&&this.bufferedToItem(t[o]))}assetsBuffered(e,t){return 0!==e.event.assetList.length&&!e.event.assetList.some(e=>{const i=this.getAssetPlayer(e.identifier);return!(null!=i&&i.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(e,t)&&i){const{items:s,events:r}=i;if(!s||!r)return t;const n=this.isInterstitial(e),a=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const o=a?a.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${io(e)}`+(t?` (${o.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(n){const t=i.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((e,i)=>{const s=this.getAssetPlayer(e.identifier);s&&(i===t&&s.loadSource(),s.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(e=>e.pauseBuffering());this.hls.trigger(P.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:s.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){const i=this.setBufferingItem(e);if(!this.playbackDisabled)if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(null!==i){this.bufferingAsset=null;const t=this.detachedData;if(t)if(t.mediaSource){const t=!0;this.attachPrimary(e.start,e,t)}else this.preloadPrimary(e);else this.preloadPrimary(e)}}preloadPrimary(e){const t=this.findItemIndex(e),i=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(i)}bufferedToEvent(e,t){const i=e.event,s=0===i.assetList.length&&!i.assetListLoader,r=i.cue.once;if(s||!r){const e=this.preloadAssets(i,t);if(null!=e&&e.interstitial.appendInPlace){const t=this.primaryMedia;t&&this.bufferAssetPlayer(e,t)}}}preloadAssets(e,t){const i=e.assetUrl,s=e.assetList.length,r=0===s&&!e.assetListLoader,n=e.cue.once;if(r){const r=e.timelineStart;if(e.appendInPlace){var a;const t=this.playingItem;this.isInterstitial(t)||(null==t||null==(a=t.nextEvent)?void 0:a.identifier)!==e.identifier||this.flushFrontBuffer(r+.25)}let n,o=0;if(!this.playingItem&&this.primaryLive&&(o=this.hls.startPosition,-1===o&&(o=this.hls.liveSyncPosition||0)),o&&!e.cue.pre&&!e.cue.post){const e=o-r;e>0&&(n=Math.round(1e3*e)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${i?1:s} ${e}${n?` live-start: ${o} start-offset: ${n}`:""}`),i)return this.createAsset(e,0,0,r,e.duration,i);const l=this.assetListLoader.loadAssetList(e,n);l&&(e.assetListLoader=l)}else if(!n&&s){for(let i=t;i<s;i++){const t=e.assetList[i],s=this.getAssetPlayerQueueIndex(t.identifier);-1!==s&&!this.playerQueue[s].destroyed||t.error||this.createAssetPlayer(e,t,i)}const i=e.assetList[t];if(i){const e=this.getAssetPlayer(i.identifier);return e&&e.loadSource(),e}}return null}flushFrontBuffer(e){const t=this.requiredTracks;if(!t)return;this.log(`Removing front buffer starting at ${e}`);Object.keys(t).forEach(t=>{this.hls.trigger(P.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:t})})}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let i=0;i<t.length;i++)if(e===t[i].assetId)return i;return-1}getAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){const{playerQueue:e,primaryMedia:t}=this;if(t)for(let i=0;i<e.length;i++)if(e[i].media===t)return e[i];return null}createAsset(e,t,i,s,r,n){const a={parentIdentifier:e.identifier,identifier:Ya(e,n,t),duration:r,startOffset:i,timelineStart:s,uri:n};return this.createAssetPlayer(e,a,t)}createAssetPlayer(e,t,i){const s=this.hls,r=s.userConfig;let n=r.videoPreference;const a=s.loadLevelObj||s.levels[s.currentLevel];(n||a)&&(n=$({},n),a.videoCodec&&(n.videoCodec=a.videoCodec),a.videoRange&&(n.allowedVideoRanges=[a.videoRange]));const o=s.audioTracks[s.audioTrack],l=s.subtitleTracks[s.subtitleTrack];let d=0;if(this.primaryLive||e.appendInPlace){const e=this.timelinePos-t.timelineStart;if(e>1){const i=t.duration;i&&e<i&&(d=e)}}const c=t.identifier,u=G(G({},r),{},{maxMaxBufferLength:Math.min(180,s.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:s.sessionId,assetPlayerId:c,abrEwmaDefaultEstimate:s.bandwidthEstimate,interstitialsController:void 0,startPosition:d,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:n,audioPreference:o||r.audioPreference,subtitlePreference:l||r.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(u.timelineOffset=t.timelineStart));const h=u.cmcd;null!=h&&h.sessionId&&h.contentId&&(u.cmcd=$({},h,{contentId:ja(t.uri)})),this.getAssetPlayer(c)&&this.warn(`Duplicate date range identifier ${e} and asset ${c}`);const f=new eo(this.HlsPlayerClass,u,e,t);this.playerQueue.push(f),e.assetList[i]=t;let g=!0;const p=s=>{if(s.live){var r;const t=new Error(`Interstitials MUST be VOD assets ${e}`),s={fatal:!0,type:k.OTHER_ERROR,details:w.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},n=(null==(r=this.schedule)?void 0:r.findEventIndex(e.identifier))||-1;return void this.handleAssetItemError(s,e,n,i,t.message)}const n=s.edge-s.fragmentStart,a=t.duration;(g||null===a||n>a)&&(g=!1,this.log(`Interstitial asset "${c}" duration change ${a} > ${n}`),t.duration=n,this.updateSchedule())};f.on(P.LEVEL_UPDATED,(e,{details:t})=>p(t)),f.on(P.LEVEL_PTS_UPDATED,(e,{details:t})=>p(t)),f.on(P.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const m=(e,t)=>{const i=this.getAssetPlayer(c);if(i&&t.tracks){i.off(P.BUFFER_CODECS,m),i.tracks=t.tracks;const e=this.primaryMedia;this.bufferingAsset===i.assetItem&&e&&!i.media&&this.bufferAssetPlayer(i,e)}};f.on(P.BUFFER_CODECS,m);f.on(P.BUFFERED_TO_END,()=>{var i;const s=this.getAssetPlayer(c);if(this.log(`buffered to end of asset ${s}`),!s||!this.schedule)return;const r=this.schedule.findEventIndex(e.identifier),n=null==(i=this.schedule.items)?void 0:i[r];this.isInterstitial(n)&&this.advanceAssetBuffering(n,t)});const v=t=>()=>{if(!this.getAssetPlayer(c)||!this.schedule)return;this.shouldPlay=!0;const i=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,i,t)};return f.once(P.MEDIA_ENDED,v(i)),f.once(P.PLAYOUT_LIMIT_REACHED,v(1/0)),f.on(P.ERROR,(t,s)=>{if(!this.schedule)return;const r=this.getAssetPlayer(c);if(s.details===w.BUFFER_STALLED_ERROR)return null!=r&&r.appendInPlace?void this.handleInPlaceStall(e):(this.onTimeupdate(),void this.checkBuffer(!0));this.handleAssetItemError(s,e,this.schedule.findEventIndex(e.identifier),i,`Asset player error ${s.error} ${e}`)}),f.on(P.DESTROYING,()=>{if(!this.getAssetPlayer(c)||!this.schedule)return;const t=new Error(`Asset player destroyed unexpectedly ${c}`),s={fatal:!0,type:k.OTHER_ERROR,details:w.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};this.handleAssetItemError(s,e,this.schedule.findEventIndex(e.identifier),i,t.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Za(t)}`),this.hls.trigger(P.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:f}),f}clearInterstitial(e,t){e.assetList.forEach(e=>{this.clearAssetPlayer(e.identifier,t)}),e.reset()}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(-1!==t){this.log(`reset asset player "${e}" after error`);const i=this.playerQueue[t];this.transferMediaFromPlayer(i,null),i.resetDetails()}}clearAssetPlayer(e,t){const i=this.getAssetPlayerQueueIndex(e);if(-1!==i){const e=this.playerQueue[i];this.log(`clear ${e} toSegment: ${t?io(t):t}`),this.transferMediaFromPlayer(e,t),this.playerQueue.splice(i,1),e.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,i,s,r){const{interstitial:n,assetItem:a,assetId:o}=e,l=n.assetList.length,d=this.playingAsset;this.endedAsset=null,this.playingAsset=a,d&&d.identifier===o||(d&&(this.clearAssetPlayer(d.identifier,i[s]),delete d.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${l} ${Za(a)}`),this.hls.trigger(P.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:t,event:n,schedule:i.slice(0),scheduleIndex:s,player:e})),this.bufferAssetPlayer(e,r)}bufferAssetPlayer(e,t){var i,s;if(!this.schedule)return;const{interstitial:r,assetItem:n}=e,a=this.schedule.findEventIndex(r.identifier),o=null==(i=this.schedule.items)?void 0:i[a];if(!o)return;e.loadSource(),this.setBufferingItem(o),this.bufferingAsset=n;const l=this.getBufferingPlayer();if(l===e)return;const d=r.appendInPlace;if(d&&!1===(null==l?void 0:l.interstitial.appendInPlace))return;const c=(null==l?void 0:l.tracks)||(null==(s=this.detachedData)?void 0:s.tracks)||this.requiredTracks;if(d&&n!==this.playingAsset){if(!e.tracks)return void this.log(`Waiting for track info before buffering ${e}`);if(c&&!Q(c,e.tracks)){const t=new Error(`Asset ${Za(n)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(c)}')`),i={fatal:!0,type:k.OTHER_ERROR,details:w.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},s=r.findAssetIndex(n);return void this.handleAssetItemError(i,r,a,s,t.message)}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,i=this.primaryMedia;if(!t||!i)return;const s=i.currentTime,r=t.findAssetIndex(e,s),n=e.assetList[r];if(n){const a=this.getAssetPlayer(n.identifier);if(a){const o=a.currentTime||s-n.timelineStart,l=a.duration-o;if(this.warn(`Stalled at ${o} of ${o+l} in ${a} ${e} (media.currentTime: ${s})`),o&&(l/i.playbackRate<.5||a.bufferedInPlaceToEnd(i))&&a.hls){const i=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,i,r)}}}}advanceInPlace(e){const t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,i,s,r){if(e.details===w.BUFFER_STALLED_ERROR)return;const n=t.assetList[s]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${n?Za(n):n} ${e.error}`),!this.schedule)return;const a=(null==n?void 0:n.identifier)||"",o=this.getAssetPlayerQueueIndex(a),l=this.playerQueue[o]||null,d=this.schedule.items,c=$({},e,{fatal:!1,errorAction:zt(!0),asset:n,assetListIndex:s,event:t,schedule:d,scheduleIndex:i,player:l});if(this.hls.trigger(P.INTERSTITIAL_ASSET_ERROR,c),!e.fatal)return;const u=this.playingAsset,h=this.bufferingAsset,f=new Error(r);if(n&&(this.clearAssetPlayer(a,null),n.error=f),t.assetList.some(e=>!e.error))for(let e=s;e<t.assetList.length;e++)this.resetAssetPlayer(t.assetList[e].identifier);else t.error=f;this.updateSchedule(!0),t.error?this.primaryFallback(t):u&&u.identifier===a?this.advanceAfterAssetEnded(t,i,s):h&&h.identifier===a&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,h)}primaryFallback(e){const t=e.timelineStart,i=this.effectivePlayingItem;if(i){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${this.timelinePos} playing: ${io(i)} error: ${e.error}`);let s=this.timelinePos;-1===s&&(s=this.hls.startPosition);const r=this.updateItem(i,s);if(this.itemsMatch(i,r)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t)),!this.schedule)return;const n=this.schedule.findItemIndexAtTime(s);this.setSchedulePosition(n)}else this.checkStart()}onAssetListLoaded(e,t){var i,s;const r=t.event,n=r.identifier,a=t.assetListResponse.ASSETS;if(null==(i=this.schedule)||!i.hasEvent(n))return;const o=r.timelineStart,l=r.duration;let d=0;a.forEach((e,t)=>{const i=parseFloat(e.DURATION);this.createAsset(r,t,d,o+d,i,e.URI),d+=i}),r.duration=d,this.log(`Loaded asset-list with duration: ${d} (was: ${l}) ${r}`);const c=this.waitingItem,u=(null==c?void 0:c.event.identifier)===n;this.updateSchedule();const h=null==(s=this.bufferingItem)?void 0:s.event;if(u){var f;const e=this.schedule.findEventIndex(n),t=null==(f=this.schedule.items)?void 0:f[e];if(t){if(!this.playingItem&&this.timelinePos>t.end){if(this.schedule.findItemIndexAtTime(this.timelinePos)!==e)return r.error=new Error(`Interstitial no longer within playback range ${this.timelinePos} ${r}`),this.updateSchedule(!0),void this.primaryFallback(r)}this.setBufferingItem(t)}this.setSchedulePosition(e)}else if((null==h?void 0:h.identifier)===n){const e=r.assetList[0];if(e){const t=this.getAssetPlayer(e.identifier);if(h.appendInPlace){const e=this.primaryMedia;t&&e&&this.bufferAssetPlayer(t,e)}else t&&t.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case w.ASSET_LIST_PARSING_ERROR:case w.ASSET_LIST_LOAD_ERROR:case w.ASSET_LIST_LOAD_TIMEOUT:{const e=t.interstitial;e&&(this.updateSchedule(!0),this.primaryFallback(e));break}case w.BUFFER_STALLED_ERROR:{const e=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(e)&&e.event.appendInPlace)return void this.handleInPlaceStall(e.event);this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}});function ul(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(ul):Object.keys(e).reduce((t,i)=>(t[i]=ul(e[i]),t),{}):e}function hl(e,t){const i=e.loader;if(i!==nl&&i!==dl)t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1;else{(function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1})()&&(e.loader=nl,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}}class fl extends pi{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var e;null!=(e=this.media)&&e.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{var e;this.hls&&(this.ended=(null==(e=this.media)?void 0:e.currentTime)||1,this.hls.trigger(P.MEDIA_ENDED,{stalled:!1}))},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(P.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(P.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(P.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(P.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(P.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(P.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(100),this.mediaSource=t.mediaSource;const i=this.media=t.media;Os(i,"playing",this.onMediaPlaying),Os(i,"waiting",this.onMediaWaiting),Os(i,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:i}=this;i&&(Fs(i,"playing",this.onMediaPlaying),Fs(i,"waiting",this.onMediaWaiting),Fs(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(null==(e=this.media)||!e.readyState||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var i,s;const r=null==(i=this.hls)?void 0:i.config;if(!r)return;const n=this.media;if(!n)return;const{seeking:a}=n,o=this.seeking&&!a,l=!this.seeking&&a,d=n.paused&&!a||n.ended||0===n.playbackRate;if(this.seeking=a,e!==t)return t&&(this.ended=0),this.moved=!0,a||(this.nudgeRetry=0,r.nudgeOnVideoHole&&!d&&e>t&&this.nudgeOnVideoHole(e,t)),void(0===this.waiting&&this.stallResolved(e));if(l||o)return void(o&&this.stallResolved(e));if(d)return this.nudgeRetry=0,this.stallResolved(e),void(!this.ended&&n.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(P.MEDIA_ENDED,{stalled:!1})));if(!yi.getBuffered(n).length)return void(this.nudgeRetry=0);const c=yi.bufferInfo(n,e,0),u=c.nextStart||0,h=this.fragmentTracker;if(a&&h&&this.hls){const t=gl(this.hls.inFlightFragments,e),i=c.len>2,s=!u||t||u-e>2&&!h.getPartialFragment(e);if(i||s)return;this.moved=!1}const f=null==(s=this.hls)?void 0:s.latestLevelDetails;if(!this.moved&&null!==this.stalled&&h){if(!(c.len>0)&&!u)return;const t=Math.max(u,c.start||0)-e,i=!(null==f||!f.live)?2*f.targetduration:2,s=ml(e,h);if(t>0&&(t<=i||s))return void(n.paused||this._trySkipBufferHole(s))}const g=r.detectStallWithCurrentTimeMs,p=self.performance.now(),m=this.waiting;let v=this.stalled;if(null===v){if(!(m>0&&p-m<g))return void(this.stalled=p);v=this.stalled=m}const y=p-v;if(!a&&(y>=g||m)&&this.hls){var T;if("ended"===(null==(T=this.mediaSource)?void 0:T.readyState)&&(null==f||!f.live)&&Math.abs(e-((null==f?void 0:f.edge)||0))<1){if(this.ended)return;return this.ended=e||1,void this.hls.trigger(P.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(c),!this.media||!this.hls)return}const E=yi.bufferInfo(n,e,r.maxBufferHole);this._tryFixBufferStall(E,y,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const i=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(i)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(P.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var i;const s=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(i=this.buffered.audio)&&i.length&&s&&s.length>1&&e>s.end(0)){const i=yi.bufferedInfo(yi.timeRangesToArray(this.buffered.audio),e,0);if(i.len>1&&t>=i.start){const i=yi.timeRangesToArray(s),r=yi.bufferedInfo(i,t,0).bufferedIndex;if(r>-1&&r<i.length-1){const t=yi.bufferedInfo(i,e,0).bufferedIndex,s=i[r].end,n=i[r+1].start;if((-1===t||t>r)&&n-s<1&&e-s<2){const i=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${s} -> ${n} buffered index: ${t}`);this.warn(i.message),this.media.currentTime+=1e-6;let r=ml(e,this.fragmentTracker);r&&"fragment"in r?r=r.fragment:r||(r=void 0);const a=yi.bufferInfo(this.media,e,0);this.hls.trigger(P.ERROR,{type:k.MEDIA_ERROR,details:w.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,frag:r,buffer:a.len,bufferInfo:a})}}}}}_tryFixBufferStall(e,t,i){var s,r;const{fragmentTracker:n,media:a}=this,o=null==(s=this.hls)?void 0:s.config;if(!a||!n||!o)return;const l=null==(r=this.hls)?void 0:r.latestLevelDetails,d=ml(i,n);if(d||null!=l&&l.live&&i<l.fragmentStart){if(this._trySkipBufferHole(d)||!this.media)return}const c=e.buffered,u=this.adjacentTraversal(e,i);(c&&c.length>1&&e.len>o.maxBufferHole||e.nextStart&&(e.nextStart-i<o.maxBufferHole||u))&&(t>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const i=this.fragmentTracker,s=e.nextStart;if(i&&s){const e=i.getFragAtPos(t,M),r=i.getFragAtPos(s,M);if(e&&r)return r.sn-e.sn<2}return!1}_reportStall(e){const{hls:t,media:i,stallReported:s,stalled:r}=this;if(!s&&null!==r&&i&&t){this.stallReported=!0;const s=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${Tt(e)})`);this.warn(s.message),t.trigger(P.ERROR,{type:k.MEDIA_ERROR,details:w.BUFFER_STALLED_ERROR,fatal:!1,error:s,buffer:e.len,bufferInfo:e,stalled:{start:r}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:i,media:s}=this,r=null==(t=this.hls)?void 0:t.config;if(!s||!i||!r)return 0;const n=s.currentTime,a=yi.bufferInfo(s,n,0),o=n<a.start?a.start:a.nextStart;if(o&&this.hls){const t=a.len<=r.maxBufferHole,d=a.len>0&&a.len<1&&s.readyState<3,c=o-n;if(c>0&&(t||d)){if(c>r.maxBufferHole){let t=!1;if(0===n){const e=i.getAppendedFrag(0,M);e&&o<e.end&&(t=!0)}if(!t&&e){var l;if(null==(l=this.hls.loadLevelObj)||!l.details)return 0;if(gl(this.hls.inFlightFragments,o))return 0;let t=!1,s=e.end;for(;s<o;){const e=ml(s,i);if(!e){t=!0;break}s+=e.duration}if(t)return 0}}const t=Math.max(o+.05,n+.1);if(this.warn(`skipping hole, adjusting currentTime from ${n} to ${t}`),this.moved=!0,s.currentTime=t,null==e||!e.gap){const i=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${t}`),s={type:k.MEDIA_ERROR,details:w.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,buffer:a.len,bufferInfo:a};e&&("fragment"in e?s.part=e:s.frag=e),this.hls.trigger(P.ERROR,s)}return t}}return 0}_tryNudgeBuffer(e){const{hls:t,media:i,nudgeRetry:s}=this,r=null==t?void 0:t.config;if(!i||!r)return 0;const n=i.currentTime;if(this.nudgeRetry++,s<r.nudgeMaxRetry){const a=n+(s+1)*r.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${n} to ${a}`);this.warn(o.message),i.currentTime=a,t.trigger(P.ERROR,{type:k.MEDIA_ERROR,details:w.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:e.len,bufferInfo:e})}else{const i=new Error(`Playhead still not moving while enough data buffered @${n} after ${r.nudgeMaxRetry} nudges`);this.error(i.message),t.trigger(P.ERROR,{type:k.MEDIA_ERROR,details:w.BUFFER_STALLED_ERROR,error:i,fatal:!0,buffer:e.len,bufferInfo:e})}}}function gl(e,t){const i=pl(e.main);if(i&&i.start<=t)return i;const s=pl(e.audio);return s&&s.start<=t?s:null}function pl(e){if(!e)return null;switch(e.state){case Bs:case Ns:case Ws:case qs:return null}return e.frag}function ml(e,t){return t.getAppendedFrag(e,M)||t.getPartialFragment(e)}function vl(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function yl(e,t,i,s,r){let n=new e(t,i,"");try{n.value=s,r&&(n.type=r)}catch(a){n=new e(t,i,Tt(r?G({type:r},s):s))}return n}const Tl=(()=>{const e=vl();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class El{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(P.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e&&(e.on(P.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(P.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(P.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(P.MANIFEST_LOADING,this.onManifestLoading,this),e.on(P.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(P.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(P.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(P.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(P.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(P.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(P.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(P.MANIFEST_LOADING,this.onManifestLoading,this),e.off(P.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(P.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(P.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(P.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var i;this.media=t.media,!1===(null==(i=t.overrides)?void 0:i.cueRemoval)&&(this.removeCues=!1)}onMediaAttached(){var e;const t=null==(e=this.hls)?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null;!!t.transferMedia||(this.id3Track&&(this.removeCues&&Ga(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const i=e[t];if("metadata"===i.kind&&"id3"===i.label)return $a(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:i,enableID3MetadataCues:s}=this.hls.config;if(!i&&!s)return;const{samples:r}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=vl();if(n)for(let e=0;e<r.length;e++){const t=r[e].type;if(t===Ir.emsg&&!i||!s)continue;const a=Ar(r[e].data),o=r[e].pts;let l=o+r[e].duration;l>Tl&&(l=Tl);l-o<=0&&(l=o+.25);for(let e=0;e<a.length;e++){const i=a[e];if(!br(i)){this.updateId3CueEnds(o,t);const e=yl(n,o,l,i,t);e&&this.id3Track.addCue(e)}}}}updateId3CueEnds(e,t){var i;const s=null==(i=this.id3Track)?void 0:i.cues;if(s)for(let i=s.length;i--;){const r=s[i];r.type===t&&r.startTime<e&&r.endTime===Tl&&(r.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:i,type:s}){const{id3Track:r,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=n;if(r&&(a||o)){let e;e="audio"===s?e=>e.type===Ir.audioId3&&o:"video"===s?e=>e.type===Ir.emsg&&a:e=>e.type===Ir.audioId3&&o||e.type===Ir.emsg&&a,Ha(r,t,i,e)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:i,timelineOffset:s,enableDateRangeMetadataCues:r,interstitialsController:n}=this.hls.config;if(!r)return;const a=vl();if(i&&s&&!n){const{fragmentStart:t,fragmentEnd:s}=e;let r=this.assetCue;r?(r.startTime=t,r.endTime=s):a&&(r=this.assetCue=yl(a,t,s,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),r&&(r.id=i,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(r),r.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:o}=this,{dateRanges:l}=e,d=Object.keys(l);let c=this.dateRangeCuesAppended;var u;if(o&&t)if(null!=(u=o.cues)&&u.length){const e=Object.keys(c).filter(e=>!d.includes(e));for(let t=e.length;t--;){var h;const i=e[t],s=null==(h=c[i])?void 0:h.cues;delete c[i],s&&Object.keys(s).forEach(e=>{const t=s[e];if(t){t.removeEventListener("enter",this.onEventCueEnter);try{o.removeCue(t)}catch(e){}}})}}else c=this.dateRangeCuesAppended={};const f=e.fragments[e.fragments.length-1];if(0!==d.length&&L(null==f?void 0:f.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let e=0;e<d.length;e++){const t=d[e],i=l[t],s=i.startTime,r=c[t],o=(null==r?void 0:r.cues)||{};let u=(null==r?void 0:r.durationKnown)||!1,h=Tl;const{duration:f,endDate:g}=i;if(g&&null!==f)h=s+f,u=!0;else if(i.endOnNext&&!u){const e=d.reduce((e,t)=>{if(t!==i.id){const s=l[t];if(s.class===i.class&&s.startDate>i.startDate&&(!e||i.startDate<e.startDate))return s}return e},null);e&&(h=e.startTime,u=!0)}const p=Object.keys(i.attr);for(let e=0;e<p.length;e++){const l=p[e];if(!ki(l))continue;const d=o[l];if(d)!u||null!=r&&r.durationKnown?Math.abs(d.startTime-s)>.01&&(d.startTime=s,d.endTime=h):d.endTime=h;else if(a){let e=i.attr[l];wi(l)&&(e=ee(e));const r=yl(a,s,h,{key:l,data:e},Ir.dateRange);r&&(r.id=t,this.id3Track.addCue(r),o[l]=r,n&&("X-ASSET-LIST"!==l&&"X-ASSET-URL"!==l||r.addEventListener("enter",this.onEventCueEnter)))}}c[t]={cues:o,dateRange:i,durationKnown:u}}}}}class Sl{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:e}=this,t=this.levelDetails;if(!e||!t)return;this.currentTime=e.currentTime;const i=this.computeLatency();if(null===i)return;this._latency=i;const{lowLatencyMode:s,maxLiveSyncPlaybackRate:r}=this.config;if(!s||1===r||!t.live)return;const n=this.targetLatency;if(null===n)return;const a=i-n;if(a<Math.min(this.maxLatency,n+t.targetduration)&&a>.05&&this.forwardBufferLength>1){const t=Math.min(2,Math.max(1,r)),i=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20,s=Math.min(t,Math.max(1,i));this.changeMediaPlaybackRate(e,s)}else 1!==e.playbackRate&&0!==e.playbackRate&&this.changeMediaPlaybackRate(e,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return(null==(e=this.hls)?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(void 0!==e.liveMaxLatencyDuration)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(null===e||null===this.hls)return null;const{holdBack:t,partHoldBack:i,targetduration:s}=e,{liveSyncDuration:r,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&i||t;(this._targetLatencyUpdated||o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==r?r:n*s);const d=s;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,d)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(null===e||null===t)return null;const i=this.levelDetails;if(null===i)return null;const s=i.edge,r=e-t-this.edgeStalled,n=s-i.totalduration,a=s-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(n,r),a)}get drift(){const e=this.levelDetails;return null===e?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(null===e)return 0;const t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(P.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(P.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(P.MANIFEST_LOADING,this.onManifestLoading,this),e.on(P.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(P.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(P.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(P.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(P.MANIFEST_LOADING,this.onManifestLoading,this),e.off(P.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(P.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var i;t.details===w.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(i=this.levelDetails)&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var i,s;e.playbackRate!==t&&(null==(i=this.hls)||i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${null==(s=this.targetLatency)?void 0:s.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return null===e?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return null===e?null:e-this.currentTime}}class Al extends Pn{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(P.MANIFEST_LOADING,this.onManifestLoading,this),e.on(P.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(P.LEVEL_LOADED,this.onLevelLoaded,this),e.on(P.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(P.FRAG_BUFFERED,this.onFragBuffered,this),e.on(P.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(P.MANIFEST_LOADING,this.onManifestLoading,this),e.off(P.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(P.LEVEL_LOADED,this.onLevelLoaded,this),e.off(P.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(P.FRAG_BUFFERED,this.onFragBuffered,this),e.off(P.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(e=>{e.loadError=0,e.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const i=this.hls.config.preferManagedMediaSource,s=[],r={},n={};let a=!1,o=!1,l=!1;t.levels.forEach(e=>{const t=e.attrs;let{audioCodec:d,videoCodec:c}=e;d&&(e.audioCodec=d=Xe(d,i)||void 0),c&&(c=e.videoCodec=function(e){const t=e.split(",");for(let e=0;e<t.length;e++){const i=t[e].split(".");i.length>2&&"avc1"===i[0]&&(t[e]=`avc1.${parseInt(i[1]).toString(16)}${("000"+parseInt(i[2]).toString(16)).slice(-4)}`)}return t.join(",")}(c));const{width:u,height:h,unknownCodecs:f}=e,g=(null==f?void 0:f.length)||0;if(a||(a=!(!u||!h)),o||(o=!!c),l||(l=!!d),g||d&&!this.isAudioSupported(d)||c&&!this.isVideoSupported(c))return void this.log(`Some or all CODECS not supported "${t.CODECS}"`);const{CODECS:p,"FRAME-RATE":m,"HDCP-LEVEL":v,"PATHWAY-ID":y,RESOLUTION:T,"VIDEO-RANGE":E}=t,S=`${`${y||"."}-`}${e.bitrate}-${T}-${m}-${p}-${E}-${v}`;if(r[S])if(r[S].uri===e.url||e.attrs["PATHWAY-ID"])r[S].addGroupId("audio",t.AUDIO),r[S].addGroupId("text",t.SUBTITLES);else{const t=n[S]+=1;e.attrs["PATHWAY-ID"]=new Array(t+1).join(".");const i=this.createLevel(e);r[S]=i,s.push(i)}else{const t=this.createLevel(e);r[S]=t,n[S]=1,s.push(t)}}),this.filterAndSortMediaOptions(s,t,a,o,l)}createLevel(e){const t=new mt(e),i=e.supplemental;if(null!=i&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){const e=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(e.message),t.supportedResult=rt(e,[])}return t}isAudioSupported(e){return He(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return He(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,i,s,r){var n;let a=[],o=[],l=e;const d=(null==(n=t.stats)?void 0:n.parsing)||{};if((i||s)&&r&&(l=l.filter(({videoCodec:e,videoRange:t,width:i,height:s})=>{return(!!e||!(!i||!s))&&(!!(r=t)&&ct.indexOf(r)>-1);var r})),0===l.length)return Promise.resolve().then(()=>{if(this.hls){let e="no level with compatible codecs found in manifest",i=e;t.levels.length&&(i=`one or more CODECS in variant not supported: ${Tt(t.levels.map(e=>e.attrs.CODECS).filter((e,t,i)=>i.indexOf(e)===t))}`,this.warn(i),e+=` (${i})`);const s=new Error(e);this.hls.trigger(P.ERROR,{type:k.MEDIA_ERROR,details:w.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:s,reason:i})}}),void(d.end=performance.now());t.audioTracks&&(a=t.audioTracks.filter(e=>!e.audioCodec||this.isAudioSupported(e.audioCodec)),bl(a)),t.subtitles&&(o=t.subtitles,bl(o));const c=l.slice(0);l.sort((e,t)=>{if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return ct.indexOf(e.videoRange)-ct.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){const i=We(e.videoCodec),s=We(t.videoCodec);if(i!==s)return s-i}if(e.uri===t.uri&&e.codecSet!==t.codecSet){const i=qe(e.codecSet),s=qe(t.codecSet);if(i!==s)return s-i}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0});let u=c[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==c.length))for(let e=0;e<c.length;e++)if(c[e].pathwayId===l[0].pathwayId){u=c[e];break}this._levels=l;for(let e=0;e<l.length;e++)if(l[e]===u){var h;this._firstLevel=e;const t=u.bitrate,i=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${t}`),void 0===(null==(h=this.hls.userConfig)?void 0:h.abrEwmaDefaultEstimate)){const e=Math.min(t,this.hls.config.abrEwmaDefaultEstimateMax);e>i&&i===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=e)}break}const f=r&&!s,g=this.hls.config,p=!(!g.audioStreamController||!g.audioTrackController),m={levels:l,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:s,altAudio:p&&!f&&a.some(e=>!!e.url)};d.end=performance.now(),this.hls.trigger(P.MANIFEST_PARSED,m)}get levels(){return 0===this._levels.length?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(0===t.length)return;if(e<0||e>=t.length){const i=new Error("invalid level idx"),s=e<0;if(this.hls.trigger(P.ERROR,{type:k.OTHER_ERROR,details:w.LEVEL_SWITCH_ERROR,level:e,fatal:s,error:i,reason:i.message}),s)return;e=Math.min(e,t.length-1)}const i=this.currentLevelIndex,s=this.currentLevel,r=s?s.attrs["PATHWAY-ID"]:void 0,n=t[e],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=n,i===e&&s&&r===a)return;this.log(`Switching to level ${e} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${a?" with Pathway "+a:""} from level ${i}${r?" with Pathway "+r:""}`);const o={level:e,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(P.LEVEL_SWITCHING,o);const l=n.details;if(!l||l.live){const e=this.switchParams(n.uri,null==s?void 0:s.details,l);this.loadPlaylist(e)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(void 0===this._startLevel){const e=this.hls.config.startLevel;return void 0!==e?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),i=e.filter(e=>-1!==t.indexOf(e));if(e.length<1)return void this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);this.steering.pathwayPriority=i}}onError(e,t){!t.fatal&&t.context&&t.context.type===x&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(void 0!==t&&t.type===M){const e=t.elementaryStreams;if(!Object.keys(e).some(t=>!!e[t]))return;const i=this._levels[t.level];null!=i&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(e,t){var i;const{level:s,details:r}=t,n=t.levelInfo;var a;if(!n)return this.warn(`Invalid level index ${s}`),void(null!=(a=t.deliveryDirectives)&&a.skip&&(r.deltaUpdateFailed=!0));if(n===this.currentLevel||t.withoutMultiVariant){0===n.fragmentError&&(n.loadError=0);let e=n.details;e===t.details&&e.advanced&&(e=void 0),this.playlistLoaded(s,t,e)}else null!=(i=t.deliveryDirectives)&&i.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=this.getUrlWithDirectives(e.uri,t),s=this.currentLevelIndex,r=e.attrs["PATHWAY-ID"],n=e.details,a=null==n?void 0:n.age;this.log(`Loading level index ${s}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${r?" Pathway "+r:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${i}`),this.hls.trigger(P.LEVEL_LOADING,{url:i,level:s,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(1===this._levels.length)return;const i=this._levels.filter((t,i)=>i!==e||(this.steering&&this.steering.removeLevel(t),t===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,t.details&&t.details.fragments.forEach(e=>e.level=-1)),!1));ks(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);const s=i.length-1;this._firstLevel=Math.min(this._firstLevel,s),this._startLevel&&(this._startLevel=Math.min(this._startLevel,s)),this.hls.trigger(P.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(P.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function bl(e){const t={};e.forEach(e=>{const i=e.groupId||"";e.id=t[i]=t[i]||0,t[i]++})}function Ll(){return self.SourceBuffer||self.WebKitSourceBuffer}function Rl(){if(!X())return!1;const e=Ll();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}class Il extends Xs{constructor(e,t,i){super(e,t,i,"stream-controller",M),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const e=this.media,t=e?e.currentTime:null;if(null===t||!L(t))return;if(this.log(`Media seeked to ${t.toFixed(3)}`),!this.getBufferedFrag(t))return;const i=this.getFwdBufferInfoAtPos(e,t,M,0);null!==i&&0!==i.len?this.tick():this.warn(`Main forward buffer length at ${t} on "seeked" event ${i?i.len:"empty"})`)},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(P.MANIFEST_PARSED,this.onManifestParsed,this),e.on(P.LEVEL_LOADING,this.onLevelLoading,this),e.on(P.LEVEL_LOADED,this.onLevelLoaded,this),e.on(P.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(P.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(P.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(P.BUFFER_CREATED,this.onBufferCreated,this),e.on(P.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(P.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(P.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(P.MANIFEST_PARSED,this.onManifestParsed,this),e.off(P.LEVEL_LOADED,this.onLevelLoaded,this),e.off(P.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(P.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(P.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(P.BUFFER_CREATED,this.onBufferCreated,this),e.off(P.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(P.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(P.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:i,hls:s}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let e=s.startLevel;-1===e&&(s.config.testBandwidth&&this.levels.length>1?(e=0,this.bitrateTest=!0):e=s.firstAutoLevel),s.nextLoadLevel=e,this.level=s.loadLevel,this._hasEnoughToStart=!!t}i>0&&-1===e&&!t&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i),this.state=Bs,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=Ns}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case zs:{const{levels:e,level:t}=this,i=null==e?void 0:e[t],s=null==i?void 0:i.details;if(s&&(!s.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(s))break;this.state=Bs;break}if(this.hls.nextLoadLevel!==this.level){this.state=Bs;break}break}case Gs:this.checkRetryDate()}this.state===Bs&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),null!=(e=this.media)&&e.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:i,media:s}=this;if(null===t||!s&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const r=this.buffering?e.nextLoadLevel:e.loadLevel;if(null==i||!i[r])return;const n=i[r],a=this.getMainFwdBufferInfo();if(null===a)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const e={};return 2===this.altAudio&&(e.type="video"),this.hls.trigger(P.BUFFER_EOS,e),void(this.state=Ws)}if(!this.buffering)return;e.loadLevel!==r&&-1===e.manualLevel&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=e.nextLoadLevel=r;const l=n.details;if(!l||this.state===zs||this.waitForLive(n))return this.level=r,this.state=zs,void(this.startFragRequested=!1);const d=a.len,c=this.getMaxBufferLength(n.maxBitrate);if(d>=c)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const u=this.backtrackFragment?this.backtrackFragment.start:a.end;let h=this.getNextFragment(u,l);if(this.couldBacktrack&&!this.fragPrevious&&h&&ce(h)&&this.fragmentTracker.getState(h)!==Zt){var f;const e=(null!=(f=this.backtrackFragment)?f:h).sn-l.startSN,t=l.fragments[e-1];t&&h.cc===t.cc&&(h=t,this.fragmentTracker.removeFragment(t))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(h&&this.isLoopLoading(h,u)){if(!h.gap){const e=this.audioOnly&&!this.altAudio?ae:oe,t=(e===oe?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e,M)}h=this.getNextFragmentLoopLoading(h,l,a,M,c)}h&&(!h.initSegment||h.initSegment.data||this.bitrateTest||(h=h.initSegment),this.loadFragment(h,n,u))}loadFragment(e,t,i){const s=this.fragmentTracker.getState(e);s===Xt||s===Jt?ce(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,i):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,M)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(null!=t&&t.readyState){let i;const s=this.getAppendedFrag(t.currentTime);s&&s.start>1&&this.flushMainBuffer(0,s.start-1);const r=this.getLevelDetails();if(null!=r&&r.live){const e=this.getMainFwdBufferInfo();if(!e||e.len<2*r.targetduration)return}if(!t.paused&&e){const t=e[this.hls.nextLoadLevel],s=this.fragLastKbps;i=s&&this.fragCurrent?this.fragCurrent.duration*t.maxBitrate/(1e3*s)+1:0}else i=0;const n=this.getBufferedFrag(t.currentTime+i);if(n){const e=this.followingBufferedFrag(n);if(e){this.abortCurrentFrag();const t=e.maxStartPTS?e.maxStartPTS:e.start,i=e.duration,s=Math.max(n.end,t+Math.min(Math.max(i-this.config.maxFragLookUpTolerance,i*(this.couldBacktrack?.5:.125)),i*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(s,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case $s:case Vs:case Gs:case Ks:case js:this.state=Bs}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,2===this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const i=t.media;Os(i,"playing",this.onMediaPlaying),Os(i,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:i}=this;i&&(Fs(i,"playing",this.onMediaPlaying),Fs(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t);!!t.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(P.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let i=!1,s=!1;for(let e=0;e<t.levels.length;e++){const r=t.levels[e].audioCodec;r&&(i=i||-1!==r.indexOf("mp4a.40.2"),s=s||-1!==r.indexOf("mp4a.40.5"))}this.audioCodecSwitch=i&&s&&!function(){var e;const t=Ll();return"function"==typeof(null==t||null==(e=t.prototype)?void 0:e.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:i}=this;if(!i||this.state!==Bs)return;const s=t.levelInfo;(!s.details||s.details.live&&(this.levelLastLoaded!==s||s.details.expired)||this.waitForCdnTuneIn(s.details))&&(this.state=zs)}onLevelLoaded(e,t){var i;const{levels:s,startFragRequested:r}=this,n=t.level,a=t.details,o=a.totalduration;if(!s)return void this.warn(`Levels were reset while loading level ${n}`);this.log(`Level ${n} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=t.levelInfo,d=this.fragCurrent;!d||this.state!==Vs&&this.state!==Gs||d.level!==t.level&&d.loader&&this.abortCurrentFrag();let c=0;if(a.live||null!=(i=l.details)&&i.live){var u;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;c=this.alignPlaylists(a,l.details,null==(u=this.levelLastLoaded)?void 0:u.details)}if(l.details=a,this.levelLastLoaded=l,r||this.setStartPosition(a,c),this.hls.trigger(P.LEVEL_UPDATED,{details:a,level:n}),this.state===zs){if(this.waitForCdnTuneIn(a))return;this.state=Bs}r&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:i}=this;if(!i)return;const s=this.hls.liveSyncPosition,r=this.getLoadPosition(),n=e.fragmentStart,a=e.edge,o=r>=n-t.maxFragLookUpTolerance&&r<=a;if(null!==s&&i.duration>s&&(r<s||!o)){const n=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!o&&i.readyState<4||r<a-n)&&(this._hasEnoughToStart||(this.nextLoadPosition=s),i.readyState))if(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${s.toFixed(3)}`),"buffered"===this.config.liveSyncMode){var l;const e=yi.bufferInfo(i,s,0);if(null==(l=e.buffered)||!l.length)return void(i.currentTime=s);if(e.start<=r)return void(i.currentTime=s);const{nextStart:t}=yi.bufferedInfo(e.buffered,r,0);t&&(i.currentTime=t)}else i.currentTime=s}}_handleFragmentLoadProgress(e){var t;const i=e.frag,{part:s,payload:r}=e,{levels:n}=this;if(!n)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);const a=n[i.level];if(!a)return void this.warn(`Level ${i.level} not found on progress`);const o=a.details;if(!o)return this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),void this.fragmentTracker.removeFragment(i);const l=a.videoCodec,d=o.PTSKnown||!o.live,c=null==(t=i.initSegment)?void 0:t.data,u=this._getAudioCodec(a),h=this.transmuxer=this.transmuxer||new wn(this.hls,M,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=s?s.index:-1,g=-1!==f,p=new mi(i.level,i.sn,i.stats.chunkCount,r.byteLength,f,g),m=this.initPTS[i.cc];h.push(r,c,u,l,i,s,o.totalduration,d,p,m)}onAudioTrackSwitching(e,t){const i=this.hls,s=2===this.altAudio;if(kt(t.url,i))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const e=this.fragCurrent;e&&(this.log("Switching to main audio track, cancel main fragment load"),e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(s)return this.fragmentTracker.removeAllFragments(),i.once(P.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(P.AUDIO_TRACK_SWITCHED,t)}),void i.trigger(P.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});i.trigger(P.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const i=kt(t.url,this.hls);if(i){const e=this.videoBuffer;e&&this.mediaBuffer!==e&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=e)}this.altAudio=i?2:0,this.tick()}onBufferCreated(e,t){const i=t.tracks;let s,r,n=!1;for(const e in i){const t=i[e];if("main"===t.id){if(r=e,s=t,"video"===e){const t=i[e];t&&(this.videoBuffer=t.buffer)}}else n=!0}n&&s?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=s.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:i,part:s}=t,r=i.type===M;if(r){if(this.fragContextChanged(i))return this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===js&&(this.state=Bs));const e=s?s.stats:i.stats;this.fragLastKbps=Math.round(8*e.total/(e.buffering.end-e.loading.first)),ce(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,s)}const n=this.media;n&&(!this._hasEnoughToStart&&yi.getBuffered(n).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var i;if(t.fatal)this.state=qs;else switch(t.details){case w.FRAG_GAP:case w.FRAG_PARSING_ERROR:case w.FRAG_DECRYPT_ERROR:case w.FRAG_LOAD_ERROR:case w.FRAG_LOAD_TIMEOUT:case w.KEY_LOAD_ERROR:case w.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(M,t);break;case w.LEVEL_LOAD_ERROR:case w.LEVEL_LOAD_TIMEOUT:case w.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==zs||(null==(i=t.context)?void 0:i.type)!==x||(this.state=Bs);break;case w.BUFFER_ADD_CODEC_ERROR:case w.BUFFER_APPEND_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case w.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 w.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onFragLoadEmergencyAborted(){this.state=Bs,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==ae||!this.altAudio){const e=(t===oe?this.videoBuffer:this.mediaBuffer)||this.media;e&&(this.afterBufferFlushed(e,t,M),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let i=this.startPosition;if(i>=0&&t<i){if(e.seeking)return void this.log(`could not seek to ${i}, already seeking at ${t}`);const s=this.timelineOffset;s&&i&&(i+=s);const r=this.getLevelDetails(),n=yi.getBuffered(e),a=n.length?n.start(0):0,o=a-i,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*((null==r?void 0:r.partTarget)||0)))&&(this.log(`adjusting start position by ${o} to match buffer start`),i+=o,this.startPosition=i),t<i&&(this.log(`seek to target start position ${i} from current time ${t} buffer start ${a}`),e.currentTime=i)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(e=>{const{hls:i}=this,s=null==e?void 0:e.frag;if(!s||this.fragContextChanged(s))return;t.fragmentError=0,this.state=Bs,this.startFragRequested=!1,this.bitrateTest=!1;const r=s.stats;r.parsing.start=r.parsing.end=r.buffering.start=r.buffering.end=self.performance.now(),i.trigger(P.FRAG_LOADED,e),s.bitrateTest=!1}).catch(t=>{this.state!==Ns&&this.state!==qs&&(this.warn(t),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:i}=this,{remuxResult:s,chunkMeta:r}=e,n=this.getCurrentContext(r);if(!n)return void this.resetWhenMissingContext(r);const{frag:a,part:o,level:l}=n,{video:d,text:c,id3:u,initSegment:h}=s,{details:f}=l,g=this.altAudio?void 0:s.audio;if(this.fragContextChanged(a))this.fragmentTracker.removeFragment(a);else{if(this.state=Ks,h){const e=h.tracks;if(e){const s=a.initSegment||a;if(this.unhandledEncryptionError(h,a))return;this._bufferInitSegment(l,e,s,r),i.trigger(P.FRAG_PARSING_INIT_SEGMENT,{frag:s,id:t,tracks:e})}const s=h.initPTS,n=h.timescale,o=this.initPTS[a.cc];if(L(s)&&(!o||o.baseTime!==s||o.timescale!==n)){const e=h.trackId;this.initPTS[a.cc]={baseTime:s,timescale:n,trackId:e},i.trigger(P.INIT_PTS_FOUND,{frag:a,id:t,initPTS:s,timescale:n,trackId:e})}}if(d&&f){g&&"audiovideo"===d.type&&this.logMuxedErr(a);const e=f.fragments[a.sn-1-f.startSN],t=a.sn===f.startSN,i=!e||a.cc>e.cc;if(!1!==s.independent){const{startPTS:e,endPTS:s,startDTS:n,endDTS:l}=d;if(o)o.elementaryStreams[d.type]={startPTS:e,endPTS:s,startDTS:n,endDTS:l};else if(d.firstKeyFrame&&d.independent&&1===r.id&&!i&&(this.couldBacktrack=!0),d.dropped&&d.independent){const r=this.getMainFwdBufferInfo(),n=(r?r.end:this.getLoadPosition())+this.config.maxBufferHole,o=d.firstKeyFramePTS?d.firstKeyFramePTS:e;if(!t&&n<o-this.config.maxBufferHole&&!i)return void this.backtrack(a);i&&(a.gap=!0),a.setElementaryStreamInfo(d.type,a.start,s,a.start,l,!0)}else t&&e-(f.appliedTimelineOffset||0)>2&&(a.gap=!0);a.setElementaryStreamInfo(d.type,e,s,n,l),this.backtrackFragment&&(this.backtrackFragment=a),this.bufferFragmentData(d,a,o,r,t||i)}else{if(!t&&!i)return void this.backtrack(a);a.gap=!0}}if(g){const{startPTS:e,endPTS:t,startDTS:i,endDTS:s}=g;o&&(o.elementaryStreams[ae]={startPTS:e,endPTS:t,startDTS:i,endDTS:s}),a.setElementaryStreamInfo(ae,e,t,i,s),this.bufferFragmentData(g,a,o,r)}if(f&&null!=u&&u.samples.length){const e={id:t,frag:a,details:f,samples:u.samples};i.trigger(P.FRAG_PARSING_METADATA,e)}if(f&&c){const e={id:t,frag:a,details:f,samples:c.samples};i.trigger(P.FRAG_PARSING_USERDATA,e)}}}logMuxedErr(e){this.warn(`${ce(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,i,s){if(this.state!==Ks)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));const{audio:r,video:n,audiovideo:a}=t;if(r){const i=e.audioCodec;let s=Qe(r.codec,i);"mp4a"===s&&(s="mp4a.40.5");const n=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){s&&(s=-1!==s.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const e=r.metadata;e&&"channelCount"in e&&1!==(e.channelCount||1)&&-1===n.indexOf("firefox")&&(s="mp4a.40.5")}s&&-1!==s.indexOf("mp4a.40.5")&&-1!==n.indexOf("android")&&"audio/mpeg"!==r.container&&(s="mp4a.40.2",this.log(`Android: force audio codec to ${s}`)),i&&i!==s&&this.log(`Swapping manifest audio codec "${i}" for "${s}"`),r.levelCodec=s,r.id=M,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${s||""}/${i||""}/${r.codec}]`),delete t.audiovideo}if(n){n.levelCodec=e.videoCodec,n.id=M;const i=n.codec;if(4===(null==i?void 0:i.length))switch(i){case"hvc1":case"hev1":n.codec="hvc1.1.6.L120.90";break;case"av01":n.codec="av01.0.04M.08";break;case"avc1":n.codec="avc1.42e01e"}this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${e.videoCodec||""}/${i}]${n.codec!==i?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete t.audiovideo}a&&(this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${e.codecs}/${a.codec}]`),delete t.video,delete t.audio);const o=Object.keys(t);if(o.length){if(this.hls.trigger(P.BUFFER_CODECS,t),!this.hls)return;o.forEach(e=>{const r=t[e].initSegment;null!=r&&r.byteLength&&this.hls.trigger(P.BUFFER_APPENDING,{type:e,data:r,frag:i,part:null,chunkMeta:s,parent:i.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,M)}get maxBufferLength(){const{levels:e,level:t}=this,i=null==e?void 0:e[t];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=Bs}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&!1===e.seeking){const i=e.currentTime;if(yi.isBuffered(e,i)?t=this.getAppendedFrag(i):yi.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;const e=this.fragPlaying,i=t.level;e&&t.sn===e.sn&&e.level===i||(this.fragPlaying=t,this.hls.trigger(P.FRAG_CHANGED,{frag:t}),e&&e.level===i||this.hls.trigger(P.LEVEL_SWITCHED,{level:i}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;return L(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if(L(t)){const e=this.getLevelDetails(),i=this.currentFrag||(e?Pt(null,e.fragments,t):null);if(i){const e=i.programDateTime;if(null!==e){const s=e+1e3*(t-i.start);return new Date(s)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class kl extends H{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const i in this.keyIdToKeyInfo){const s=this.keyIdToKeyInfo[i].loader;if(s){var t;if(e&&e!==(null==(t=s.context)?void 0:t.frag.type))return;s.abort()}}}detach(){for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=w.KEY_LOAD_ERROR,i,s,r){return new gi({type:k.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:i,networkDetails:s})}loadClear(e,t,i){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let s=0,r=t.length;s<r;s++){const n=t[s];if(e.cc<=n.cc&&(!ce(e)||!ce(n)||e.sn<n.sn)||!i&&s==r-1)return this.emeController.selectKeySystemFormat(n).then(e=>{if(!this.emeController)return;n.setKeyFormat(e);const t=ji(e);return t?this.emeController.getKeySystemAccess([t]):void 0})}if(this.config.requireKeySystemAccessOnStart){const e=qi(this.config);if(e.length)return this.emeController.getKeySystemAccess(e)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var i,s;t&&e.setKeyFormat(t);const r=e.decryptdata;if(!r){const i=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,w.KEY_LOAD_ERROR,i))}const n=r.uri;if(!n)return Promise.reject(this.createKeyLoadError(e,w.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));const a=wl(r);let o=this.keyIdToKeyInfo[a];if(null!=(i=o)&&i.decryptdata.key)return r.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});if(this.emeController&&null!=(s=o)&&s.keyLoadPromise){switch(this.emeController.getKeyStatus(o.decryptdata)){case"usable":case"usable-in-future":return o.keyLoadPromise.then(t=>{const{keyInfo:i}=t;return r.key=i.decryptdata.key,{frag:e,keyInfo:i}})}}switch(this.log(`${this.keyIdToKeyInfo[a]?"Rel":"L"}oading${r.keyId?" keyId: "+Z(r.keyId):""} URI: ${r.uri} from ${e.type} ${e.level}`),o=this.keyIdToKeyInfo[a]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===r.keyFormat?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,w.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e,t){const i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var s;if(!e.decryptdata.keyId&&null!=(s=t.initSegment)&&s.data){const i=function(e){const t=[];return De(e,e=>t.push(e.subarray(8,24))),t}(t.initSegment.data);if(i.length){const t=i[0];t.some(e=>0!==e)&&(this.log(`Using keyId found in init segment ${Z(t)}`),e.decryptdata.keyId=t,Ji.setKeyIdForUri(e.decryptdata.uri,t))}}const r=this.emeController.loadKey(i);return(e.keyLoadPromise=r.then(t=>(e.mediaKeySessionContext=t,i))).catch(i=>{throw e.keyLoadPromise=null,"data"in i&&(i.data.frag=t),i})}return Promise.resolve(i)}loadKeyHTTP(e,t){const i=this.config,s=new(0,i.loader)(i);return t.keyLoader=e.loader=s,e.keyLoadPromise=new Promise((r,n)=>{const a={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},o=i.keyLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(e,t,i,s)=>{const{frag:a,keyInfo:o}=i,l=wl(o.decryptdata);if(!a.decryptdata||o!==this.keyIdToKeyInfo[l])return n(this.createKeyLoadError(a,w.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),s));o.decryptdata.key=a.decryptdata.key=new Uint8Array(e.data),a.keyLoader=null,o.loader=null,r({frag:a,keyInfo:o})},onError:(e,i,s,r)=>{this.resetLoader(i),n(this.createKeyLoadError(t,w.KEY_LOAD_ERROR,new Error(`HTTP Error ${e.code} loading key ${e.text}`),s,G({url:a.url,data:void 0},e)))},onTimeout:(e,i,s)=>{this.resetLoader(i),n(this.createKeyLoadError(t,w.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),s))},onAbort:(e,i,s)=>{this.resetLoader(i),n(this.createKeyLoadError(t,w.INTERNAL_ABORTED,new Error("key loading aborted"),s))}};s.load(a,l,d)})}resetLoader(e){const{frag:t,keyInfo:i,url:s}=e,r=i.loader;t.keyLoader===r&&(t.keyLoader=null,i.loader=null);const n=wl(i.decryptdata)||s;delete this.keyIdToKeyInfo[n],r&&r.destroy()}}function wl(e){if(e.keyFormat!==Gi){const t=e.keyId;if(t)return Z(t)}return e.uri}function Pl(e){const{type:t}=e;switch(t){case C:return O;case _:return F;default:return M}}function Dl(e,t){let i=e.url;return void 0!==i&&0!==i.indexOf("data:")||(i=t.url),i}class xl{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(P.MANIFEST_LOADING,this.onManifestLoading,this),e.on(P.LEVEL_LOADING,this.onLevelLoading,this),e.on(P.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(P.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(P.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(P.MANIFEST_LOADING,this.onManifestLoading,this),e.off(P.LEVEL_LOADING,this.onLevelLoading,this),e.off(P.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(P.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(P.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,i=t.pLoader,s=t.loader,r=new(i||s)(t);return this.loaders[e.type]=r,r}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:D,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:i,level:s,pathwayId:r,url:n,deliveryDirectives:a,levelInfo:o}=t;this.load({id:i,level:s,pathwayId:r,responseType:"text",type:x,url:n,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(e,t){const{id:i,groupId:s,url:r,deliveryDirectives:n,track:a}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:C,url:r,deliveryDirectives:n,levelOrTrack:a})}onSubtitleTrackLoading(e,t){const{id:i,groupId:s,url:r,deliveryDirectives:n,track:a}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:_,url:r,deliveryDirectives:n,levelOrTrack:a})}onLevelsUpdated(e,t){const i=this.loaders[x];if(i){const e=i.context;e&&!t.levels.some(t=>t===e.levelOrTrack)&&(i.abort(),delete this.loaders[x])}}load(e){var t;const i=this.hls.config;let s,r=this.getInternalLoader(e);if(r){const t=this.hls.logger,i=r.context;if(i&&i.levelOrTrack===e.levelOrTrack&&(i.url===e.url||i.deliveryDirectives&&!e.deliveryDirectives))return void(i.url===e.url?t.log(`[playlist-loader]: ignore ${e.url} ongoing request`):t.log(`[playlist-loader]: ignore ${e.url} in favor of ${i.url}`));t.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),r.abort()}if(s=e.type===D?i.manifestLoadPolicy.default:$({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(e),L(null==(t=e.deliveryDirectives)?void 0:t.part)){let t;if(e.type===x&&null!==e.level?t=this.hls.levels[e.level].details:e.type===C&&null!==e.id?t=this.hls.audioTracks[e.id].details:e.type===_&&null!==e.id&&(t=this.hls.subtitleTracks[e.id].details),t){const e=t.partTarget,i=t.targetduration;if(e&&i){const t=1e3*Math.max(3*e,.8*i);s=$({},s,{maxTimeToFirstByteMs:Math.min(t,s.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,s.maxTimeToFirstByteMs)})}}}const n=s.errorRetry||s.timeoutRetry||{},a={loadPolicy:s,timeout:s.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},o={onSuccess:(e,t,i,s)=>{const r=this.getInternalLoader(i);this.resetInternalLoader(i.type);const n=e.data;t.parsing.start=performance.now(),ns.isMediaPlaylist(n)||i.type!==D?this.handleTrackOrLevelPlaylist(e,t,i,s||null,r):this.handleMasterPlaylist(e,t,i,s)},onError:(e,t,i,s)=>{this.handleNetworkError(t,i,!1,e,s)},onTimeout:(e,t,i)=>{this.handleNetworkError(t,i,!0,void 0,e)}};r.load(e,a,o)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:i}=this.hls;(e||i)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,i,s){const r=this.hls,n=e.data,a=Dl(e,i),o=ns.parseMasterPlaylist(n,a);if(o.playlistParsingError)return t.parsing.end=performance.now(),void this.handleManifestParsingError(e,i,o.playlistParsingError,s,t);const{contentSteering:l,levels:d,sessionData:c,sessionKeys:u,startTimeOffset:h,variableList:f}=o;this.variableList=f,d.forEach(e=>{const{unknownCodecs:t}=e;if(t){const{preferManagedMediaSource:i}=this.hls.config;let{audioCodec:s,videoCodec:r}=e;for(let n=t.length;n--;){const a=t[n];He(a,"audio",i)?(e.audioCodec=s=s?`${s},${a}`:a,Ve.audio[s.substring(0,4)]=2,t.splice(n,1)):He(a,"video",i)&&(e.videoCodec=r=r?`${r},${a}`:a,Ve.video[r.substring(0,4)]=2,t.splice(n,1))}}});const{AUDIO:g=[],SUBTITLES:p,"CLOSED-CAPTIONS":m}=ns.parseMasterPlaylistMedia(n,a,o);if(g.length){g.some(e=>!e.url)||!d[0].audioCodec||d[0].attrs.AUDIO||(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Ii({}),bitrate:0,url:""}))}r.trigger(P.MANIFEST_LOADED,{levels:d,audioTracks:g,subtitles:p,captions:m,contentSteering:l,url:a,stats:t,networkDetails:s,sessionData:c,sessionKeys:u,startTimeOffset:h,variableList:f})}handleTrackOrLevelPlaylist(e,t,i,s,r){const n=this.hls,{id:a,level:o,type:l}=i,d=Dl(e,i),c=L(o)?o:L(a)?a:0,u=Pl(i),h=ns.parseLevelPlaylist(e.data,d,c,u,0,this.variableList);if(l===D){const e={attrs:new Ii({}),bitrate:0,details:h,name:"",url:d};h.requestScheduled=t.loading.start+bs(h,0),n.trigger(P.MANIFEST_LOADED,{levels:[e],audioTracks:[],url:d,stats:t,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=h,this.handlePlaylistLoaded(h,e,t,i,s,r)}handleManifestParsingError(e,t,i,s,r){this.hls.trigger(P.ERROR,{type:k.NETWORK_ERROR,details:w.MANIFEST_PARSING_ERROR,fatal:t.type===D,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:s,stats:r})}handleNetworkError(e,t,i=!1,s,r){let n=`A network ${i?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${e.type}`;e.type===x?n+=`: ${e.level} id: ${e.id}`:e.type!==C&&e.type!==_||(n+=` id: ${e.id} group-id: "${e.groupId}"`);const a=new Error(n);this.hls.logger.warn(`[playlist-loader]: ${n}`);let o=w.UNKNOWN,l=!1;const d=this.getInternalLoader(e);switch(e.type){case D:o=i?w.MANIFEST_LOAD_TIMEOUT:w.MANIFEST_LOAD_ERROR,l=!0;break;case x:o=i?w.LEVEL_LOAD_TIMEOUT:w.LEVEL_LOAD_ERROR,l=!1;break;case C:o=i?w.AUDIO_TRACK_LOAD_TIMEOUT:w.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case _:o=i?w.SUBTITLE_TRACK_LOAD_TIMEOUT:w.SUBTITLE_LOAD_ERROR,l=!1}d&&this.resetInternalLoader(e.type);const c={type:k.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:d,context:e,error:a,networkDetails:t,stats:r};if(s){const i=(null==t?void 0:t.url)||e.url;c.response=G({url:i,data:void 0},s)}this.hls.trigger(P.ERROR,c)}handlePlaylistLoaded(e,t,i,s,r,n){const a=this.hls,{type:o,level:l,levelOrTrack:d,id:c,groupId:u,deliveryDirectives:h}=s,f=Dl(t,s),g=Pl(s);let p="number"==typeof s.level&&g===M?l:void 0;const m=e.playlistParsingError;if(m){if(this.hls.logger.warn(`${m} ${e.url}`),!a.config.ignorePlaylistParsingErrors)return void a.trigger(P.ERROR,{type:k.NETWORK_ERROR,details:w.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:m,reason:m.message,response:t,context:s,level:p,parent:g,networkDetails:r,stats:i});e.playlistParsingError=null}if(!e.fragments.length){const n=e.playlistParsingError=new Error("No Segments found in Playlist");return void a.trigger(P.ERROR,{type:k.NETWORK_ERROR,details:w.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:n,reason:n.message,response:t,context:s,level:p,parent:g,networkDetails:r,stats:i})}switch(e.live&&n&&(n.getCacheAge&&(e.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case D:case x:if(p)if(d){if(d!==a.levels[p]){const e=a.levels.indexOf(d);e>-1&&(p=e)}}else p=0;a.trigger(P.LEVEL_LOADED,{details:e,levelInfo:d||a.levels[0],level:p||0,id:c||0,stats:i,networkDetails:r,deliveryDirectives:h,withoutMultiVariant:o===D});break;case C:a.trigger(P.AUDIO_TRACK_LOADED,{details:e,track:d,id:c||0,groupId:u||"",stats:i,networkDetails:r,deliveryDirectives:h});break;case _:a.trigger(P.SUBTITLE_TRACK_LOADED,{details:e,track:d,id:c||0,groupId:u||"",stats:i,networkDetails:r,deliveryDirectives:h})}}}class Cl{static get version(){return sr}static isMSESupported(){return Rl()}static isSupported(){return function(){if(!Rl())return!1;const e=X();return"function"==typeof(null==e?void 0:e.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(t=>e.isTypeSupported(je(t,"video")))||["mp4a.40.2","fLaC"].some(t=>e.isTypeSupported(je(t,"audio"))))}()}static getMediaSource(){return X()}static get Events(){return P}static get MetadataSchema(){return Ir}static get ErrorTypes(){return k}static get ErrorDetails(){return w}static get DefaultConfig(){return Cl.defaultConfig?Cl.defaultConfig:cl}static set DefaultConfig(e){Cl.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new ir,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const t=this.logger=function(e,t,i){const s=W();if("object"==typeof console&&!0===e||"object"==typeof e){const r=["debug","log","info","warn","error"];r.forEach(t=>{s[t]=q(t,e,i)});try{s.log(`Debug logs enabled for "${t}" in hls.js version 1.6.14`)}catch(e){return W()}r.forEach(t=>{Y[t]=q(t,e)})}else $(Y,s);return s}(e.debug||!1,"Hls instance",e.assetPlayerId),i=this.config=function(e,t,i){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const s=ul(e),r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(e=>{const n=`${"level"===e?"playlist":e}LoadPolicy`,a=void 0===t[n],o=[];r.forEach(i=>{const r=`${e}Loading${i}`,l=t[r];if(void 0!==l&&a){o.push(r);const e=s[n].default;switch(t[n]={default:e},i){case"TimeOut":e.maxLoadTimeMs=l,e.maxTimeToFirstByteMs=l;break;case"MaxRetry":e.errorRetry.maxNumRetry=l,e.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":e.errorRetry.retryDelayMs=l,e.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":e.errorRetry.maxRetryDelayMs=l,e.timeoutRetry.maxRetryDelayMs=l}}}),o.length&&i.warn(`hls.js config: "${o.join('", "')}" setting(s) are deprecated, use "${n}": ${Tt(t[n])}`)}),G(G({},s),t)}(Cl.DefaultConfig,e,t);this.userConfig=e,i.progressive&&hl(i,t);const{abrController:s,bufferController:r,capLevelController:n,errorController:a,fpsController:o}=i,l=new a(this),d=this.abrController=new s(this),c=new ei(this),u=i.interstitialsController,h=u?this.interstitialsController=new u(this,Cl):null,f=this.bufferController=new r(this,c),g=this.capLevelController=new n(this),p=new o(this),m=new xl(this),v=i.contentSteeringController,y=v?new v(this):null,T=this.levelController=new Al(this,y),E=new El(this),S=new kl(this.config,this.logger),A=this.streamController=new Il(this,c,S),b=this.gapController=new fl(this,c);g.setStreamController(A),p.setStreamController(A);const L=[m,T,A];h&&L.splice(1,0,h),y&&L.splice(1,0,y),this.networkControllers=L;const R=[d,f,b,g,p,E,c];this.audioTrackController=this.createController(i.audioTrackController,L);const I=i.audioStreamController;I&&L.push(this.audioStreamController=new I(this,c,S)),this.subtitleTrackController=this.createController(i.subtitleTrackController,L);const k=i.subtitleStreamController;k&&L.push(this.subtititleStreamController=new k(this,c,S)),this.createController(i.timelineController,R),S.emeController=this.emeController=this.createController(i.emeController,R),this.cmcdController=this.createController(i.cmcdController,R),this.latencyController=this.createController(Sl,R),this.coreComponents=R,L.push(l);const w=l.onErrorOut;"function"==typeof w&&this.on(P.ERROR,w,l),this.on(P.MANIFEST_LOADED,m.onManifestLoaded,m)}createController(e,t){if(e){const i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i)}once(e,t,i=this){this._emitter.once(e,t,i)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,i=this,s){this._emitter.off(e,t,i,s)}listeners(e){return this._emitter.listeners(e)}emit(e,t,i){return this._emitter.emit(e,t,i)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),!this.triggeringException){this.triggeringException=!0;const i=e===P.ERROR;this.trigger(P.ERROR,{type:k.OTHER_ERROR,details:w.INTERNAL_EXCEPTION,fatal:i,event:e,error:t}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(P.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(e=>e.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(e=>e.destroy()),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const t=new Error(`attachMedia failed: invalid argument (${e})`);return void this.trigger(P.ERROR,{type:k.OTHER_ERROR,details:w.ATTACH_MEDIA_ERROR,fatal:!0,error:t})}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,i=t?e.media:e,s=t?e:{media:i};this._media=i,this.trigger(P.MEDIA_ATTACHING,s)}detachMedia(){this.logger.log("detachMedia"),this.trigger(P.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(P.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,i=this._url,s=this._url=re.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${s}`),t&&i&&(i!==s||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(P.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(e,t),this.started&&this.networkControllers);i++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!this.started&&this.networkControllers);e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[M]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[O]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[F]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=null==e?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=function(){try{return crypto.randomUUID()}catch(e){try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(e){let t=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const i=(t+16*Math.random())%16|0;return t=Math.floor(t/16),("x"==e?i:3&i|8).toString(16)})}}}()),e}get levels(){const e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return-1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){(function(e){return dt.indexOf(e)>-1})(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const i=e.length;for(let s=0;s<i;s++)if(e[s].maxBitrate>=t)return s;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this;let s;if(s=-1===t&&null!=e&&e.length?e.length-1:t,i)for(let t=s;t--;){const s=e[t].attrs["HDCP-LEVEL"];if(s&&s<=i)return t}return s}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return(null==(t=this.audioTrackController)?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return(null==(t=this.subtitleTrackController)?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return!!e&&e.subtitleDisplay}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!(null==(e=this.bufferController)||!e.bufferedToEnd)}get interstitialsManager(){var e;return(null==(e=this.interstitialsController)?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){return at(e,St(t),navigator.mediaCapabilities)}}function _l(){var e=navigator.userAgent,t=function(){var e;if("userAgentData"in navigator&&(null===(e=navigator.userAgentData)||void 0===e?void 0:e.platform))return navigator.userAgentData.platform;var t=navigator.userAgent;return/Mac|iPhone|iPad|iPod/i.test(t)?/iPhone|iPad|iPod/i.test(t)?"iPhone":"MacIntel":/Win/i.test(t)?"Win32":/Linux/i.test(t)?/Android/i.test(t)?"Linux armv8l":"Linux x86_64":/CrOS/i.test(t)?"CrOS":navigator.platform||"Unknown"}(),i="Unknown",s="0",r=0,n=!1,a=!1,o=!0,l=!0,d="ima";if(/Web0S|webOS/i.test(e))i="LG WebOS",n=!0,"Unknown"!==(s=(c=e.match(/Web0S[/\s]*([\d.]+)/i))&&c[1]?c[1]:"Unknown")&&(r=(u=s.split("."))[0]?parseInt(u[0],10):0);else if(/Tizen/i.test(e)){var c,u;if(i="Samsung Tizen",n=!0,"Unknown"!==(s=(c=e.match(/Tizen[/\s]*([\d.]+)/i))&&c[1]?c[1]:"Unknown"))r=(u=s.split("."))[0]?parseInt(u[0],10):0}else/SMART-TV|SmartTV/i.test(e)?(i="Smart TV",n=!0):/NetCast/i.test(e)?(i="LG NetCast",n=!0,a=!0):/BRAVIA/i.test(e)&&(i="Sony BRAVIA",n=!0);var h=function(e){var t=e.match(/Chrome\/(\d+)/);return t&&t[1]?parseInt(t[1],10):0}(e),f=function(e){var t=e.match(/AppleWebKit\/(\d+)/);return t&&t[1]?parseInt(t[1],10):0}(e);return h>0&&(n||(i="Chrome",s=h.toString(),r=h),h<50&&(o=!1,l=!1,a=!0,d="hls")),f>0&&f<600&&(l=!1,n&&(a=!0,o=!1,d="hls")),"undefined"!=typeof Promise&&"undefined"!=typeof Map&&"undefined"!=typeof Set||(l=!1,o=!1,d="hls"),"undefined"==typeof URLSearchParams&&(l=!1),{name:i,version:s,majorVersion:r,isSmartTV:n,isLegacyTV:a,platform:t,supportsIMA:o,supportsModernJS:l,recommendedAdPlayer:d}}function Ml(){var e=_l();if(e.isLegacyTV)return!1;if("undefined"==typeof document||"function"!=typeof document.createElement)return!1;try{if(!document.createElement("video"))return!1}catch(e){return!1}return"undefined"!=typeof Promise&&e.supportsIMA}function Ol(e){if(void 0===e&&(e=!1),e){var t=_l(),i=Ml();console.log("[StormcloudVideoPlayer] Browser Compatibility Info:",{browser:"".concat(t.name," ").concat(t.version),platform:t.platform,isSmartTV:t.isSmartTV,isLegacyTV:t.isLegacyTV,supportsIMA:i,supportsModernJS:t.supportsModernJS,recommendedAdPlayer:t.recommendedAdPlayer,userAgent:navigator.userAgent})}}function Fl(){var e=_l(),t={};return!e.isLegacyTV&&e.supportsIMA||(t.adPlayerType="hls"),e.isSmartTV&&(t.allowNativeHls=!0),t}function Ul(e,t){var i,s,r,l,d,c,u=!1,h=!1,f=!1,g="number"!=typeof e.volume||Number.isNaN(e.volume)?1:Math.max(0,Math.min(1,e.volume)),p=new Map,m=new Map,v=new Map;function y(t){t?e.dataset.stormcloudAdPlaying="true":delete e.dataset.stormcloudAdPlaying}function T(){h&&(e.style.visibility="visible",e.style.transition="opacity 0.3s ease-in-out",e.offsetHeight,e.style.opacity="1",e.muted=f,e.volume=g,h=!1)}function E(){var e=document.createElement("video");return e.style.position="absolute",e.style.top="0",e.style.left="0",e.style.width="100%",e.style.height="100%",e.style.objectFit="contain",e.style.backgroundColor="transparent",e.style.zIndex="15",e.playsInline=!0,e.muted=!1,e.volume=f?0:g,e.style.opacity="0",e.addEventListener("canplay",function(){e.style.opacity="1"},{once:!0}),e}function S(e,t){var i,s,r=p.get(e);if(r)try{for(var n=o(Array.from(r)),a=n.next();!a.done;a=n.next()){var l=a.value;try{l(t)}catch(e){}}}catch(e){i={error:e}}finally{try{a&&!a.done&&(s=n.return)&&s.call(n)}finally{if(i)throw i.error}}}function A(){var e,t,i;if(!Ml())return console.warn("[IMA] Google IMA SDK is not supported on this browser. Please use HLS ad player instead."),Promise.reject(new Error("Google IMA SDK not supported on this browser"));try{var s=window.frameElement,r=(null===(e=null==s?void 0:s.getAttribute)||void 0===e?void 0:e.call(s,"sandbox"))||"";if(r)new Set(r.split(/\s+/).map(function(e){return e.trim()}).filter(function(e){return e.length>0})).has("allow-scripts")||console.error("StormcloudVideoPlayer: The host page is inside a sandboxed iframe without 'allow-scripts'. Google IMA cannot run ads within sandboxed frames. Remove the sandbox attribute or include 'allow-scripts allow-same-origin'.")}catch(e){}if("undefined"!=typeof window&&(null===(t=window.google)||void 0===t?void 0:t.ima))return Promise.resolve();var n=document.querySelector('script[data-ima="true"]');return n?(null===(i=window.google)||void 0===i?void 0:i.ima)?Promise.resolve():new Promise(function(e,t){var i=setTimeout(function(){t(new Error("IMA SDK load timeout"))},1e4);n.addEventListener("load",function(){clearTimeout(i),e()}),n.addEventListener("error",function(){clearTimeout(i),t(new Error("IMA SDK load failed"))})}):new Promise(function(e,t){var i=document.createElement("script");i.src="https://imasdk.googleapis.com/js/sdkloader/ima3.js",i.async=!0,i.defer=!0,i.setAttribute("data-ima","true"),i.onload=function(){return e()},i.onerror=function(){return t(new Error("IMA SDK load failed"))},document.head.appendChild(i)})}var b,L,R,I=0;function k(t,i){var s=new t.ima.AdsRequest;console.log("[IMA] 📡 Requesting VAST from URL (letting IMA fetch fresh)"),s.adTagUrl=i;var n=e.offsetWidth||e.clientWidth||640,a=e.offsetHeight||e.clientHeight||360;if(s.linearAdSlotWidth=n,s.linearAdSlotHeight=a,s.nonLinearAdSlotWidth=n,s.nonLinearAdSlotHeight=a,"function"==typeof s.setAdWillAutoPlay)try{var o=!e.paused||e.autoplay;s.setAdWillAutoPlay(o)}catch(e){console.warn("[IMA] Failed to call setAdWillAutoPlay:",e)}if("function"==typeof s.setAdWillPlayMuted)try{var l=e.muted||0===e.volume;s.setAdWillPlayMuted(l)}catch(e){console.warn("[IMA] Failed to call setAdWillPlayMuted:",e)}s.vastLoadTimeout=1e4,r.requestAds(s)}function w(){var t;if(!d){var i=document.createElement("div");i.style.position="absolute",i.style.left="0",i.style.top="0",i.style.right="0",i.style.bottom="0",i.style.display="none",i.style.alignItems="center",i.style.justifyContent="center",i.style.pointerEvents="none",i.style.zIndex="10",i.style.backgroundColor="transparent",i.style.transition="opacity 0.3s ease-in-out, background-color 0.3s ease-in-out",i.style.opacity="0",null===(t=e.parentElement)||void 0===t||t.appendChild(i),d=i}}function P(){if(s){try{s.destroy()}catch(e){}s=void 0}i&&(i.style.opacity="0")}return{initialize:function(){A().then(function(){var e,t=window.google;if(w(),!l&&d){i||(i=E(),d.appendChild(i)),l=new t.ima.AdDisplayContainer(d,i);try{null===(e=l.initialize)||void 0===e||e.call(l)}catch(e){}}}).catch(function(){})},requestAds:function(o){return n(this,void 0,void 0,function(){var n,p,m,v,w,D,x,C;return a(this,function(a){switch(a.label){case 0:if(!o||""===o.trim())return D=new Error("VAST tag URL is empty or undefined"),console.warn("[IMA] ❌",D.message),[2,Promise.reject(D)];try{new URL(o)}catch(e){return D=new Error("Invalid VAST tag URL format: ".concat(o)),console.warn("[IMA] ❌",D.message),[2,Promise.reject(D)]}if(u)return console.warn("[IMA] ⚠️ Cannot request new ads while an ad is playing. Call stop() first."),[2,Promise.reject(new Error("Ad already playing - cannot request new ads"))];P(),R=void 0,L=void 0,b=new Promise(function(e,t){L=e,R=t,n=t,setTimeout(function(){R&&(R(new Error("Ad request timeout")),R=void 0,L=void 0)},1e4)}),a.label=1;case 1:return a.trys.push([1,3,,4]),[4,A()];case 2:if(a.sent(),p=window.google,c=o,I=0,!l){if((m=document.createElement("div")).style.position="absolute",m.style.left="0",m.style.top="0",m.style.right="0",m.style.bottom="0",m.style.display="none",m.style.alignItems="center",m.style.justifyContent="center",m.style.pointerEvents="none",m.style.zIndex="10",m.style.backgroundColor="transparent",m.style.transition="opacity 0.3s ease-in-out, background-color 0.3s ease-in-out",m.style.opacity="0",!e.parentElement)throw new Error("Video element has no parent for ad container");e.parentElement.appendChild(m),d=m,i||(i=E(),d.appendChild(i)),l=new p.ima.AdDisplayContainer(m,i)}return v=e.offsetWidth||e.clientWidth,w=e.offsetHeight||e.clientHeight,v&&w&&0!==v&&0!==w?(r||(x=new p.ima.AdsLoader(l),(r=x).addEventListener(p.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,function(r){try{var n=new p.ima.AdsRenderingSettings;n.enablePreloading=!0,s=r.getAdsManager(e,n);var a=p.ima.AdEvent.Type,o=p.ima.AdErrorEvent.Type;s.addEventListener(o.AD_ERROR,function(i){var s,r,n=i.getError();if(console.error("[DEBUG-ERROR] ❌ AD_ERROR:",null===(s=n.getMessage)||void 0===s?void 0:s.call(n)),P(),u=!1,y(!1),d&&(d.style.opacity="0",d.style.backgroundColor="transparent",setTimeout(function(){d&&(d.style.pointerEvents="none",d.style.display="none")},300)),T(),R&&(R(new Error("Ad playback error")),R=void 0,L=void 0),c&&I<2){var a=500*Math.pow(2,I++);window.setTimeout(function(){try{k(p,c)}catch(e){}},a)}else S("ad_error"),(null==t?void 0:t.continueLiveStreamDuringAds)||e.paused&&(null===(r=e.play())||void 0===r||r.catch(function(){}))}),s.addEventListener(a.CONTENT_PAUSE_REQUESTED,function(){(null==t?void 0:t.continueLiveStreamDuringAds)||e.pause(),u=!0,y(!0),S("content_pause")}),s.addEventListener(a.STARTED,function(){y(!0),h||(e.style.transition="opacity 0.3s ease-in-out",e.style.opacity="0",setTimeout(function(){e.style.visibility="hidden"},300),e.muted=!0,e.volume=0,h=!0),i&&(i.volume=f?0:g,i.muted=f),d&&(d.style.pointerEvents="auto",d.style.display="flex",d.style.backgroundColor="#000",d.offsetHeight,d.style.opacity="1")}),s.addEventListener(a.CONTENT_RESUME_REQUESTED,function(){u=!1,y(!1),S("content_resume")}),s.addEventListener(a.ALL_ADS_COMPLETED,function(){u=!1,y(!1),d&&(d.style.opacity="0",d.style.backgroundColor="transparent",setTimeout(function(){d&&(d.style.pointerEvents="none",d.style.display="none")},300)),T(),!(null==t?void 0:t.continueLiveStreamDuringAds)&&e.paused&&e.play().catch(function(){}),S("all_ads_completed")}),L&&(L(),L=void 0,R=void 0)}catch(i){console.error("[IMA] Error setting up ads manager:",i),u=!1,y(!1),d&&(d.style.opacity="0",d.style.backgroundColor="transparent",setTimeout(function(){d&&(d.style.pointerEvents="none",d.style.display="none")},300)),T(),(null==t?void 0:t.continueLiveStreamDuringAds)||e.paused&&e.play().catch(function(){}),R&&(R(new Error("Failed to setup ads manager")),R=void 0,L=void 0),S("ad_error")}},!1),r.addEventListener(p.ima.AdErrorEvent.Type.AD_ERROR,function(i){var s,r=i.getError();console.error("[DEBUG-ERROR] ❌ ADS_LOADER ERROR:",null===(s=r.getMessage)||void 0===s?void 0:s.call(r)),u=!1,y(!1),d&&(d.style.opacity="0",d.style.backgroundColor="transparent",setTimeout(function(){d&&(d.style.pointerEvents="none",d.style.display="none")},300)),T(),(null==t?void 0:t.continueLiveStreamDuringAds)||e.paused&&e.play().catch(function(){}),R&&(R(new Error("Ads loader error")),R=void 0,L=void 0),S("ad_error")},!1)),k(p,o),[2,b]):(D=new Error("Invalid video dimensions: ".concat(v,"x").concat(w,". Cannot initialize ads.")),console.warn("[IMA]",D.message),null==n||n(D),R=void 0,L=void 0,[2,Promise.reject(D)]);case 3:return C=a.sent(),console.error("[IMA] Failed to request ads:",C),null==n||n(C),R=void 0,L=void 0,[2,Promise.reject(C)];case 4:return[2]}})})},preloadAds:function(e){return n(this,void 0,void 0,function(){var t,i;return a(this,function(s){return e&&""!==e.trim()?m.has(e)?[2,Promise.resolve()]:(t=v.get(e))?[2,t]:(i=function(e){return n(this,void 0,void 0,function(){var t;return a(this,function(i){switch(i.label){case 0:return[4,fetch(e,{mode:"cors"})];case 1:if(!(t=i.sent()).ok)throw new Error("Failed to preload VAST: ".concat(t.status));return[2,t.text()]}})})}(e).then(function(t){m.set(e,t)}).catch(function(){m.delete(e)}).finally(function(){v.delete(e)}),v.set(e,i),[2,i]):[2,Promise.resolve()]})})},hasPreloadedAd:function(e){return m.has(e)},play:function(){return n(this,void 0,void 0,function(){var r,n,o,d,c;return a(this,function(a){if(!(null===(d=window.google)||void 0===d?void 0:d.ima)||!l)return[2,Promise.reject(new Error("IMA SDK not available"))];if(!s)return[2,Promise.reject(new Error("No ads manager"))];try{r=e.clientWidth||640,n=e.clientHeight||360,s.init(r,n,window.google.ima.ViewMode.NORMAL),u=!0,o=f?0:g,i&&(i.volume=o,i.muted=f);try{s.setVolume(o)}catch(e){}return s.start(),[2,Promise.resolve()]}catch(i){return console.error("[IMA] ❌ Error starting ad:",i),u=!1,y(!1),(null==t?void 0:t.continueLiveStreamDuringAds)||null===(c=e.play())||void 0===c||c.catch(function(){}),[2,Promise.reject(i)]}return[2]})})},stop:function(){return n(this,void 0,void 0,function(){var e;return a(this,function(t){u=!1,y(!1),d&&(d.style.opacity="0",d.style.backgroundColor="transparent",setTimeout(function(){d&&(d.style.pointerEvents="none",d.style.display="none")},300)),T();try{null===(e=null==s?void 0:s.stop)||void 0===e||e.call(s)}catch(e){}return P(),[2]})})},destroy:function(){var e;P(),u=!1,y(!1),d&&(d.style.opacity="0",d.style.backgroundColor="transparent",setTimeout(function(){d&&(d.style.pointerEvents="none",d.style.display="none",d.parentElement&&d.parentElement.removeChild(d),d=void 0,i=void 0)},300)),T();try{null===(e=null==r?void 0:r.destroy)||void 0===e||e.call(r)}catch(e){}l=void 0,r=void 0,h=!1,m.clear(),v.clear()},isAdPlaying:function(){return u},resize:function(e,t){var i;if(s&&(null===(i=window.google)||void 0===i?void 0:i.ima))try{console.log("[IMA] Resizing ads manager to ".concat(e,"x").concat(t)),s.resize(e,t,window.google.ima.ViewMode.NORMAL)}catch(e){console.warn("[IMA] Error resizing ads manager:",e)}else console.warn("[IMA] Cannot resize: No ads manager or IMA SDK available")},on:function(e,t){p.has(e)||p.set(e,new Set),p.get(e).add(t)},off:function(e,t){var i;null===(i=p.get(e))||void 0===i||i.delete(t)},updateOriginalMutedState:function(e,t){var i="number"!=typeof t||Number.isNaN(t)?g:Math.max(0,Math.min(1,t));f=e,g=i},getOriginalMutedState:function(){return f},getOriginalVolume:function(){return g},setAdVolume:function(e){var t=Math.max(0,Math.min(1,e));if(i&&u&&(i.volume=t,i.muted=0===t),s&&u)try{s.setVolume(t)}catch(e){}},getAdVolume:function(){if(i&&u)return i.volume;if(s&&u)try{return s.getVolume()}catch(e){return console.warn("[IMA] Failed to get ad volume:",e),1}return 1},showPlaceholder:function(){w(),d&&(d.style.display="flex",d.style.backgroundColor="#000",d.offsetHeight,d.style.opacity="1",d.style.pointerEvents="auto")},hidePlaceholder:function(){d&&(d.style.opacity="0",d.style.backgroundColor="transparent",setTimeout(function(){d&&(d.style.display="none",d.style.pointerEvents="none")},300))}}}function Nl(e,t){var i,s,r,l,d,c=!1,u=!1,h=Math.max(0,Math.min(1,e.volume||1)),f=new Map,g=null==t?void 0:t.licenseKey,p=null==t?void 0:t.mainHlsInstance,m=new Map,v=new Map,y=!1,T=[],E={impression:!1,start:!1,firstQuartile:!1,midpoint:!1,thirdQuartile:!1,complete:!1};function S(e,t){var i,s,r=f.get(e);if(r)try{for(var n=o(Array.from(r)),a=n.next();!a.done;a=n.next()){var l=a.value;try{l(t)}catch(t){console.warn("[HlsAdPlayer] Error in event listener for ".concat(e,":"),t)}}}catch(e){i={error:e}}finally{try{a&&!a.done&&(s=n.return)&&s.call(n)}finally{if(i)throw i.error}}}function A(e){e&&0!==e.length&&e.forEach(function(e){try{var t=e;d&&(t="".concat(t).concat(t.includes("?")?"&":"?","session_id=").concat(d)),g&&(t="".concat(t).concat(t.includes("?")?"&":"?","license_key=").concat(g)),new Image(1,1).src=t,console.log("[HlsAdPlayer] Fired tracking pixel: ".concat(t))}catch(e){console.warn("[HlsAdPlayer] Error firing tracking pixel:",e)}})}function b(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 i=function(){if(!p||!p.levels)return null;var e=p.currentLevel;if(-1===e||!p.levels[e]){var t=p.loadLevel;if(-1!==t&&p.levels[t]){var i=p.levels[t];return{width:i.width||1920,height:i.height||1080,bitrate:i.bitrate||5e6}}return null}var s=p.levels[e];return{width:s.width||1920,height:s.height||1080,bitrate:s.bitrate||5e6}}();if(!i)return console.log("[HlsAdPlayer] No main stream quality info, using first media file"),t;console.log("[HlsAdPlayer] Main stream quality:",i);var s=e.map(function(e){var t=Math.abs(e.width-i.width)+Math.abs(e.height-i.height),s=1e3*(e.bitrate||5e3),r=Math.abs(s-i.bitrate);return{file:e,score:2*t+r/1e3,resolutionDiff:t,bitrateDiff:r}});s.sort(function(e,t){return e.score-t.score});var r=s[0];return r?(console.log("[HlsAdPlayer] Selected media file:",{url:r.file.url,resolution:"".concat(r.file.width,"x").concat(r.file.height),bitrate:r.file.bitrate,score:r.score,resolutionDiff:r.resolutionDiff,bitrateDiff:r.bitrateDiff}),r.file):(console.log("[HlsAdPlayer] No best match found, using first media file"),t)}function L(e){var t,i,s,r;try{var n=(new DOMParser).parseFromString(e,"text/xml"),a=n.querySelector("parsererror");if(a)return console.error("[HlsAdPlayer] XML parsing error (malformed VAST XML):",a.textContent),null;var o=n.querySelector("Ad");if(!o)return console.warn("[HlsAdPlayer] No Ad element found in VAST XML"),null;var l=o.getAttribute("id")||"unknown",d=(null===(t=n.querySelector("AdTitle"))||void 0===t?void 0:t.textContent)||"Ad",c="empty"===l||d.toLowerCase().includes("no ad available")||"no ad available"===d.toLowerCase(),u=((null===(i=n.querySelector("Duration"))||void 0===i?void 0:i.textContent)||"00:00:30").split(":"),h=3600*parseInt(u[0]||"0",10)+60*parseInt(u[1]||"0",10)+parseInt(u[2]||"0",10),f=n.querySelectorAll("MediaFile"),g=[];if(console.log("[HlsAdPlayer] Found ".concat(f.length," MediaFile element(s) in VAST XML")),f.forEach(function(e,t){var i,s=e.getAttribute("type")||"",r=(null===(i=e.textContent)||void 0===i?void 0:i.trim())||"",n=e.getAttribute("width")||"",a=e.getAttribute("height")||"";if(console.log("[HlsAdPlayer] MediaFile ".concat(t,': type="').concat(s,'", url="').concat(r,'", width="').concat(n,'", height="').concat(a,'"')),"application/x-mpegURL"===s||s.includes("m3u8")){if(!r)return void console.warn("[HlsAdPlayer] MediaFile ".concat(t," has HLS type but empty URL"));var o=e.getAttribute("bitrate"),l=o?parseInt(o,10):void 0;g.push({url:r,type:s,width:parseInt(n||"1920",10),height:parseInt(a||"1080",10),bitrate:l&&l>0?l:void 0}),console.log("[HlsAdPlayer] Added HLS MediaFile: ".concat(r))}else console.log("[HlsAdPlayer] MediaFile ".concat(t,' ignored (type="').concat(s,'" is not HLS)'))}),0===g.length)return c?console.warn("[HlsAdPlayer] No ads available (VAST response indicates no ads)"):console.warn("[HlsAdPlayer] No HLS media files found in VAST XML"),null;var p={impression:[],start:[],firstQuartile:[],midpoint:[],thirdQuartile:[],complete:[],mute:[],unmute:[],pause:[],resume:[],fullscreen:[],exitFullscreen:[],skip:[],error:[]};n.querySelectorAll("Impression").forEach(function(e){var t,i=null===(t=e.textContent)||void 0===t?void 0:t.trim();i&&p.impression.push(i)}),n.querySelectorAll("Tracking").forEach(function(e){var t,i=e.getAttribute("event"),s=null===(t=e.textContent)||void 0===t?void 0:t.trim();if(i&&s){var r=i;p[r]&&p[r].push(s)}});var m=null===(r=null===(s=n.querySelector("ClickThrough"))||void 0===s?void 0:s.textContent)||void 0===r?void 0:r.trim();return{id:l,title:d,duration:h,mediaFiles:g,trackingUrls:p,clickThrough:m}}catch(e){return console.error("[HlsAdPlayer] Error parsing VAST XML:",e),null}}function R(e){return n(this,void 0,void 0,function(){var t,i;return a(this,function(s){switch(s.label){case 0:return[4,fetch(e)];case 1:if(!(t=s.sent()).ok)throw new Error("Failed to fetch VAST: ".concat(t.statusText));return[4,t.text()];case 2:return i=s.sent(),console.log("[HlsAdPlayer] VAST XML received"),console.log("[HlsAdPlayer] VAST XML content (first 2000 chars):",i.substring(0,2e3)),[2,L(i)]}})})}function I(){i&&l&&(i.addEventListener("timeupdate",function(){if(l&&i){var e=i.currentTime/l.duration;e>=.25&&!E.firstQuartile&&(E.firstQuartile=!0,A(l.trackingUrls.firstQuartile)),e>=.5&&!E.midpoint&&(E.midpoint=!0,A(l.trackingUrls.midpoint)),e>=.75&&!E.thirdQuartile&&(E.thirdQuartile=!0,A(l.trackingUrls.thirdQuartile))}}),i.addEventListener("playing",function(){l&&!E.start&&(E.start=!0,A(l.trackingUrls.start),console.log("[HlsAdPlayer] Ad started playing"))}),i.addEventListener("ended",function(){l&&!E.complete&&(E.complete=!0,A(l.trackingUrls.complete),console.log("[HlsAdPlayer] Ad completed"),function(){console.log("[HlsAdPlayer] Handling ad completion"),c=!1,k(!1),S("content_resume");var t=window.setTimeout(function(){if(y)console.log("[HlsAdPlayer] Player destroyed, skipping post-completion check");else{"true"===e.dataset.stormcloudAdPlaying&&(console.log("[HlsAdPlayer] Still in ad pod - keeping ad container visible (black screen)"),r&&(r.style.display="flex",r.style.pointerEvents="auto"));var i=T.indexOf(t);-1!==i&&T.splice(i,1)}},50);T.push(t)}())}),i.addEventListener("error",function(e){console.error("[HlsAdPlayer] Ad video error:",e),l&&A(l.trackingUrls.error),w()}),i.addEventListener("volumechange",function(){l&&(i.muted?A(l.trackingUrls.mute):A(l.trackingUrls.unmute))}),i.addEventListener("pause",function(){l&&!i.ended&&A(l.trackingUrls.pause)}),i.addEventListener("play",function(){l&&i.currentTime>0&&A(l.trackingUrls.resume)}))}function k(t){t?e.dataset.stormcloudAdPlaying="true":delete e.dataset.stormcloudAdPlaying}function w(){console.log("[HlsAdPlayer] Handling ad error"),c=!1,k(!1);var i=e.muted;e.muted=u,e.volume=u?0:h,console.log("[HlsAdPlayer] Restored mute state: ".concat(i," -> ").concat(u)),r&&(r.style.display="none",r.style.pointerEvents="none"),(null==t?void 0:t.continueLiveStreamDuringAds)||e.paused&&e.play().catch(function(){}),S("ad_error")}return{initialize:function(){var t;if(console.log("[HlsAdPlayer] Initializing"),!r){var i=document.createElement("div");i.style.position="absolute",i.style.left="0",i.style.top="0",i.style.right="0",i.style.bottom="0",i.style.display="none",i.style.alignItems="center",i.style.justifyContent="center",i.style.pointerEvents="none",i.style.zIndex="10",i.style.backgroundColor="#000",null===(t=e.parentElement)||void 0===t||t.appendChild(i),r=i}},requestAds:function(e){return n(this,void 0,void 0,function(){var t,i;return a(this,function(s){switch(s.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"))];s.label=1;case 1:return s.trys.push([1,5,,6]),d="session-".concat(Date.now(),"-").concat(Math.random().toString(36).substr(2,9)),t=void 0,m.has(e)?(t=m.get(e),m.delete(e),console.log("[HlsAdPlayer] Using preloaded VAST response:",e),[3,4]):[3,2];case 2:return[4,R(e)];case 3:t=s.sent(),s.label=4;case 4:return t?(l=t,console.log("[HlsAdPlayer] Ad parsed: ".concat(t.title,", duration: ").concat(t.duration,"s")),A(t.trackingUrls.impression),E.impression=!0,[2,Promise.resolve()]):(console.warn("[HlsAdPlayer] No ads available from VAST response"),S("ad_error"),[2,Promise.resolve()]);case 5:return i=s.sent(),console.error("[HlsAdPlayer] Error requesting ads:",i),S("ad_error"),[2,Promise.reject(i)];case 6:return[2]}})})},preloadAds:function(e){return n(this,void 0,void 0,function(){var t,i;return a(this,function(s){return e&&""!==e.trim()?m.has(e)?[2,Promise.resolve()]:(t=v.get(e))?[2,t]:(i=R(e).then(function(t){t&&(m.set(e,t),console.log("[HlsAdPlayer] Cached VAST response for preloading:",e))}).catch(function(t){console.warn("[HlsAdPlayer] Failed to preload VAST response:",t),m.delete(e)}).finally(function(){v.delete(e)}),v.set(e,i),[2,i]):[2,Promise.resolve()]})})},hasPreloadedAd:function(e){return m.has(e)},play:function(){return n(this,void 0,void 0,function(){var n,o,d;return a(this,function(a){if(!l)return console.warn("[HlsAdPlayer] Cannot play: No ad loaded (no ads available)"),[2,Promise.reject(new Error("No ad loaded"))];console.log("[HlsAdPlayer] Starting ad playback");try{if(i||((f=document.createElement("video")).style.position="absolute",f.style.left="0",f.style.top="0",f.style.width="100%",f.style.height="100%",f.style.objectFit="contain",f.style.backgroundColor="#000",f.playsInline=!0,f.muted=!1,f.volume=1,console.log("[HlsAdPlayer] Created ad video element with volume ".concat(f.volume)),i=f,null==r||r.appendChild(i),I()),E={impression:E.impression,start:!1,firstQuartile:!1,midpoint:!1,thirdQuartile:!1,complete:!1},n=e.volume,h=Math.max(0,Math.min(1,n||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,e.volume=0,c=!0,k(!0),i&&(o=u?0:h,i.volume=Math.max(0,Math.min(1,o)),i.muted=!1,console.log("[HlsAdPlayer] Set ad video volume to ".concat(i.volume,", muted: ").concat(i.muted,", originalMutedState: ").concat(u,", contentVolume: ").concat(n))),r&&(r.style.display="flex",r.style.pointerEvents="auto"),S("content_pause"),!(d=b(l.mediaFiles)))throw new Error("No media file available for ad");if(console.log("[HlsAdPlayer] Loading ad from: ".concat(d.url)),Cl.isSupported())s&&s.destroy(),(s=new Cl({enableWorker:!0,lowLatencyMode:!1})).loadSource(d.url),s.attachMedia(i),s.on(Cl.Events.MANIFEST_PARSED,function(){console.log("[HlsAdPlayer] HLS manifest parsed, starting playback"),i.play().catch(function(e){console.error("[HlsAdPlayer] Error starting ad playback:",e),w()})}),s.on(Cl.Events.ERROR,function(e,t){console.error("[HlsAdPlayer] HLS error:",t),t.fatal&&w()});else{if(!i.canPlayType("application/vnd.apple.mpegurl"))throw new Error("HLS not supported");i.src=d.url,i.play().catch(function(e){console.error("[HlsAdPlayer] Error starting ad playback:",e),w()})}return[2,Promise.resolve()]}catch(e){return console.error("[HlsAdPlayer] Error playing ad:",e),w(),[2,Promise.reject(e)]}var f;return[2]})})},stop:function(){return n(this,void 0,void 0,function(){return a(this,function(e){return console.log("[HlsAdPlayer] Stopping ad"),c=!1,k(!1),r&&(r.style.display="none",r.style.pointerEvents="none"),s&&(s.destroy(),s=void 0),i&&(i.pause(),i.src=""),l=void 0,[2]})})},destroy:function(){var t,n;console.log("[HlsAdPlayer] Destroying"),y=!0;try{for(var a=o(T),d=a.next();!d.done;d=a.next()){var g=d.value;clearTimeout(g)}}catch(e){t={error:e}}finally{try{d&&!d.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}T=[],c=!1,k(!1),e.muted=u,e.volume=u?0:h,s&&(s.destroy(),s=void 0),i&&(i.pause(),i.src="",i.remove(),i=void 0),(null==r?void 0:r.parentElement)&&r.parentElement.removeChild(r),r=void 0,l=void 0,f.clear(),m.clear(),v.clear()},isAdPlaying:function(){return c},resize:function(e,t){console.log("[HlsAdPlayer] Resizing to ".concat(e,"x").concat(t)),r&&(r.style.width="".concat(e,"px"),r.style.height="".concat(t,"px")),i&&(i.style.width="".concat(e,"px"),i.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 i;null===(i=f.get(e))||void 0===i||i.delete(t)},updateOriginalMutedState:function(e,t){var i="number"!=typeof t||Number.isNaN(t)?h:Math.max(0,Math.min(1,t));console.log("[HlsAdPlayer] updateOriginalMutedState called: { muted: ".concat(u," -> ").concat(e,", volume: ").concat(h," -> ").concat(i," }")),u=e,h=i},getOriginalMutedState:function(){return u},getOriginalVolume:function(){return h},setAdVolume:function(e){i&&c&&(i.volume=Math.max(0,Math.min(1,e)))},getAdVolume:function(){return i&&c?i.volume:1},showPlaceholder:function(){var t;if(!r){var i=document.createElement("div");i.style.position="absolute",i.style.left="0",i.style.top="0",i.style.right="0",i.style.bottom="0",i.style.display="none",i.style.alignItems="center",i.style.justifyContent="center",i.style.pointerEvents="none",i.style.zIndex="10",i.style.backgroundColor="#000",null===(t=e.parentElement)||void 0===t||t.appendChild(i),r=i}r&&(r.style.display="flex",r.style.pointerEvents="auto")},hidePlaceholder:function(){r&&(r.style.display="none",r.style.pointerEvents="none")}}}Cl.defaultConfig=void 0;var Bl=null;function $l(){var e,t,i,s,r,n=navigator.userAgent,a=navigator.platform,o=navigator.vendor||"",l=navigator.maxTouchPoints||0,d=navigator.deviceMemory||null,c=navigator.hardwareConcurrency||1,u={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",g="Unknown",p="",m=!1,v=!1,y=!1;if(n.includes("Web0S")){f="LG",g="webOS",m=!0,h="tv";var T=n.match(/Web0S\/([^\s]+)/);p=T?"webOS ".concat(T[1]):"webOS TV"}else if(n.includes("Tizen")){f="Samsung",g="Tizen",m=!0,h="tv";var E=n.match(/Tizen\/([^\s]+)/),S=n.match(/(?:Smart-TV|SMART-TV|TV)/i)?"Smart TV":"";p=E?"Tizen ".concat(E[1]," ").concat(S).trim():"Tizen TV"}else n.includes("Philips")?(f="Philips",g="Saphi",m=!0,h="tv"):n.includes("Sharp")||n.includes("AQUOS")?(f="Sharp",g="Android TV",m=!0,h="tv"):n.includes("Android")&&(n.includes("Sony")||o.includes("Sony"))?(f="Sony",g="Android TV",m=!0,h="tv"):n.includes("Android")&&(n.includes("NetCast")||n.includes("LG"))?(f="LG",g="Android TV",m=!0,h="tv"):n.includes(" Roku")||n.includes("Roku/")?(f="Roku",g="Roku OS",m=!0,h="tv"):n.includes("AppleTV")&&(f="Apple",g="tvOS",m=!0,h="tv");if(n.includes("Android")){v=!0,g="Android",h=/Mobile/.test(n)?"mobile":"tablet",n.includes("Android")&&(0===l||n.includes("Google TV")||n.includes("XiaoMi"))&&(h="tv",m=!0,f="Unknown"===f?"Android TV":f);var A=n.match(/\(([^)]*Android[^)]*)\)/);A&&A[1]&&(p=A[1])}return/iPad|iPhone|iPod/.test(n)&&(g="iOS",h="mobile",f="Apple",navigator.maxTouchPoints>1&&/iPad/.test(n)&&(h="tablet")),v||m||/Mobile/.test(n)||(n.includes("Windows")?(g="Windows",h="desktop"):n.includes("Mac")&&!/iPhone/.test(n)?(g="macOS",h="desktop",l>1&&(h="tablet")):n.includes("Linux")&&(g="Linux",h="desktop")),"Unknown"===f&&((o.includes("Google")||n.includes("Chrome"))&&(f="Google"),o.includes("Apple")&&(f="Apple"),(o.includes("Samsung")||n.includes("SM-"))&&(f="Samsung")),y=/wv|WebView|Linux; U;/.test(n),0===(null===window||void 0===window?void 0:window.outerHeight)&&0===(null===window||void 0===window?void 0:window.outerWidth)&&(y=!0),r=window.matchMedia("(display-mode: standalone)").matches||!0===window.navigator.standalone||void 0!==(null===(i=null===(t=window.screen)||void 0===t?void 0:t.orientation)||void 0===i?void 0:i.angle),{brand:f,os:g,model:p||n.substring(0,50)+"...",deviceType:h,isSmartTV:m,isAndroid:v,isWebView:y,isWebApp:r,domain:window.location.hostname,origin:window.location.origin,path:window.location.pathname,userAgent:n,vendor:o,platform:a,screen:u,hardwareConcurrency:c,deviceMemory:d,maxTouchPoints:l,language:navigator.language,languages:(null===(s=navigator.languages)||void 0===s?void 0:s.join(","))||"",cookieEnabled:navigator.cookieEnabled,doNotTrack:navigator.doNotTrack||"",referrer:document.referrer,visibilityState:document.visibilityState}}function Vl(e){return n(this,void 0,void 0,function(){var t,i,s,r,n,o,l,d,c,u,h,f,g;return a(this,function(a){switch(a.label){case 0:if(Bl)return[2,Bl];if(t=JSON.stringify(e),"undefined"==typeof crypto||!crypto.subtle||!crypto.subtle.digest)return[3,5];a.label=1;case 1:return a.trys.push([1,4,,5]),[4,crypto.subtle.digest("SHA-256",new Uint8Array([1,2,3]))];case 2:if(a.sent(),i=void 0,"undefined"!=typeof TextEncoder)i=(new TextEncoder).encode(t);else{for(s=unescape(encodeURIComponent(t)),r=new Uint8Array(s.length),c=0;c<s.length;c++)r[c]=s.charCodeAt(c);i=r}return[4,crypto.subtle.digest("SHA-256",i)];case 3:return n=a.sent(),o=Array.from(new Uint8Array(n)),l=o.map(function(e){return e.toString(16).padStart(2,"0")}).join(""),Bl=l,[2,l];case 4:return a.sent(),console.warn("[StormcloudVideoPlayer] crypto.subtle.digest not supported, using fallback hash"),[3,5];case 5:for(d=0,c=0;c<t.length;c++)u=t.charCodeAt(c),d=(d<<5)-d+u,d&=d;return h=Math.abs(d).toString(16).padStart(8,"0"),f=Date.now().toString(16).padStart(12,"0"),g=Math.random().toString(16).substring(2,14).padStart(12,"0"),[2,Bl=(h+f+g).padEnd(64,"0")]}})})}function Gl(e){return n(this,void 0,void 0,function(){var t,i,r,n,o,l;return a(this,function(a){switch(a.label){case 0:return a.trys.push([0,4,,5]),[4,Vl(t=$l())];case 1:return i=a.sent(),r=s({browserId:i},t),n={"Content-Type":"application/json"},e&&(n.Authorization="Bearer ".concat(e)),[4,fetch("https://adstorm.co/api-adstorm-dev/adstorm/player-tracking/track",{method:"POST",headers:n,body:JSON.stringify(r)})];case 2:if(!(o=a.sent()).ok)throw new Error("HTTP error! status: ".concat(o.status));return[4,o.json()];case 3:return a.sent(),[3,5];case 4:return l=a.sent(),console.error("[StormcloudVideoPlayer] Error sending initial tracking data:",l),[3,5];case 5:return[2]}})})}function Hl(e){return n(this,void 0,void 0,function(){var t,i,s,r,n;return a(this,function(a){switch(a.label){case 0:return a.trys.push([0,4,,5]),[4,Vl($l())];case 1:return t=a.sent(),i={browserId:t,timestamp:(new Date).toISOString()},s={"Content-Type":"application/json"},e&&(s.Authorization="Bearer ".concat(e)),[4,fetch("https://adstorm.co/api-adstorm-dev/adstorm/player-tracking/heartbeat",{method:"POST",headers:s,body:JSON.stringify(i)})];case 2:if(!(r=a.sent()).ok)throw new Error("HTTP error! status: ".concat(r.status));return[4,r.json()];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 Kl(){"function"!=typeof Object.assign&&(Object.assign=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];if(null==e)throw new TypeError("Cannot convert undefined or null to object");for(var s=Object(e),r=0;r<t.length;r++){var n=t[r];if(null!=n)for(var a in n)Object.prototype.hasOwnProperty.call(n,a)&&(s[a]=n[a])}return s}),Array.from||(Array.from=function(e,t,i){var s=Object(e);if(null==e)throw new TypeError("Array.from requires an array-like object");for(var r=s.length>>>0,n=new Array(r),a=0;a<r;a++)n[a]=t?t.call(i,s[a],a):s[a];return n}),String.prototype.startsWith||(String.prototype.startsWith=function(e,t){return t=!t||t<0?0:+t,this.substring(t,t+e.length)===e}),String.prototype.endsWith||(String.prototype.endsWith=function(e,t){return(void 0===t||t>this.length)&&(t=this.length),this.substring(t-e.length,t)===e}),String.prototype.includes||(String.prototype.includes=function(e,t){return"number"!=typeof t&&(t=0),!(t+e.length>this.length)&&-1!==this.indexOf(e,t)}),function(){if("undefined"==typeof URLSearchParams){var e=function(){function e(t){var i=this;this.params=new Map,"string"==typeof t?this.parseQueryString(t):t instanceof e&&t.forEach(function(e,t){i.append(t,e)})}return e.prototype.parseQueryString=function(e){var t=this,i=e.startsWith("?")?e.slice(1):e;i&&i.split("&").forEach(function(e){var i=l(e.split("="),2),s=i[0],r=i[1];if(s){var n=t.safeDecodeURIComponent(s),a=r?t.safeDecodeURIComponent(r):"";t.append(n,a)}})},e.prototype.safeDecodeURIComponent=function(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch(t){return e}},e.prototype.append=function(e,t){var i=this.params.get(e)||[];i.push(String(t)),this.params.set(e,i)},e.prototype.delete=function(e){this.params.delete(e)},e.prototype.get=function(e){var t=this.params.get(e);return t&&t.length>0&&void 0!==t[0]?t[0]:null},e.prototype.getAll=function(e){return this.params.get(e)||[]},e.prototype.has=function(e){return this.params.has(e)},e.prototype.set=function(e,t){this.params.set(e,[String(t)])},e.prototype.forEach=function(e){var t=this;this.params.forEach(function(i,s){i.forEach(function(i){e(i,s,t)})})},e.prototype.toString=function(){var e=[];return this.params.forEach(function(t,i){t.forEach(function(t){e.push("".concat(encodeURIComponent(i),"=").concat(encodeURIComponent(t)))})}),e.join("&")},e}();window.URLSearchParams=e}}(),function(){if("undefined"==typeof TextEncoder){var e=function(){function e(){this.encoding="utf-8"}return e.prototype.encode=function(e){for(var t=[],i=0;i<e.length;i++){var s=e.charCodeAt(i);s<128?t.push(s):s<2048?t.push(192|s>>6,128|63&s):s<55296||s>=57344?t.push(224|s>>12,128|s>>6&63,128|63&s):(i++,s=65536+((1023&s)<<10|1023&e.charCodeAt(i)),t.push(240|s>>18,128|s>>12&63,128|s>>6&63,128|63&s))}return new Uint8Array(t)},e}();window.TextEncoder=e}}(),"undefined"==typeof Promise||Promise.prototype.finally||(Promise.prototype.finally=function(e){var t=this.constructor;return this.then(function(i){return t.resolve(e()).then(function(){return i})},function(i){return t.resolve(e()).then(function(){throw i})})})}var jl=function(){function e(e){this.attached=!1,this.inAdBreak=!1,this.ptsDriftEmaMs=0,this.adPodQueue=[],this.lastHeartbeatTime=0,this.currentAdIndex=0,this.totalAdsInBreak=0,this.showAds=!1,this.isLiveStream=!1,this.nativeHlsMode=!1,this.videoSrcProtection=null,this.bufferedSegmentsCount=0,this.shouldAutoplayAfterBuffering=!1,this.hasInitialBufferCompleted=!1,this.adPodAllUrls=[],this.preloadingAdUrls=new Set,this.vastToMediaUrlMap=new Map,this.preloadedMediaUrls=new Set,this.preloadingMediaUrls=new Set,this.adRequestTokenCounter=0,this.activeAdRequestToken=null,this.adRequestWatchdogToken=null,this.adFailsafeToken=null,this.fetchedAdDurations=new Map,this.targetAdBreakDurationMs=null,this.isAdaptiveMode=!1,this.failedVastUrls=new Set,this.continuousFetchingActive=!1,this.adRequestQueue=[],this.successfulAdRequests=[],this.maxPlaceholderDurationMs=5e3,this.placeholderStartTimeMs=null,this.isShowingPlaceholder=!1,Kl();var t=Fl();this.config=s(s({},e),t),this.video=e.videoElement,Ol(e.debugAdTiming),this.ima=this.createAdPlayer(!1)}return e.prototype.createAdPlayer=function(e){var t=this.config.vastMode||"default",i=this.config.adPlayerType||("adstorm"===t?"hls":"ima");return"ima"!==i||Ml()||(this.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Google IMA SDK not supported on this browser, falling back to HLS ad player"),i="hls"),"hls"===i?(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Creating HLS ad player (AdStorm mode)"),Nl(this.video,s(s({continueLiveStreamDuringAds:e},this.config.licenseKey?{licenseKey:this.config.licenseKey}:{}),this.hls?{mainHlsInstance:this.hls}:{}))):(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Creating Google IMA ad player (Default mode)"),Ul(this.video,{continueLiveStreamDuringAds:e}))},e.prototype.load=function(){return n(this,void 0,void 0,function(){var e,t,i,r=this;return a(this,function(l){switch(l.label){case 0:this.attached||this.attach(),l.label=1;case 1:return l.trys.push([1,3,,4]),[4,this.fetchAdConfiguration()];case 2:return l.sent(),[3,4];case 3:return e=l.sent(),this.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Failed to fetch ad configuration:",e),[3,4];case 4:return this.initializeTracking(),this.shouldUseNativeHls()?(this.nativeHlsMode=!0,this.videoSrcProtection=this.config.src,this.video.src=this.config.src,this.isLiveStream=null!==(t=this.config.lowLatencyMode)&&void 0!==t&&t,this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Using native HLS playback - VOD mode:",{isLive:this.isLiveStream,allowNativeHls:this.config.allowNativeHls,adBehavior:"vod (main video pauses during ads)"}),this.ima.destroy(),this.ima=this.createAdPlayer(!1),this.ima.initialize(),this.config.autoplay?[4,null===(i=this.video.play())||void 0===i?void 0:i.catch(function(){})]:[3,6]):[3,7];case 5:l.sent(),l.label=6;case 6:return[2];case 7:return this.hls=new Cl(s(s({enableWorker:!0,backBufferLength:30,liveDurationInfinity:!0,lowLatencyMode:!!this.config.lowLatencyMode,maxLiveSyncPlaybackRate:this.config.lowLatencyMode?1.5:1},this.config.lowLatencyMode?{liveSyncDuration:2}:{}),{maxBufferLength:30,maxMaxBufferLength:600,maxBufferSize:6e7,maxBufferHole:.5,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,startPosition:-1})),this.hls.on(Cl.Events.MEDIA_ATTACHED,function(){var e;null===(e=r.hls)||void 0===e||e.loadSource(r.config.src)}),this.hls.on(Cl.Events.MANIFEST_PARSED,function(e,t){return n(r,void 0,void 0,function(){var e,t,i,s,r,n,o;return a(this,function(a){switch(a.label){case 0:return this.isLiveStream=null!==(r=null===(s=null===(i=this.hls)||void 0===i?void 0:i.levels)||void 0===s?void 0:s.some(function(e){var t,i;return!0===(null===(t=null==e?void 0:e.details)||void 0===t?void 0:t.live)||"LIVE"===(null===(i=null==e?void 0:e.details)||void 0===i?void 0:i.type)}))&&void 0!==r&&r,this.config.debugAdTiming&&(e=this.shouldContinueLiveStreamDuringAds()?"live (main video continues muted during ads)":"vod (main video pauses during ads)",console.log("[StormcloudVideoPlayer] Stream type detected:",{isLive:this.isLiveStream,allowNativeHls:this.config.allowNativeHls,adBehavior:e})),this.ima.destroy(),this.ima=this.createAdPlayer(this.shouldContinueLiveStreamDuringAds()),this.ima.initialize(),this.bufferedSegmentsCount=0,this.hasInitialBufferCompleted=!1,this.shouldAutoplayAfterBuffering=!!this.config.autoplay,t=null!==(n=this.config.minSegmentsBeforePlay)&&void 0!==n?n:2,this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Waiting for",t,"segments to buffer before playback"),0!==t&&this.config.autoplay?[3,2]:(this.hasInitialBufferCompleted=!0,this.config.autoplay?[4,null===(o=this.video.play())||void 0===o?void 0:o.catch(function(){})]:[3,2]);case 1:a.sent(),a.label=2;case 2:return[2]}})})}),this.hls.on(Cl.Events.FRAG_BUFFERED,function(e,t){return n(r,void 0,void 0,function(){var e,t,i,s=this;return a(this,function(r){switch(r.label){case 0:return this.hasInitialBufferCompleted?[2]:(this.bufferedSegmentsCount++,e=null!==(t=this.config.minSegmentsBeforePlay)&&void 0!==t?t:2,this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Buffered segment ".concat(this.bufferedSegmentsCount,"/").concat(e)),this.bufferedSegmentsCount>=e?(this.hasInitialBufferCompleted=!0,this.shouldAutoplayAfterBuffering?(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Initial buffer complete (".concat(this.bufferedSegmentsCount," segments). Starting playback.")),[4,null===(i=this.video.play())||void 0===i?void 0:i.catch(function(e){s.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Autoplay failed:",e)})]):[3,2]):[3,2]);case 1:r.sent(),r.label=2;case 2:return[2]}})})}),this.hls.on(Cl.Events.FRAG_PARSING_METADATA,function(e,t){((null==t?void 0:t.samples)||[]).map(function(e){return{key:"ID3",value:null==e?void 0:e.data,ptsSeconds:null==e?void 0:e.pts}}).forEach(function(e){return r.onId3Tag(e)})}),this.hls.on(Cl.Events.FRAG_CHANGED,function(e,t){var i,n,a,l,d,c=null==t?void 0:t.frag,u=null==c?void 0:c.tagList;if(Array.isArray(u))try{for(var h=o(u),f=h.next();!f.done;f=h.next()){var g=f.value,p="",m="";if(Array.isArray(g))p=String(null!==(a=g[0])&&void 0!==a?a:""),m=String(null!==(l=g[1])&&void 0!==l?l:"");else if("string"==typeof g){var v=g.indexOf(":");v>=0?(p=g.substring(0,v),m=g.substring(v+1)):(p=g,m="")}if(p)if(p.includes("EXT-X-CUE-OUT")){var y=r.parseCueOutDuration(m),T=s(s({type:"start"},void 0!==y?{durationSeconds:y}:{}),{raw:{tag:p,value:m}});r.onScte35Marker(T)}else if(p.includes("EXT-X-CUE-OUT-CONT")){var E=r.parseCueOutCont(m);T=s(s(s({type:"progress"},void 0!==(null==E?void 0:E.duration)?{durationSeconds:E.duration}:{}),void 0!==(null==E?void 0:E.elapsed)?{ptsSeconds:E.elapsed}:{}),{raw:{tag:p,value:m}});r.onScte35Marker(T)}else if(p.includes("EXT-X-CUE-IN"))r.onScte35Marker({type:"end",raw:{tag:p,value:m}});else if(p.includes("EXT-X-DATERANGE")){var S=r.parseAttributeList(m),A="SCTE35-OUT"in S||void 0!==S["SCTE35-OUT"],b="SCTE35-IN"in S||void 0!==S["SCTE35-IN"],L=String(null!==(d=S.CLASS)&&void 0!==d?d:""),R=r.toNumber(S.DURATION);if(A||/com\.apple\.hls\.cue/i.test(L)){T=s(s({type:"start"},void 0!==R?{durationSeconds:R}:{}),{raw:{tag:p,value:m,attrs:S}});r.onScte35Marker(T)}b&&r.onScte35Marker({type:"end",raw:{tag:p,value:m,attrs:S}})}}}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(Cl.Events.ERROR,function(e,t){var i,s;if(null==t?void 0:t.fatal)switch(t.type){case Cl.ErrorTypes.NETWORK_ERROR:null===(i=r.hls)||void 0===i||i.startLoad();break;case Cl.ErrorTypes.MEDIA_ERROR:null===(s=r.hls)||void 0===s||s.recoverMediaError();break;default:r.destroy()}}),this.hls.attachMedia(this.video),[2]}})})},e.prototype.attach=function(){var e=this;this.attached||(this.attached=!0,this.video.autoplay=!!this.config.autoplay,this.video.muted=!!this.config.muted,this.ima.initialize(),this.ima.updateOriginalMutedState(this.video.muted,this.video.volume),this.ima.on("all_ads_completed",function(){e.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] IMA all_ads_completed event received - ending ad break"),e.inAdBreak&&e.handleAdPodComplete()}),this.ima.on("ad_error",function(t){var i=e.getRemainingAdMs();if(console.error("[AD-ERROR] Ad playback failed",t||""),e.inAdBreak)if(i>500&&e.adPodQueue.length>0){var s=e.findNextPreloadedAd();s?(e.currentAdIndex++,e.playSingleAd(s).catch(function(){e.handleAdFailure()})):e.handleAdFailure()}else e.handleAdFailure();else e.handleAdFailure()}),this.ima.on("content_pause",function(){e.clearAdFailsafeTimer(),e.clearAdRequestWatchdog(),e.activeAdRequestToken=null,e.showAds=!0}),this.ima.on("content_resume",function(){if(e.clearAdFailsafeTimer(),e.clearAdRequestWatchdog(),e.activeAdRequestToken=null,e.showAds=!1,e.inAdBreak){var t=e.getRemainingAdMs();e.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] content_resume event: remaining=".concat(t,"ms, queued ads=").concat(e.adRequestQueue.length)),t>500?e.tryNextAvailableAd():e.handleAdPodComplete()}}),this.timeUpdateHandler=function(){e.onTimeUpdate(e.video.currentTime)},this.video.addEventListener("timeupdate",this.timeUpdateHandler),this.emptiedHandler=function(){if(e.nativeHlsMode&&e.videoSrcProtection&&!e.ima.isAdPlaying()){e.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Video src was cleared, restoring:",e.videoSrcProtection);var t=e.video.currentTime,i=e.video.paused;e.video.src=e.videoSrcProtection,e.video.currentTime=t,i||e.video.play().catch(function(){})}},this.video.addEventListener("emptied",this.emptiedHandler))},e.prototype.shouldUseNativeHls=function(){if("other"===this.getStreamType())return!0;var e=this.video.canPlayType("application/vnd.apple.mpegurl");return!(!this.config.allowNativeHls||!e)},e.prototype.onId3Tag=function(e){"number"==typeof e.ptsSeconds&&this.updatePtsDrift(e.ptsSeconds);var t=this.parseScte35FromId3(e);t&&this.onScte35Marker(t)},e.prototype.parseScte35FromId3=function(e){var t,i,r,n,a=this.decodeId3ValueToText(e.value);if(a){var o=a.match(/EXT-X-CUE-OUT(?::([^\r\n]*))?/i)||a.match(/CUE-OUT(?::([^\r\n]*))?/i);if(o){var l=(null!==(t=o[1])&&void 0!==t?t:"").trim(),d=this.parseCueOutDuration(l);return s(s(s({type:"start"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),void 0!==d?{durationSeconds:d}:{}),{raw:{id3:a}})}var c=a.match(/EXT-X-CUE-OUT-CONT:([^\r\n]*)/i);if(c){l=(null!==(i=c[1])&&void 0!==i?i:"").trim();var u=this.parseCueOutCont(l);return s(s(s({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 s(s({type:"end"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),{raw:{id3:a}});var h=a.match(/EXT-X-DATERANGE:([^\r\n]*)/i);if(h){var f=this.parseAttributeList(null!==(r=h[1])&&void 0!==r?r:""),g="SCTE35-OUT"in f||void 0!==f["SCTE35-OUT"],p="SCTE35-IN"in f||void 0!==f["SCTE35-IN"],m=String(null!==(n=f.CLASS)&&void 0!==n?n:""),v=this.toNumber(f.DURATION);if(g||/com\.apple\.hls\.cue/i.test(m))return s(s(s({type:"start"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),void 0!==v?{durationSeconds:v}:{}),{raw:{id3:a,attrs:f}});if(p)return s(s({type:"end"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),{raw:{id3:a,attrs:f}})}if(/SCTE35-OUT/i.test(a))return s(s({type:"start"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),{raw:{id3:a}});if(/SCTE35-IN/i.test(a))return s(s({type:"end"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),{raw:{id3:a}});if(e.value instanceof Uint8Array){var y=this.parseScte35Binary(e.value);if(y)return y}}},e.prototype.decodeId3ValueToText=function(e){try{if("string"==typeof e)return e;var t=new TextDecoder("utf-8",{fatal:!1}).decode(e);if(t&&/[\x20-\x7E]/.test(t))return t;for(var i="",s=0;s<e.length;s++)i+=String.fromCharCode(e[s]);return i}catch(e){return}},e.prototype.onScte35Marker=function(e){var t,i;if(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] SCTE-35 marker detected:",{type:e.type,ptsSeconds:e.ptsSeconds,durationSeconds:e.durationSeconds,currentTime:this.video.currentTime,raw:e.raw}),"start"!==e.type){if("progress"===e.type&&this.inAdBreak){if(null!=e.durationSeconds&&(this.expectedAdBreakDurationMs=1e3*e.durationSeconds),null!=this.expectedAdBreakDurationMs&&null!=this.currentAdBreakStartWallClockMs){var s=Date.now()-this.currentAdBreakStartWallClockMs,r=Math.max(0,this.expectedAdBreakDurationMs-s);this.scheduleAdStopCountdown(r)}if(!this.ima.isAdPlaying()&&null===this.activeAdRequestToken){var n=this.findCurrentOrNextBreak(1e3*this.video.currentTime),a=this.selectVastTagsForBreak(n)||(this.apiVastTagUrl?[this.apiVastTagUrl]:void 0);if(a&&a.length>0){var o=a[0],l=a.slice(1);this.adPodQueue=l,this.playSingleAd(o).catch(function(){})}}}else if("end"===e.type)return this.inAdBreak=!1,this.expectedAdBreakDurationMs=void 0,this.currentAdBreakStartWallClockMs=void 0,this.clearAdStartTimer(),this.clearAdStopTimer(),this.ima.isAdPlaying()&&this.ima.stop().catch(function(){}),void this.handleAdPodComplete()}else{if(this.inAdBreak)return;this.inAdBreak=!0;var d=null!=e.durationSeconds?1e3*e.durationSeconds:void 0;this.expectedAdBreakDurationMs=d,this.currentAdBreakStartWallClockMs=Date.now();var c=this.isManifestBasedMarker(e),u=null===(t=this.config.immediateManifestAds)||void 0===t||t;if(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Ad start decision:",{isManifestMarker:c,forceImmediate:u,hasPts:"number"==typeof e.ptsSeconds}),c&&u)this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Starting ad immediately (manifest-based)"),this.clearAdStartTimer(),this.handleAdStart(e);else if("number"==typeof e.ptsSeconds){var h=null!==(i=this.config.driftToleranceMs)&&void 0!==i?i:1e3,f=1e3*this.video.currentTime,g=f-this.ptsDriftEmaMs,p=Math.floor(1e3*e.ptsSeconds-g);this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] PTS-based timing calculation:",{nowMs:f,estCurrentPtsMs:g,markerPtsMs:1e3*e.ptsSeconds,deltaMs:p,tolerance:h}),p>h?(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Scheduling ad start in ".concat(p,"ms")),this.scheduleAdStartIn(p)):(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Starting ad immediately (within tolerance)"),this.clearAdStartTimer(),this.handleAdStart(e))}else this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Starting ad immediately (fallback)"),this.clearAdStartTimer(),this.handleAdStart(e);null!=this.expectedAdBreakDurationMs&&this.scheduleAdStopCountdown(this.expectedAdBreakDurationMs)}},e.prototype.parseCueOutDuration=function(e){var t=parseFloat(e.trim());if(!Number.isNaN(t))return t;var i=e.match(/(?:^|[,\s])DURATION\s*=\s*([0-9.]+)/i)||e.match(/Duration\s*=\s*([0-9.]+)/i);if(i&&null!=i[1]){var s=i[1],r=parseFloat(s);return Number.isNaN(r)?void 0:r}},e.prototype.parseCueOutCont=function(e){var t=e.match(/Elapsed\s*=\s*([0-9.]+)/i),i=e.match(/Duration\s*=\s*([0-9.]+)/i),s={};if(t&&null!=t[1]){var r=parseFloat(t[1]);Number.isNaN(r)||(s.elapsed=r)}if(i&&null!=i[1]){var n=parseFloat(i[1]);Number.isNaN(n)||(s.duration=n)}if("elapsed"in s||"duration"in s)return s},e.prototype.parseAttributeList=function(e){for(var t,i,s,r,n={},a=/([A-Z0-9-]+)=(("[^"]*")|([^",]*))(?:,|$)/gi;null!==(r=a.exec(e));){var o=null!==(t=r[1])&&void 0!==t?t:"",l=null!==(s=null!==(i=r[3])&&void 0!==i?i:r[4])&&void 0!==s?s:"";l.startsWith('"')&&l.endsWith('"')&&(l=l.slice(1,-1)),o&&(n[o]=l)}return n},e.prototype.toNumber=function(e){if(null!=e){var t="string"==typeof e?parseFloat(e):Number(e);return Number.isNaN(t)?void 0:t}},e.prototype.isManifestBasedMarker=function(e){var t=e.raw;if(!t)return!1;if(t.tag){var i=String(t.tag);return i.includes("EXT-X-CUE-OUT")||i.includes("EXT-X-CUE-IN")||i.includes("EXT-X-DATERANGE")}return t.id3||t.splice_command_type,!1},e.prototype.parseScte35Binary=function(e){var t=new(function(){function e(e){this.buf=e,this.bytePos=0,this.bitPos=0}return e.prototype.readBits=function(e){for(var t=0;e>0;){if(this.bytePos>=this.buf.length)return t;var i=8-this.bitPos,s=Math.min(e,i);t=t<<s|this.buf[this.bytePos]>>i-s&((1<<s)-1&255),this.bitPos+=s,this.bitPos>=8&&(this.bitPos=0,this.bytePos+=1),e-=s}return t>>>0},e.prototype.skipBits=function(e){this.readBits(e)},e}())(e);if(252===t.readBits(8)){t.readBits(1),t.readBits(1),t.readBits(2);t.readBits(12);t.readBits(8),t.readBits(1),t.readBits(6);t.readBits(1),t.readBits(32);t.readBits(8),t.readBits(12);t.readBits(12);if(5===t.readBits(8)){t.readBits(32);var i=1===t.readBits(1);if(t.readBits(7),!i){var r=1===t.readBits(1),n=1===t.readBits(1),a=1===t.readBits(1),o=1===t.readBits(1);if(t.readBits(4),n&&!o)1===t.readBits(1)?(t.readBits(6),t.readBits(33)):t.readBits(7);else if(!n)for(var l=t.readBits(8),d=0;d<l;d++){if(t.readBits(8),!o)1===t.readBits(1)?(t.readBits(6),t.readBits(33)):t.readBits(7)}var c=void 0;if(a)t.readBits(6),t.readBits(1),c=(4294967296*t.readBits(1)+t.readBits(32))/9e4;if(t.readBits(16),t.readBits(8),t.readBits(8),r)return s(s({type:"start"},void 0!==c?{durationSeconds:c}:{}),{raw:{splice_command_type:5}})}}}},e.prototype.initializeTracking=function(){var e=this;Gl(this.config.licenseKey).then(function(){e.heartbeatInterval=window.setInterval(function(){e.sendHeartbeatIfNeeded()},5e3)}).catch(function(t){e.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Failed to send initial tracking:",t),e.heartbeatInterval=window.setInterval(function(){e.sendHeartbeatIfNeeded()},5e3)})},e.prototype.sendHeartbeatIfNeeded=function(){var e=this,t=Date.now();(!this.lastHeartbeatTime||t-this.lastHeartbeatTime>3e4)&&(this.lastHeartbeatTime=t,Hl(this.config.licenseKey).catch(function(t){e.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Failed to send heartbeat:",t)}))},e.prototype.fetchAdConfiguration=function(){return n(this,void 0,void 0,function(){var e,t,i,s,r,n,o,l,d,c,u,h,f,g,p;return a(this,function(a){switch(a.label){case 0:return e=this.config.vastMode||"default",this.config.debugAdTiming&&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.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Using AdStorm VAST endpoint (adstorm mode):",t),[2]):(this.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] AdStorm mode requires a license key"),[2]):this.config.vastTagUrl?(this.apiVastTagUrl=this.config.vastTagUrl,this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Using custom VAST tag URL:",this.apiVastTagUrl),[2]):(i="https://adstorm.co/api-adstorm-dev/adstorm/ads/web",this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Fetching ad configuration from:",i),s={},this.config.licenseKey&&(s.Authorization="Bearer ".concat(this.config.licenseKey)),[4,fetch(i,{headers:s})]);case 1:return(r=a.sent()).ok?[4,r.json()]:(this.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Failed to fetch ad configuration: ".concat(r.status)),[2]);case 2:return n=a.sent(),(o=null===(u=null===(c=null===(d=n.response)||void 0===d?void 0:d.ima)||void 0===c?void 0:c["publisherdesk.ima"])||void 0===u?void 0:u.payload)?(this.apiVastTagUrl=decodeURIComponent(o),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Extracted VAST tag URL from /ads/web:",this.apiVastTagUrl)):this.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] No VAST tag URL found in /ads/web response"),null!=(l=null===(p=null===(g=null===(f=null===(h=n.response)||void 0===h?void 0:h.options)||void 0===f?void 0:f.vast)||void 0===g?void 0:g.cue_tones)||void 0===p?void 0:p.number_ads)&&l>0&&(this.apiNumberAds=l,this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Number of ads per break from API:",this.apiNumberAds)),[2]}})})},e.prototype.getCurrentAdIndex=function(){return this.currentAdIndex},e.prototype.getTotalAdsInBreak=function(){return this.totalAdsInBreak},e.prototype.generateVastUrlsWithCorrelators=function(e,t){for(var i=[],s=0;s<t;s++)try{var r=new URL(e),n=Date.now(),a=Math.floor(1e6*Math.random()),o="".concat(n).concat(a).concat(s);r.searchParams.set("correlator",o),i.push(r.toString())}catch(t){console.warn("[StormcloudVideoPlayer] Failed to parse VAST URL:",e,t),i.push("".concat(e).concat(e.includes("?")?"&":"?","correlator=").concat(Date.now()).concat(s))}return i},e.prototype.isAdPlaying=function(){return this.inAdBreak&&this.ima.isAdPlaying()},e.prototype.isShowingAds=function(){return this.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.shouldContinueLiveStreamDuringAds=function(){return!this.config.allowNativeHls&&!!this.isLiveStream},e.prototype.handleAdStart=function(e){return n(this,void 0,void 0,function(){var t,i,s,r,n,o,l,d,c;return a(this,function(a){switch(a.label){case 0:if(t=this.findCurrentOrNextBreak(1e3*this.video.currentTime),i=this.selectVastTagsForBreak(t),this.apiVastTagUrl)s=this.apiVastTagUrl;else{if(!(i&&i.length>0&&i[0]))return[2];s=i[0]}if(r=null!=e.durationSeconds?1e3*e.durationSeconds:null==t?void 0:t.durationMs,this.isLiveStream&&null!=r&&r>0?(this.isAdaptiveMode=!0,this.targetAdBreakDurationMs=r,this.fetchedAdDurations.clear(),this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 📺 LIVE MODE: Target duration=".concat(r,"ms | ")+"Will continuously fetch ads during break")):(this.isAdaptiveMode=!1,this.targetAdBreakDurationMs=null,this.fetchedAdDurations.clear(),this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🎬 VOD MODE: Using fixed ad strategy")),this.adPodAllUrls=[],this.preloadingAdUrls.clear(),this.vastToMediaUrlMap.clear(),this.preloadedMediaUrls.clear(),this.preloadingMediaUrls.clear(),this.failedVastUrls.clear(),this.adRequestQueue=[],this.successfulAdRequests=[],this.continuousFetchingActive=!0,this.isShowingPlaceholder=!1,this.placeholderStartTimeMs=null,n=this.video.muted,o=this.video.volume,this.ima.updateOriginalMutedState(n,o),this.inAdBreak=!0,this.currentAdIndex=0,this.totalAdsInBreak=1,this.adPodQueue=[],null==this.expectedAdBreakDurationMs&&null!=r&&(this.expectedAdBreakDurationMs=r,this.currentAdBreakStartWallClockMs=Date.now(),this.scheduleAdStopCountdown(this.expectedAdBreakDurationMs)),this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🚀 Immediately requesting first ad..."),l=this.generateVastUrlsWithCorrelators(s,1),!(d=l[0]))return this.config.debugAdTiming&&console.warn("[CONTINUOUS-FETCH] ⚠️ Failed to generate first ad URL"),this.handleAdPodComplete(),[2];a.label=1;case 1:return a.trys.push([1,4,,5]),[4,this.ima.requestAds(d)];case 2:return a.sent(),this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ✅ First ad request successful, starting playback"),this.successfulAdRequests.push(d),this.currentAdIndex++,this.startContinuousFetching(s),[4,this.ima.play()];case 3:return a.sent(),[3,5];case 4:return c=a.sent(),this.config.debugAdTiming&&console.warn("[CONTINUOUS-FETCH] ⚠️ First ad request failed:",c),this.failedVastUrls.add(d),this.startContinuousFetching(s),this.tryNextAvailableAd(),[3,5];case 5:return[2]}})})},e.prototype.startContinuousFetching=function(e){this.continuousFetchingActive&&(this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🔄 Starting continuous ad fetching loop"),this.continuousFetchLoop(e))},e.prototype.continuousFetchLoop=function(e){return n(this,void 0,void 0,function(){var t,i,s,r,n,o;return a(this,function(a){switch(a.label){case 0:return this.continuousFetchingActive&&this.inAdBreak?this.getRemainingAdMs()<=0?(this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ⏹️ Ad break time expired, stopping fetch loop"),[3,14]):this.adRequestQueue.length>=3?(this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ⏸️ Queue full (".concat(this.adRequestQueue.length,"), pausing fetching...")),[4,new Promise(function(e){return setTimeout(e,2e3)})]):[3,2]:[3,14];case 1:return a.sent(),[3,0];case 2:return(t=this.generateVastUrlsWithCorrelators(e,1)[0])&&!this.failedVastUrls.has(t)?[3,4]:[4,new Promise(function(e){return setTimeout(e,1e3)})];case 3:return a.sent(),[3,0];case 4:this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 📡 Attempting to fetch ad (".concat(this.successfulAdRequests.length+this.adRequestQueue.length+1," total)...")),a.label=5;case 5:return a.trys.push([5,11,,13]),[4,fetch(t,{mode:"cors"})];case 6:if(!(i=a.sent()).ok)throw new Error("Failed to fetch VAST: ".concat(i.status));return[4,i.text()];case 7:return s=a.sent(),r=new DOMParser,n=r.parseFromString(s,"text/xml"),0!==n.querySelectorAll("MediaFile").length?[3,9]:(this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ⚠️ VAST response has no media files, skipping"),this.failedVastUrls.add(t),[4,new Promise(function(e){return setTimeout(e,1e3)})]);case 8:return a.sent(),[3,0];case 9:return this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ✅ Successfully fetched ad, adding to queue (queue size: ".concat(this.adRequestQueue.length+1,")")),this.adRequestQueue.push(t),this.totalAdsInBreak++,[4,new Promise(function(e){return setTimeout(e,500)})];case 10:return a.sent(),[3,13];case 11:return o=a.sent(),this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ❌ Ad fetch failed:",o.message),this.failedVastUrls.add(t),[4,new Promise(function(e){return setTimeout(e,2e3)})];case 12:return a.sent(),[3,13];case 13:return[3,0];case 14:return this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🛑 Continuous fetch loop ended"),[2]}})})},e.prototype.stopContinuousFetching=function(){this.continuousFetchingActive=!1,this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🛑 Stopping continuous ad fetching")},e.prototype.tryNextAvailableAd=function(){return n(this,arguments,void 0,function(e){var t,i,s,r,n=this;return void 0===e&&(e=0),a(this,function(a){switch(a.label){case 0:return(t=this.getRemainingAdMs())<=500?(this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ⏹️ No time remaining, ending ad break"),this.handleAdPodComplete(),[2]):this.adRequestQueue.length>0&&(i=this.adRequestQueue.shift())?(this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🎬 Playing next queued ad (".concat(this.currentAdIndex+1,"/").concat(this.totalAdsInBreak,", ").concat(this.adRequestQueue.length," remaining in queue)")),s=this.video.muted,r=this.video.volume,this.ima.updateOriginalMutedState(s,r),this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🔊 Updated ad audio state: muted=".concat(s,", volume=").concat(r)),this.currentAdIndex++,this.successfulAdRequests.push(i),[4,this.playSingleAd(i).catch(function(){n.tryNextAvailableAd(0)})]):[3,2];case 1:case 4:return a.sent(),[2];case 2:return this.continuousFetchingActive&&e<5&&t>2e3?(this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ⏳ Queue empty but fetching active, waiting... (retry ".concat(e+1,"/").concat(5,")")),[4,new Promise(function(e){return setTimeout(e,1e3)})]):[3,5];case 3:return a.sent(),[4,this.tryNextAvailableAd(e+1)];case 5:return!this.isShowingPlaceholder&&t>1e3?this.showPlaceholderAndWaitForAds():(this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ⏹️ No more ads available, ending ad break"),this.handleAdPodComplete()),[2]}})})},e.prototype.showPlaceholderAndWaitForAds=function(){return n(this,void 0,void 0,function(){var e,t,i,s,r,n,o,l,d=this;return a(this,function(a){switch(a.label){case 0:if(e=this.getRemainingAdMs(),(t=Math.min(this.maxPlaceholderDurationMs,e))<1e3)return this.handleAdPodComplete(),[2];this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ⬛ Showing black placeholder for ".concat(t,"ms while waiting for ads")),this.isShowingPlaceholder=!0,this.placeholderStartTimeMs=Date.now(),this.ima.showPlaceholder(),i=500,s=Math.floor(t/i),r=0,a.label=1;case 1:return r<s?[4,new Promise(function(e){return setTimeout(e,i)})]:[3,6];case 2:return a.sent(),this.inAdBreak?this.adRequestQueue.length>0?(this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ✅ New ad became available during placeholder"),this.isShowingPlaceholder=!1,this.placeholderStartTimeMs=null,this.ima.hidePlaceholder(),n=this.video.muted,o=this.video.volume,this.ima.updateOriginalMutedState(n,o),(l=this.adRequestQueue.shift())?(this.currentAdIndex++,this.successfulAdRequests.push(l),[4,this.playSingleAd(l).catch(function(){d.tryNextAvailableAd()})]):[3,4]):[3,5]:[2];case 3:a.sent(),a.label=4;case 4:return[2];case 5:return r++,[3,1];case 6:return this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ⏰ Placeholder timeout reached, no ads fetched"),this.isShowingPlaceholder=!1,this.placeholderStartTimeMs=null,this.ima.hidePlaceholder(),this.handleAdPodComplete(),[2]}})})},e.prototype.findCurrentOrNextBreak=function(e){var t,i,s,r;try{for(var n=o([]),a=n.next();!a.done;a=n.next()){var l=a.value,d=null!==(s=this.config.driftToleranceMs)&&void 0!==s?s:1e3;l.startTimeMs<=e+d&&(null==r||l.startTimeMs>(r.startTimeMs||0))&&(r=l)}}catch(e){t={error:e}}finally{try{a&&!a.done&&(i=n.return)&&i.call(n)}finally{if(t)throw t.error}}return r},e.prototype.onTimeUpdate=function(e){if(!this.ima.isAdPlaying()){var t=1e3*e,i=this.findBreakForTime(t);i&&this.handleMidAdJoin(i,t)}},e.prototype.handleMidAdJoin=function(e,t){return n(this,void 0,void 0,function(){var i,s,r,n,o,l,d;return a(this,function(a){switch(a.label){case 0:return i=null!==(d=e.durationMs)&&void 0!==d?d:0,s=e.startTimeMs+i,i>0&&t>e.startTimeMs&&t<s?(r=s-t,(n=this.selectVastTagsForBreak(e)||(this.apiVastTagUrl?[this.apiVastTagUrl]:void 0))&&n.length>0?(o=n[0],l=n.slice(1),this.adPodQueue=l,this.ima.updateOriginalMutedState(this.video.muted,this.video.volume),[4,this.playSingleAd(o)]):[3,2]):[3,2];case 1:a.sent(),this.inAdBreak=!0,this.expectedAdBreakDurationMs=r,this.currentAdBreakStartWallClockMs=Date.now(),this.scheduleAdStopCountdown(r),a.label=2;case 2:return[2]}})})},e.prototype.scheduleAdStopCountdown=function(e){var t=this;this.clearAdStopTimer();var i=Math.max(0,Math.floor(e));0!==i?this.adStopTimerId=window.setTimeout(function(){t.ensureAdStoppedByTimer()},i):this.ensureAdStoppedByTimer()},e.prototype.clearAdStopTimer=function(){null!=this.adStopTimerId&&(clearTimeout(this.adStopTimerId),this.adStopTimerId=void 0)},e.prototype.ensureAdStoppedByTimer=function(){var e,t;if(this.inAdBreak){this.adStopTimerId=void 0;var i=this.ima.isAdPlaying(),s=this.adPodQueue.length>0,r=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:6e4,o=0;null!=this.currentAdBreakStartWallClockMs&&(o=Date.now()-this.currentAdBreakStartWallClockMs);var l=null!==(t=this.expectedAdBreakDurationMs)&&void 0!==t?t:0,d=Math.max(0,o-l);(i||s||this.showAds)&&d<a?this.scheduleAdStopCountdown(r):(i&&this.ima.stop().catch(function(){}),this.handleAdPodComplete())}},e.prototype.scheduleAdStartIn=function(e){var t=this;this.clearAdStartTimer();var i=Math.max(0,Math.floor(e));0!==i?this.adStartTimerId=window.setTimeout(function(){t.handleAdStart({type:"start"}).catch(function(){})},i):this.handleAdStart({type:"start"}).catch(function(){})},e.prototype.clearAdStartTimer=function(){null!=this.adStartTimerId&&(clearTimeout(this.adStartTimerId),this.adStartTimerId=void 0)},e.prototype.updatePtsDrift=function(e){var t=1e3*(this.video.currentTime-e);if(Number.isFinite(t)&&!(Math.abs(t)>6e4)){this.ptsDriftEmaMs=.9*this.ptsDriftEmaMs+.1*t}},e.prototype.playSingleAd=function(e){return n(this,void 0,void 0,function(){var t,i,s;return a(this,function(r){switch(r.label){case 0:if(this.ima.isAdPlaying())return[2];if(this.failedVastUrls.has(e))return console.warn("[AD-ERROR] Skipping already-failed VAST URL:",e.substring(0,60)),this.handleAdFailure(),[2];t=++this.adRequestTokenCounter,this.activeAdRequestToken=t,this.startAdRequestWatchdog(t),r.label=1;case 1:return r.trys.push([1,7,,8]),[4,this.ima.requestAds(e)];case 2:if(r.sent(),this.clearAdRequestWatchdog(),this.activeAdRequestToken!==t)return[2];r.label=3;case 3:return r.trys.push([3,5,,6]),this.startAdFailsafeTimer(t),[4,this.ima.play()];case 4:return r.sent(),[3,6];case 5:return i=r.sent(),console.error("[AD-ERROR] Failed to play ad:",i),this.failedVastUrls.add(e),this.clearAdFailsafeTimer(),this.activeAdRequestToken===t&&(this.activeAdRequestToken=null),this.handleAdFailure(),[2];case 6:return[3,8];case 7:return s=r.sent(),console.error("[AD-ERROR] Ad request failed:",null==s?void 0:s.message),this.failedVastUrls.add(e),this.clearAdRequestWatchdog(),this.clearAdFailsafeTimer(),this.activeAdRequestToken===t&&(this.activeAdRequestToken=null),this.handleAdFailure(),[3,8];case 8:return[2]}})})},e.prototype.handleAdPodComplete=function(){var e;this.clearAdRequestWatchdog(),this.clearAdFailsafeTimer(),this.activeAdRequestToken=null,this.stopContinuousFetching(),this.isShowingPlaceholder&&(this.ima.hidePlaceholder(),this.isShowingPlaceholder=!1,this.placeholderStartTimeMs=null),this.preloadingAdUrls.clear(),this.vastToMediaUrlMap.clear(),this.preloadedMediaUrls.clear(),this.preloadingMediaUrls.clear(),this.adRequestQueue=[],this.successfulAdRequests=[],this.inAdBreak=!1,this.expectedAdBreakDurationMs=void 0,this.currentAdBreakStartWallClockMs=void 0,this.clearAdStartTimer(),this.clearAdStopTimer(),this.adPodQueue=[],this.adPodAllUrls=[],this.showAds=!1,this.currentAdIndex=0,this.totalAdsInBreak=0,this.ima.stop().catch(function(){});var t=this.ima.getOriginalMutedState(),i=this.ima.getOriginalVolume();this.video.muted!==t&&(this.video.muted=t),Math.abs(this.video.volume-i)>.01&&(this.video.volume=i),!this.shouldContinueLiveStreamDuringAds()&&this.video.paused&&(null===(e=this.video.play())||void 0===e||e.catch(function(){}))},e.prototype.handleAdFailure=function(){var e=this.getRemainingAdMs();this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] Ad failure: remaining=".concat(e,"ms, queued ads=").concat(this.adRequestQueue.length)),e>500?this.tryNextAvailableAd():(console.error("[AD-ERROR] Ad failed and no time remaining. Failed URLs:",this.failedVastUrls.size),this.handleAdPodComplete())},e.prototype.startAdRequestWatchdog=function(e){var t,i=this;this.clearAdRequestWatchdog();var s=null!==(t=this.config.adFailsafeTimeoutMs)&&void 0!==t?t:1e4;this.adRequestWatchdogToken=e,this.adRequestWatchdogId=window.setTimeout(function(){i.adRequestWatchdogToken===e&&(i.adRequestWatchdogId=void 0,i.adRequestWatchdogToken=null,i.activeAdRequestToken===e&&(i.activeAdRequestToken=null),i.logAdState("ad_request_timeout",{token:e,timeoutMs:s}),i.handleAdFailure())},s),this.logAdState("ad_request_watchdog_started",{token:e,timeoutMs:s})},e.prototype.clearAdRequestWatchdog=function(){null!=this.adRequestWatchdogId&&(clearTimeout(this.adRequestWatchdogId),this.adRequestWatchdogId=void 0),null!=this.adRequestWatchdogToken&&(this.logAdState("ad_request_watchdog_cleared",{token:this.adRequestWatchdogToken}),this.adRequestWatchdogToken=null)},e.prototype.startAdFailsafeTimer=function(e){var t,i=this;this.clearAdFailsafeTimer();var s=null!==(t=this.config.adFailsafeTimeoutMs)&&void 0!==t?t:1e4;this.adFailsafeToken=e,this.adFailsafeTimerId=window.setTimeout(function(){i.adFailsafeToken===e&&(i.adFailsafeTimerId=void 0,i.adFailsafeToken=null,i.activeAdRequestToken===e&&(i.activeAdRequestToken=null),i.logAdState("ad_failsafe_triggered",{token:e,failsafeMs:s,videoPaused:i.video.paused,imaAdPlaying:i.ima.isAdPlaying()}),i.handleAdFailure())},s),this.logAdState("ad_failsafe_started",{token:e,failsafeMs:s})},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.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.logAdState=function(e,t){void 0===t&&(t={}),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer][AdState]",s({event:e,timestamp:(new Date).toISOString(),showAds:this.showAds,adPlaying:this.ima.isAdPlaying(),inAdBreak:this.inAdBreak,activeAdRequestToken:this.activeAdRequestToken},t))},e.prototype.fetchAndParseVastXml=function(e){return n(this,void 0,void 0,function(){var t,i,s;return a(this,function(r){switch(r.label){case 0:return r.trys.push([0,3,,4]),[4,fetch(e,{mode:"cors"})];case 1:if(!(t=r.sent()).ok)throw new Error("Failed to fetch VAST: ".concat(t.status));return[4,t.text()];case 2:return i=r.sent(),[2,this.extractMediaUrlsFromVast(i)];case 3:return s=r.sent(),this.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Failed to fetch/parse VAST XML: ".concat(e),s),[2,[]];case 4:return[2]}})})},e.prototype.extractMediaUrlsFromVast=function(e){var t,i,s,r=[];try{var n=(new DOMParser).parseFromString(e,"text/xml").querySelectorAll("MediaFile");try{for(var a=o(Array.from(n)),l=a.next();!l.done;l=a.next()){var d=null===(s=l.value.textContent)||void 0===s?void 0:s.trim();if(d){var c=d.toLowerCase();(c.endsWith(".mp4")||c.endsWith(".webm")||c.endsWith(".mov")||c.endsWith(".avi")||c.includes(".mp4?")||c.includes(".webm?")||c.includes("/mp4/")||c.includes("type=video"))&&r.push(d)}}}catch(e){t={error:e}}finally{try{l&&!l.done&&(i=a.return)&&i.call(a)}finally{if(t)throw t.error}}this.config.debugAdTiming&&r.length>0&&console.log("[StormcloudVideoPlayer] Extracted ".concat(r.length," media URLs from VAST:"),r)}catch(e){this.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Failed to parse VAST XML:",e)}return r},e.prototype.fetchVastDuration=function(e){return n(this,void 0,void 0,function(){var t,i,s,r,n,o,l,d;return a(this,function(a){switch(a.label){case 0:return a.trys.push([0,3,,4]),[4,fetch(e,{mode:"cors"})];case 1:return(t=a.sent()).ok?[4,t.text()]:(this.config.debugAdTiming&&console.warn("[ADAPTIVE-POD] Failed to fetch VAST: ".concat(t.status)),[2,null]);case 2:return i=a.sent(),s=new DOMParser,r=s.parseFromString(i,"text/xml"),(n=null===(d=r.querySelector("Duration"))||void 0===d?void 0:d.textContent)?(o=n.split(":"),[2,3600*parseInt(o[0]||"0",10)+60*parseInt(o[1]||"0",10)+parseInt(o[2]||"0",10)]):(this.config.debugAdTiming&&console.warn("[ADAPTIVE-POD] No Duration element found in VAST"),[2,null]);case 3:return l=a.sent(),this.config.debugAdTiming&&console.warn("[ADAPTIVE-POD] Error fetching VAST duration from ".concat(e,":"),l),[2,null];case 4:return[2]}})})},e.prototype.calculateAdditionalAdsNeeded=function(){var e,t;if(!this.isAdaptiveMode||null===this.targetAdBreakDurationMs)return 0;var i=0;try{for(var s=o(this.fetchedAdDurations.values()),r=s.next();!r.done;r=s.next()){i+=1e3*r.value}}catch(t){e={error:t}}finally{try{r&&!r.done&&(t=s.return)&&t.call(s)}finally{if(e)throw e.error}}var n=this.fetchedAdDurations.size,a=n>0?i/n:3e4,l=this.adPodAllUrls.length-n,d=l*a,c=i+d,u=this.targetAdBreakDurationMs-c;if(u<=0)return this.config.debugAdTiming&&console.log("[ADAPTIVE-POD] ✅ Target duration met: Fetched=".concat(i,"ms + Queued(").concat(l," ads)=").concat(d,"ms = ").concat(c,"ms / Target=").concat(this.targetAdBreakDurationMs,"ms")),0;var h=Math.ceil(u/a);return this.config.debugAdTiming&&console.log("[ADAPTIVE-POD] 📊 Need ".concat(h," more ads | ")+"Fetched: ".concat(i,"ms (").concat(n," ads) | ")+"Queued: ".concat(d,"ms (").concat(l," ads) | ")+"Target: ".concat(this.targetAdBreakDurationMs,"ms | ")+"Remaining: ".concat(u,"ms | ")+"Avg duration: ".concat(a,"ms")),h},e.prototype.addAdaptiveAdsToQueue=function(){return n(this,void 0,void 0,function(){var e,t,i,s;return a(this,function(r){return this.isAdaptiveMode&&this.apiVastTagUrl?((e=this.calculateAdditionalAdsNeeded())<=0||(t=this.generateVastUrlsWithCorrelators(this.apiVastTagUrl,e),this.config.debugAdTiming&&console.log("[ADAPTIVE-POD] 🔄 Adding ".concat(t.length," additional VAST URLs to queue (will be preloaded sequentially)")),(i=this.adPodAllUrls).push.apply(i,d([],l(t),!1)),(s=this.adPodQueue).push.apply(s,d([],l(t),!1)),this.totalAdsInBreak+=t.length),[2]):[2]})})},e.prototype.preloadMediaFile=function(e){return n(this,void 0,void 0,function(){var t,i;return a(this,function(s){switch(s.label){case 0:if(this.preloadedMediaUrls.has(e))return[2];if(this.preloadingMediaUrls.has(e))return[2];this.preloadingMediaUrls.add(e),s.label=1;case 1:return s.trys.push([1,3,4,5]),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Preloading video file: ".concat(e)),[4,fetch(e,{mode:"cors",method:"GET",headers:{Range:"bytes=0-1048576"}})];case 2:return((t=s.sent()).ok||206===t.status)&&(this.preloadedMediaUrls.add(e),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Successfully preloaded video file: ".concat(e))),[3,5];case 3:return i=s.sent(),this.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Failed to preload video file: ".concat(e),i),[3,5];case 4:return this.preloadingMediaUrls.delete(e),[7];case 5:return[2]}})})},e.prototype.preloadAllAdsInBackground=function(){return n(this,void 0,void 0,function(){var e,t,i,s,r,n,l,d,c,u,h,f=this;return a(this,function(a){switch(a.label){case 0:if(0===this.adPodAllUrls.length)return[2];if(!this.isAdaptiveMode)return[3,7];this.config.debugAdTiming&&console.log("[ADAPTIVE-POD] 🔄 Starting sequential preload of remaining ads"),e=new Set;try{for(t=o(this.adPodAllUrls),i=t.next();!i.done;i=t.next())s=i.value,((null===(h=(u=this.ima).hasPreloadedAd)||void 0===h?void 0:h.call(u,s))||this.fetchedAdDurations.has(s))&&e.add(s)}catch(e){d={error:e}}finally{try{i&&!i.done&&(c=t.return)&&c.call(t)}finally{if(d)throw d.error}}this.config.debugAdTiming&&e.size>0&&console.log("[ADAPTIVE-POD] 📦 Skipping ".concat(e.size," already-preloaded ads")),a.label=1;case 1:if(r=this.adPodAllUrls.find(function(t){return!e.has(t)}),!r)return this.config.debugAdTiming&&console.log("[ADAPTIVE-POD] ✅ All queued ads processed (".concat(e.size," total)")),[3,6];e.add(r),this.config.debugAdTiming&&console.log("[ADAPTIVE-POD] 📥 Preloading ad ".concat(e.size,"/").concat(this.adPodAllUrls.length,"...")),a.label=2;case 2:return a.trys.push([2,4,,5]),[4,this.preloadSingleAd(r)];case 3:return a.sent(),[3,5];case 4:return n=a.sent(),this.config.debugAdTiming&&console.warn("[ADAPTIVE-POD] ⚠️ Preload failed for ad ".concat(e.size,":"),n),[3,5];case 5:return 0===this.calculateAdditionalAdsNeeded()?(this.config.debugAdTiming&&console.log("[ADAPTIVE-POD] ✅ Target duration reached (".concat(e.size," ads preloaded), stopping")),[3,6]):[3,1];case 6:return this.config.debugAdTiming&&console.log("[ADAPTIVE-POD] ✅ Sequential preloading completed (".concat(e.size," ads ready)")),[3,9];case 7:return this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Starting parallel preload of ".concat(this.adPodAllUrls.length," ads")),l=this.adPodAllUrls.map(function(e){return f.preloadSingleAd(e).catch(function(t){f.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Preload failed for ".concat(e,":"),t)})}),[4,Promise.all(l)];case 8:a.sent(),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Background preloading completed for all ads"),a.label=9;case 9:return[2]}})})},e.prototype.preloadSingleAd=function(e){return n(this,void 0,void 0,function(){var t,i,s,r,n=this;return a(this,function(a){switch(a.label){case 0:if(!e)return[2];a.label=1;case 1:return a.trys.push([1,11,,12]),!this.isAdaptiveMode||this.fetchedAdDurations.has(e)?[3,4]:[4,this.fetchVastDuration(e)];case 2:return null===(t=a.sent())?[3,4]:(this.fetchedAdDurations.set(e,t),this.config.debugAdTiming&&console.log("[ADAPTIVE-POD] ✓ Fetched ad duration: ".concat(t,"s (").concat(this.fetchedAdDurations.size," ads fetched so far)")),[4,this.addAdaptiveAdsToQueue()]);case 3:a.sent(),a.label=4;case 4:return!this.ima.preloadAds||this.ima.hasPreloadedAd(e)||this.preloadingAdUrls.has(e)?[3,6]:(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Preloading VAST: ".concat(e)),this.preloadingAdUrls.add(e),[4,this.ima.preloadAds(e).then(function(){n.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] IMA VAST preload complete: ".concat(e))}).catch(function(t){n.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] IMA VAST preload failed: ".concat(e),t)}).finally(function(){n.preloadingAdUrls.delete(e)})]);case 5:a.sent(),a.label=6;case 6:return(i=this.vastToMediaUrlMap.get(e))?[3,8]:(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Fetching and parsing VAST to extract media URLs: ".concat(e)),[4,this.fetchAndParseVastXml(e)]);case 7:i=a.sent(),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Extracted ".concat(i.length," media URLs:"),i),i.length>0&&this.vastToMediaUrlMap.set(e,i),a.label=8;case 8:return i&&i.length>0?!(s=i[0])||this.preloadedMediaUrls.has(s)?[3,10]:[4,this.preloadMediaFile(s)]:[3,10];case 9:a.sent(),a.label=10;case 10:return[3,12];case 11:return r=a.sent(),this.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Failed to preload ad: ".concat(e),r),[3,12];case 12:return[2]}})})},e.prototype.findNextPreloadedAd=function(){for(var e,t,i,s=0;s<this.adPodQueue.length;s++){var r=this.adPodQueue[s];if(r)if(this.failedVastUrls.has(r))console.warn("[AD-ERROR] Skipping failed URL in queue");else{var n=null!==(i=null===(t=(e=this.ima).hasPreloadedAd)||void 0===t?void 0:t.call(e,r))&&void 0!==i&&i,a=this.vastToMediaUrlMap.get(r),o=!!(a&&a.length>0)&&this.preloadedMediaUrls.has(a[0]);if(n||o)return this.adPodQueue.splice(0,s+1),r}}},e.prototype.getRemainingAdMs=function(){if(null==this.expectedAdBreakDurationMs||null==this.currentAdBreakStartWallClockMs)return 0;var e=Date.now()-this.currentAdBreakStartWallClockMs;return Math.max(0,this.expectedAdBreakDurationMs-e)},e.prototype.findBreakForTime=function(e){var t,i;try{for(var s=o([]),r=s.next();!r.done;r=s.next()){var n=r.value,a=(n.startTimeMs||0)+(n.durationMs||0);if(e>=(n.startTimeMs||0)&&(!n.durationMs||e<a))return n}}catch(e){t={error:e}}finally{try{r&&!r.done&&(i=s.return)&&i.call(s)}finally{if(t)throw t.error}}},e.prototype.toggleMute=function(){if(this.ima.isAdPlaying()){var e=!this.isMuted();this.ima.updateOriginalMutedState(e,this.video.volume),this.ima.setAdVolume(e?0:1),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Mute toggle during ad - immediately applied:",e)}else this.video.muted=!this.video.muted,this.ima.updateOriginalMutedState(this.video.muted,this.video.volume),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Muted:",this.video.muted)},e.prototype.toggleFullscreen=function(){var e=this;return new Promise(function(t,i){if(document.fullscreenElement)document.exitFullscreen().then(function(){e.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Exited fullscreen"),t()}).catch(function(t){e.config.debugAdTiming&&console.error("[StormcloudVideoPlayer] Exit fullscreen error:",t),i(t)});else{var s=e.video.parentElement;if(!s)return void i(new Error("No parent container found for fullscreen"));s.requestFullscreen().then(function(){e.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Entered fullscreen"),t()}).catch(function(t){e.config.debugAdTiming&&console.error("[StormcloudVideoPlayer] Fullscreen error:",t),i(t)})}})},e.prototype.isMuted=function(){return this.ima.isAdPlaying()?(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] isMuted() override during ad playback -> false"),!1):this.video.muted},e.prototype.setMuted=function(e){var t=this.ima.isAdPlaying();if(t&&e===this.video.muted)this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] setMuted reflective update during ad ignored",{muted:e});else{if(this.video.muted=e,t)return this.ima.updateOriginalMutedState(e,this.video.volume),this.ima.setAdVolume(e?0:1),void(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] setMuted applied during ad",{muted:e}));this.ima.updateOriginalMutedState(e,this.video.volume),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] setMuted called:",e)}},e.prototype.setVolume=function(e){var t=Math.max(0,Math.min(1,e));this.ima.isAdPlaying()?(this.ima.setAdVolume(t),this.ima.updateOriginalMutedState(0===t,t),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] setVolume applied during ad",{volume:t})):(this.video.volume=t,this.video.muted=0===t,this.ima.updateOriginalMutedState(0===t,t),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] setVolume called:",t))},e.prototype.isFullscreen=function(){return!!document.fullscreenElement},e.prototype.isLive=function(){return this.isLiveStream},Object.defineProperty(e.prototype,"videoElement",{get:function(){return this.video},enumerable:!1,configurable:!0}),e.prototype.resize=function(){if(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Resizing player"),this.ima&&this.ima.isAdPlaying()){var e=this.video.clientWidth||640,t=this.video.clientHeight||360;this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Resizing ads manager to ".concat(e,"x").concat(t)),this.ima.resize(e,t)}},e.prototype.destroy=function(){var e,t;this.stopContinuousFetching(),this.clearAdStartTimer(),this.clearAdStopTimer(),this.clearAdFailsafeTimer(),this.clearAdRequestWatchdog(),this.timeUpdateHandler&&(this.video.removeEventListener("timeupdate",this.timeUpdateHandler),delete this.timeUpdateHandler),this.emptiedHandler&&(this.video.removeEventListener("emptied",this.emptiedHandler),delete this.emptiedHandler),this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=void 0),null===(e=this.hls)||void 0===e||e.destroy(),null===(t=this.ima)||void 0===t||t.destroy(),this.preloadingAdUrls.clear(),this.vastToMediaUrlMap.clear(),this.preloadedMediaUrls.clear(),this.preloadingMediaUrls.clear(),this.adPodAllUrls=[],this.adRequestQueue=[],this.successfulAdRequests=[]},e}(),Wl={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},ql=b.createContext&&b.createContext(Wl),Yl=["attr","size","title"];function zl(e,t){if(null==e)return{};var i,s,r=function(e,t){if(null==e)return{};var i={};for(var s in e)if(Object.prototype.hasOwnProperty.call(e,s)){if(t.indexOf(s)>=0)continue;i[s]=e[s]}return i}(e,t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);for(s=0;s<n.length;s++)i=n[s],t.indexOf(i)>=0||Object.prototype.propertyIsEnumerable.call(e,i)&&(r[i]=e[i])}return r}function Xl(){return Xl=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&(e[s]=i[s])}return e},Xl.apply(this,arguments)}function Ql(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,s)}return i}function Jl(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Ql(Object(i),!0).forEach(function(t){Zl(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Ql(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}function Zl(e,t,i){var s;return(t="symbol"==typeof(s=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var s=i.call(e,t||"default");if("object"!=typeof s)return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(t,"string"))?s:s+"")in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function ed(e){return e&&e.map((e,t)=>b.createElement(e.tag,Jl({key:t},e.attr),ed(e.child)))}function td(e){return t=>b.createElement(id,Xl({attr:Jl({},e.attr)},t),ed(e.child))}function id(e){var t=t=>{var i,{attr:s,size:r,title:n}=e,a=zl(e,Yl),o=r||t.size||"1em";return t.className&&(i=t.className),e.className&&(i=(i?i+" ":"")+e.className),b.createElement("svg",Xl({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},t.attr,s,a,{className:i,style:Jl(Jl({color:e.color||t.color},t.style),e.style),height:o,width:o,xmlns:"http://www.w3.org/2000/svg"}),n&&b.createElement("title",null,n),e.children)};return void 0!==ql?b.createElement(ql.Consumer,null,e=>t(e)):t(Wl)}function sd(e){return td({tag:"svg",attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M436 192H312c-13.3 0-24-10.7-24-24V44c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v84h84c6.6 0 12 5.4 12 12v40c0 6.6-5.4 12-12 12zm-276-24V44c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v84H12c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h124c13.3 0 24-10.7 24-24zm0 300V344c0-13.3-10.7-24-24-24H12c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h84v84c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm192 0v-84h84c6.6 0 12-5.4 12-12v-40c0-6.6-5.4-12-12-12H312c-13.3 0-24 10.7-24 24v124c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12z"},child:[]}]})(e)}function rd(e){return td({tag:"svg",attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M0 180V56c0-13.3 10.7-24 24-24h124c6.6 0 12 5.4 12 12v40c0 6.6-5.4 12-12 12H64v84c0 6.6-5.4 12-12 12H12c-6.6 0-12-5.4-12-12zM288 44v40c0 6.6 5.4 12 12 12h84v84c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12V56c0-13.3-10.7-24-24-24H300c-6.6 0-12 5.4-12 12zm148 276h-40c-6.6 0-12 5.4-12 12v84h-84c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h124c13.3 0 24-10.7 24-24V332c0-6.6-5.4-12-12-12zM160 468v-40c0-6.6-5.4-12-12-12H64v-84c0-6.6-5.4-12-12-12H12c-6.6 0-12 5.4-12 12v124c0 13.3 10.7 24 24 24h124c6.6 0 12-5.4 12-12z"},child:[]}]})(e)}function nd(e){return td({tag:"svg",attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M144 479H48c-26.5 0-48-21.5-48-48V79c0-26.5 21.5-48 48-48h96c26.5 0 48 21.5 48 48v352c0 26.5-21.5 48-48 48zm304-48V79c0-26.5-21.5-48-48-48h-96c-26.5 0-48 21.5-48 48v352c0 26.5 21.5 48 48 48h96c26.5 0 48-21.5 48-48z"},child:[]}]})(e)}function ad(e){return td({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 od(e){return td({tag:"svg",attr:{viewBox:"0 0 512 512"},child:[{tag:"path",attr:{d:"M304 48c0 26.51-21.49 48-48 48s-48-21.49-48-48 21.49-48 48-48 48 21.49 48 48zm-48 368c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48-21.49-48-48-48zm208-208c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48-21.49-48-48-48zM96 256c0-26.51-21.49-48-48-48S0 229.49 0 256s21.49 48 48 48 48-21.49 48-48zm12.922 99.078c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48c0-26.509-21.491-48-48-48zm294.156 0c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48c0-26.509-21.49-48-48-48zM108.922 60.922c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48-21.491-48-48-48z"},child:[]}]})(e)}function ld(e){return td({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 dd(e){return td({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 cd(e){return td({tag:"svg",attr:{viewBox:"0 0 576 512"},child:[{tag:"path",attr:{d:"M215.03 71.05L126.06 160H24c-13.26 0-24 10.74-24 24v144c0 13.25 10.74 24 24 24h102.06l88.97 88.95c15.03 15.03 40.97 4.47 40.97-16.97V88.02c0-21.46-25.96-31.98-40.97-16.97zm233.32-51.08c-11.17-7.33-26.18-4.24-33.51 6.95-7.34 11.17-4.22 26.18 6.95 33.51 66.27 43.49 105.82 116.6 105.82 195.58 0 78.98-39.55 152.09-105.82 195.58-11.17 7.32-14.29 22.34-6.95 33.5 7.04 10.71 21.93 14.56 33.51 6.95C528.27 439.58 576 351.33 576 256S528.27 72.43 448.35 19.97zM480 256c0-63.53-32.06-121.94-85.77-156.24-11.19-7.14-26.03-3.82-33.12 7.46s-3.78 26.21 7.41 33.36C408.27 165.97 432 209.11 432 256s-23.73 90.03-63.48 115.42c-11.19 7.14-14.5 22.07-7.41 33.36 6.51 10.36 21.12 15.14 33.12 7.46C447.94 377.94 480 319.54 480 256zm-141.77-76.87c-11.58-6.33-26.19-2.16-32.61 9.45-6.39 11.61-2.16 26.2 9.45 32.61C327.98 228.28 336 241.63 336 256c0 14.38-8.02 27.72-20.92 34.81-11.61 6.41-15.84 21-9.45 32.61 6.43 11.66 21.05 15.8 32.61 9.45 28.23-15.55 45.77-45 45.77-76.88s-17.54-61.32-45.78-76.86z"},child:[]}]})(e)}var ud=["src","allowNativeHls","licenseKey","lowLatencyMode","driftToleranceMs","vastMode"],hd=b.memo(function(e){var t=e.src,i=e.autoplay,n=e.muted,a=e.lowLatencyMode,o=e.allowNativeHls,d=e.driftToleranceMs,c=e.immediateManifestAds,u=e.debugAdTiming,h=e.showCustomControls,f=e.hideLoadingIndicator,g=e.onVolumeToggle,p=e.onFullscreenToggle,m=e.onControlClick,v=e.onReady,y=e.wrapperClassName,T=e.wrapperStyle,E=e.className,L=e.style,R=e.controls,I=e.playsInline,k=e.preload,w=e.poster,P=e.children,D=e.licenseKey,x=e.vastMode,C=e.vastTagUrl,_=e.adPlayerType,M=e.minSegmentsBeforePlay,O=r(e,["src","autoplay","muted","lowLatencyMode","allowNativeHls","driftToleranceMs","immediateManifestAds","debugAdTiming","showCustomControls","hideLoadingIndicator","onVolumeToggle","onFullscreenToggle","onControlClick","onReady","wrapperClassName","wrapperStyle","className","style","controls","playsInline","preload","poster","children","licenseKey","vastMode","vastTagUrl","adPlayerType","minSegmentsBeforePlay"]),F=A.useRef(null),U=A.useRef(null),N=A.useRef(null),B=l(b.useState({showAds:!1,currentIndex:0,totalAds:0}),2),$=B[0],V=B[1],G=l(b.useState(!0),2),H=G[0],K=G[1],j=l(b.useState(!1),2),W=j[0],q=j[1],Y=l(b.useState(!1),2),z=Y[0],X=Y[1],Q=l(b.useState(!1),2),J=Q[0],Z=Q[1],ee=l(b.useState(0),2),te=ee[0],ie=ee[1],se=l(b.useState(0),2),re=se[0],ne=se[1],ae=l(b.useState(1),2),oe=ae[0],le=ae[1],de=l(b.useState(1),2),ce=de[0],ue=de[1],he=l(b.useState(!1),2),fe=he[0],ge=he[1],pe=l(b.useState(!1),2),me=pe[0],ve=pe[1],ye=l(b.useState(!0),2),Te=ye[0],Ee=ye[1],Se=l(b.useState(!1),2),Ae=Se[0],be=Se[1],Le=l(b.useState(!1),2),Re=Le[0],Ie=Le[1],ke=l(b.useState(!1),2),we=ke[0],Pe=ke[1],De=l(b.useState("undefined"!=typeof window?window.innerWidth:1920),2),xe=De[0],Ce=De[1],_e=l(b.useState("undefined"!=typeof window&&window.innerHeight>window.innerWidth),2),Me=_e[0],Oe=_e[1],Fe=xe<480?.7:xe<768?.8:xe<1024?.9:1,Ue=function(e){if(!isFinite(e))return"0:00:00";var t=Math.floor(e/3600),i=Math.floor(e%3600/60),s=Math.floor(e%60);return"".concat(t,":").concat(i.toString().padStart(2,"0"),":").concat(s.toString().padStart(2,"0"))},Ne=function(e){if(U.current&&isFinite(e)){var t=Math.max(0,Math.min(1,e));U.current.setVolume(t)}},Be=(null==t?void 0:t.toLowerCase().includes(".m3u8"))||(null==t?void 0:t.toLowerCase().includes("/hls/")),$e=h&&(!Be||o),Ve=A.useMemo(function(){return ud.map(function(t){return"".concat(t,":").concat(e[t])}).join("|")},[t,o,D,a,d,x]);return A.useEffect(function(){if("undefined"!=typeof window){var e=F.current;if(e&&t){if(!D)return Pe(!0),Ee(!1),void console.warn("StormcloudVideoPlayer: License key is required but not provided. Please set the licenseKey prop to use the player.");if(Pe(!1),u&&console.log("[StormcloudUI] Initializing player, isLoading=true"),U.current){try{U.current.destroy()}catch(e){}U.current=null}var s={src:t,videoElement:e};void 0!==i&&(s.autoplay=i),void 0!==n&&(s.muted=n),void 0!==a&&(s.lowLatencyMode=a),void 0!==o&&(s.allowNativeHls=o),void 0!==d&&(s.driftToleranceMs=d),void 0!==c&&(s.immediateManifestAds=c),void 0!==u&&(s.debugAdTiming=u),void 0!==h&&(s.showCustomControls=h),void 0!==g&&(s.onVolumeToggle=g),void 0!==p&&(s.onFullscreenToggle=p),void 0!==m&&(s.onControlClick=m),void 0!==D&&(s.licenseKey=D),void 0!==x&&(s.vastMode=x),void 0!==C&&(s.vastTagUrl=C),void 0!==_&&(s.adPlayerType=_),void 0!==M&&(s.minSegmentsBeforePlay=M);var r=new jl(s);return U.current=r,r.load().then(function(){var e=r.shouldShowNativeControls();K(e),u&&console.log("[StormcloudUI] Player loaded successfully, waiting for video ready"),null==v||v(r)}).catch(function(e){console.error("StormcloudVideoPlayer: Failed to load player:",e),Ee(!1),null==v||v(r)}),function(){try{r.destroy()}catch(e){}U.current=null}}}},[Ve]),A.useEffect(function(){if(U.current)try{void 0!==i&&U.current.videoElement&&(U.current.videoElement.autoplay=i),void 0===n||U.current.isShowingAds()||U.current.setMuted(n)}catch(e){console.warn("Failed to update player properties:",e)}},[i,n]),A.useEffect(function(){if(U.current){var e=setInterval(function(){if(U.current){var e=U.current.isShowingAds(),t=U.current.getCurrentAdIndex(),i=U.current.getTotalAdsInBreak();V(function(s){return s.showAds!==e||s.currentIndex!==t||s.totalAds!==i?{showAds:e,currentIndex:t,totalAds:i}:s})}},100);return function(){return clearInterval(e)}}},[]),A.useEffect(function(){if("undefined"!=typeof window&&U.current){var e=function(){U.current&&F.current&&"function"==typeof U.current.resize&&U.current.resize(),Ce(window.innerWidth),Oe(window.innerHeight>window.innerWidth)};return window.addEventListener("resize",e),function(){return window.removeEventListener("resize",e)}}},[]),A.useEffect(function(){if(U.current&&F.current){var e=setInterval(function(){var e;if(U.current&&F.current){q(U.current.isMuted()),Z(!F.current.paused);var t=F.current.currentTime;ie(isFinite(t)?t:0);var i=F.current.duration;ne(isFinite(i)?i:0);var s=F.current.volume;le(isFinite(s)?Math.max(0,Math.min(1,s)):1);var r=F.current.playbackRate;ue(isFinite(r)&&r>0?r:1)}X(document.fullscreenElement===(null===(e=F.current)||void 0===e?void 0:e.parentElement))},200),t=function(){var e;X(document.fullscreenElement===(null===(e=F.current)||void 0===e?void 0:e.parentElement))};return document.addEventListener("fullscreenchange",t),function(){clearInterval(e),document.removeEventListener("fullscreenchange",t)}}},[]),A.useEffect(function(){if(F.current){var e=function(){var e;F.current&&F.current.offsetHeight;u&&console.log("[StormcloudUI] Video event: loadedmetadata, readyState:",null===(e=F.current)||void 0===e?void 0:e.readyState)},t=function(){var e;u&&console.log("[StormcloudUI] Video event: loadeddata, readyState:",null===(e=F.current)||void 0===e?void 0:e.readyState)},i=function(){var e;u&&console.log("[StormcloudUI] Video event: loadstart, readyState:",null===(e=F.current)||void 0===e?void 0:e.readyState)},s=function(){var e;Ee(!1),N.current&&(clearTimeout(N.current),N.current=null),be(!1),u&&console.log("[StormcloudUI] Video event: canplay, readyState:",null===(e=F.current)||void 0===e?void 0:e.readyState,"- clearing loading state, isLoading=false")},r=function(){var e;Ee(!1),N.current&&(clearTimeout(N.current),N.current=null),be(!1),u&&console.log("[StormcloudUI] Video event: canplaythrough, readyState:",null===(e=F.current)||void 0===e?void 0:e.readyState,"- clearing loading state, isLoading=false")},n=function(){var e;N.current&&clearTimeout(N.current),N.current=window.setTimeout(function(){var e;be(!0),u&&console.log("[StormcloudUI] Video buffering detected (after 300ms delay), readyState:",null===(e=F.current)||void 0===e?void 0:e.readyState,"- showing spinner, isBuffering=true")},300),u&&console.log("[StormcloudUI] Video event: waiting, readyState:",null===(e=F.current)||void 0===e?void 0:e.readyState,"- buffering delay started (300ms)")},a=function(){var e;Ee(!1),N.current&&(clearTimeout(N.current),N.current=null),be(!1),Ie(!1),u&&console.log("[StormcloudUI] Video event: playing, readyState:",null===(e=F.current)||void 0===e?void 0:e.readyState,"- playback started, isLoading=false, isBuffering=false")},o=function(){U.current&&!U.current.isShowingAds()?Ie(!0):Ie(!1)},l=function(){Ie(!0)},d=F.current;return d.addEventListener("loadstart",i),d.addEventListener("loadedmetadata",e),d.addEventListener("loadeddata",t),d.addEventListener("canplay",s),d.addEventListener("canplaythrough",r),d.addEventListener("waiting",n),d.addEventListener("playing",a),d.addEventListener("pause",o),d.addEventListener("ended",l),d.paused&&Ie(!0),function(){N.current&&(clearTimeout(N.current),N.current=null),d.removeEventListener("loadstart",i),d.removeEventListener("loadedmetadata",e),d.removeEventListener("loadeddata",t),d.removeEventListener("canplay",s),d.removeEventListener("canplaythrough",r),d.removeEventListener("waiting",n),d.removeEventListener("playing",a),d.removeEventListener("pause",o),d.removeEventListener("ended",l)}}},[u]),S.jsxs(S.Fragment,{children:[S.jsx("style",{children:"\n @keyframes spin {\n from {\n transform: rotate(0deg);\n }\n to {\n transform: rotate(360deg);\n }\n }\n \n .stormcloud-loading-hidden .stormcloud-loading-indicator {\n display: none !important;\n }\n \n .stormcloud-video-wrapper:fullscreen {\n border-radius: 0 !important;\n box-shadow: none !important;\n width: 100vw !important;\n height: 100vh !important;\n max-width: 100vw !important;\n max-height: 100vh !important;\n position: fixed !important;\n top: 0 !important;\n left: 0 !important;\n z-index: 999999 !important;\n background: #000 !important;\n display: flex !important;\n align-items: center !important;\n justify-content: center !important;\n }\n \n .stormcloud-video-wrapper:has(*:fullscreen) {\n border-radius: 0 !important;\n box-shadow: none !important;\n width: 100vw !important;\n height: 100vh !important;\n max-width: 100vw !important;\n max-height: 100vh !important;\n position: fixed !important;\n top: 0 !important;\n left: 0 !important;\n z-index: 999999 !important;\n background: #000 !important;\n display: flex !important;\n align-items: center !important;\n justify-content: center !important;\n }\n \n *:fullscreen {\n width: 100vw !important;\n height: 100vh !important;\n max-width: 100vw !important;\n max-height: 100vh !important;\n position: fixed !important;\n top: 0 !important;\n left: 0 !important;\n z-index: 999999 !important;\n background: #000 !important;\n }\n "}),S.jsxs("div",{className:"stormcloud-video-wrapper ".concat(y||""),style:s({display:"flex",alignItems:"center",justifyContent:"center",position:z?"fixed":"relative",top:z?0:void 0,left:z?0:void 0,overflow:"hidden",width:z?"100vw":"100%",height:z?"100vh":"auto",minHeight:z?"100vh":"auto",maxWidth:z?"100vw":"100%",maxHeight:z?"100vh":"none",zIndex:z?999999:void 0,backgroundColor:z?"#000":void 0,borderRadius:z?0:void 0,boxShadow:z?"none":void 0},T),children:[S.jsx("video",s({ref:F,className:E,style:s({display:"block",width:"100%",height:z?"100%":"auto",maxWidth:"100%",maxHeight:z?"100%":"none",objectFit:z?"cover":"contain",backgroundColor:"#000",aspectRatio:z?"unset":void 0},L),controls:H&&R&&!h,playsInline:I,preload:k,poster:w},O,{children:P})),(Te||Ae)&&!f&&S.jsx(od,{className:"stormcloud-loading-indicator",size:42,color:"white",style:{position:"absolute",top:"calc(50% - 21px)",left:"calc(50% - 21px)",zIndex:20,animation:"spin 1s linear infinite",filter:"drop-shadow(0 3px 6px rgba(0, 0, 0, 0.8))"}}),we&&S.jsxs("div",{style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",zIndex:25,background:"linear-gradient(135deg, rgba(220, 38, 38, 0.95) 0%, rgba(185, 28, 28, 0.9) 100%)",color:"white",padding:"24px 32px",borderRadius:"16px",backdropFilter:"blur(20px)",border:"2px solid rgba(255, 255, 255, 0.2)",boxShadow:"0 20px 60px rgba(0, 0, 0, 0.6), inset 0 2px 0 rgba(255, 255, 255, 0.2)",textAlign:"center",maxWidth:"400px",margin:"0 16px"},children:[S.jsx("div",{style:{fontSize:"20px",fontWeight:"bold",marginBottom:"12px",color:"#ffffff",textShadow:"0 2px 4px rgba(0, 0, 0, 0.5)"},children:"License Key Required"}),S.jsxs("div",{style:{fontSize:"14px",lineHeight:"1.5",color:"rgba(255, 255, 255, 0.9)",textShadow:"0 1px 2px rgba(0, 0, 0, 0.3)"},children:["Please provide a valid license key to use the Stormcloud Video Player.",S.jsx("br",{}),"Contact your administrator for licensing information."]})]}),Re&&!Te&&!Ae&&!we&&!$.showAds&&S.jsx("div",{onClick:function(){var e;F.current&&F.current.paused&&(F.current.src||F.current.currentSrc&&""!==F.current.currentSrc||F.current.readyState>=1?(null===(e=F.current.play())||void 0===e||e.catch(function(e){console.error("[StormcloudVideoPlayer] Failed to play:",e)}),Ie(!1)):console.warn("[StormcloudVideoPlayer] Cannot play: video has no valid source"))},style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",zIndex:15,cursor:"pointer",background:"linear-gradient(135deg, rgba(0, 0, 0, 0.9) 0%, rgba(20, 20, 20, 0.8) 100%)",borderRadius:"50%",width:"100px",height:"100px",display:"flex",alignItems:"center",justifyContent:"center",backdropFilter:"blur(20px)",border:"3px solid rgba(255, 255, 255, 0.8)",boxShadow:"0 12px 40px rgba(0, 0, 0, 0.8), inset 0 2px 0 rgba(255, 255, 255, 0.3)",transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)"},onMouseEnter:function(e){var t=e.currentTarget;t.style.transform="translate(-50%, -50%)",t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.95) 0%, rgba(40, 40, 40, 0.9) 100%)",t.style.boxShadow="0 16px 48px rgba(0, 0, 0, 0.9), inset 0 2px 0 rgba(255, 255, 255, 0.4)",t.style.borderColor="rgba(255, 255, 255, 0.9)"},onMouseLeave:function(e){var t=e.currentTarget;t.style.transform="translate(-50%, -50%)",t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.9) 0%, rgba(20, 20, 20, 0.8) 100%)",t.style.boxShadow="0 12px 40px rgba(0, 0, 0, 0.8), inset 0 2px 0 rgba(255, 255, 255, 0.3)",t.style.borderColor="rgba(255, 255, 255, 0.8)"},title:"Play",children:S.jsx(ad,{size:36,color:"white",style:{marginLeft:"6px",filter:"drop-shadow(0 2px 4px rgba(0, 0, 0, 0.8))"}})}),$e&&!we?S.jsx(S.Fragment,{children:S.jsxs("div",{style:{position:"absolute",bottom:0,left:0,right:0,background:"linear-gradient(180deg, transparent 0%, rgba(0, 0, 0, 0.8) 100%)",padding:"20px 16px 16px",zIndex:10},children:[S.jsxs("div",{style:{width:"100%",height:"8px",background:"linear-gradient(90deg, rgba(255, 255, 255, 0.2) 0%, rgba(255, 255, 255, 0.1) 100%)",borderRadius:"8px",marginBottom:"16px",cursor:"pointer",position:"relative",backdropFilter:"blur(5px)",border:"1px solid rgba(255, 255, 255, 0.1)",boxShadow:"inset 0 2px 4px rgba(0, 0, 0, 0.2)"},onClick:function(e){if(F.current&&re>0&&isFinite(re)){var t=e.currentTarget.getBoundingClientRect(),i=e.clientX-t.left,s=Math.max(0,Math.min(1,i/t.width))*re;isFinite(s)&&s>=0&&s<=re&&(F.current.currentTime=s)}},children:[S.jsx("div",{style:{height:"100%",background:"linear-gradient(90deg, rgba(139, 92, 246, 0.9) 0%, rgba(59, 130, 246, 0.8) 50%, rgba(34, 197, 94, 0.9) 100%)",borderRadius:"8px",width:"".concat(re>0?te/re*100:0,"%"),transition:"width 0.2s cubic-bezier(0.4, 0, 0.2, 1)",boxShadow:"0 2px 8px rgba(139, 92, 246, 0.4)"}}),S.jsx("div",{style:{position:"absolute",top:"-6px",right:"".concat(re>0?100-te/re*100:100,"%"),width:"20px",height:"20px",background:"linear-gradient(135deg, rgba(255, 255, 255, 0.95) 0%, rgba(240, 240, 240, 0.9) 100%)",borderRadius:"50%",border:"3px solid rgba(139, 92, 246, 0.8)",boxShadow:"0 4px 16px rgba(139, 92, 246, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.8)",transform:"translateX(50%)",transition:"all 0.2s cubic-bezier(0.4, 0, 0.2, 1)"}})]}),S.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",color:"white",flexWrap:xe<768?"wrap":"nowrap",gap:"".concat(8*Fe,"px")},children:[S.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"".concat(12*Fe,"px"),flexWrap:xe<480?"wrap":"nowrap"},children:[S.jsx("button",{onClick:function(){var e;F.current&&(F.current.paused?F.current.src||F.current.currentSrc&&""!==F.current.currentSrc||F.current.readyState>=1?(null===(e=F.current.play())||void 0===e||e.catch(function(e){console.error("[StormcloudVideoPlayer] Failed to play:",e)}),Ie(!1)):console.warn("[StormcloudVideoPlayer] Cannot play: video has no valid source"):(F.current.pause(),Ie(!0)))},style:{background:"linear-gradient(135deg, rgba(0, 0, 0, 0.75) 0%, rgba(0, 0, 0, 0.65) 100%)",backdropFilter:"blur(12px)",border:"".concat(2*Fe,"px solid rgba(255, 255, 255, 0.3)"),color:"#ffffff",cursor:"pointer",padding:"".concat(10*Fe,"px"),borderRadius:"".concat(16*Fe,"px"),display:"flex",alignItems:"center",justifyContent:"center",transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",boxShadow:"0 8px 32px rgba(0, 0, 0, 0.4), 0 4px 16px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.3)",minWidth:"".concat(48*Fe,"px"),minHeight:"".concat(48*Fe,"px")},onMouseEnter:function(e){var t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.85) 0%, rgba(0, 0, 0, 0.75) 100%)",t.style.boxShadow="0 12px 48px rgba(0, 0, 0, 0.6), 0 6px 24px rgba(0, 0, 0, 0.4), inset 0 2px 0 rgba(255, 255, 255, 0.4)"},onMouseLeave:function(e){var t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.75) 0%, rgba(0, 0, 0, 0.65) 100%)",t.style.boxShadow="0 8px 32px rgba(0, 0, 0, 0.4), 0 4px 16px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.3)"},title:J?"Pause":"Play",children:J?S.jsx(nd,{size:Math.max(16,20*Fe),style:{filter:"drop-shadow(0 0 0 transparent)"}}):S.jsx(ad,{size:Math.max(16,20*Fe),style:{filter:"drop-shadow(0 0 0 transparent)"}})}),S.jsxs("div",{style:{position:"relative",display:"flex",alignItems:"center",padding:"8px",margin:"-8px"},onMouseEnter:function(){return ge(!0)},onMouseLeave:function(){return ge(!1)},children:[S.jsx("button",{onClick:function(){U.current&&U.current.toggleMute(),g&&g()},style:{background:"linear-gradient(135deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.6) 100%)",backdropFilter:"blur(10px)",border:"".concat(2*Fe,"px solid rgba(255, 255, 255, 0.3)"),color:"#ffffff",cursor:"pointer",padding:"".concat(8*Fe,"px"),borderRadius:"".concat(16*Fe,"px"),display:"flex",alignItems:"center",justifyContent:"center",transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",boxShadow:"0 6px 28px rgba(0, 0, 0, 0.4), 0 3px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.25)",minWidth:"".concat(44*Fe,"px"),minHeight:"".concat(44*Fe,"px")},onMouseEnter:function(e){var t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.8) 0%, rgba(0, 0, 0, 0.7) 100%)",t.style.boxShadow="0 10px 36px rgba(0, 0, 0, 0.6), 0 5px 16px rgba(0, 0, 0, 0.4), inset 0 2px 0 rgba(255, 255, 255, 0.35)"},onMouseLeave:function(e){var t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.6) 100%)",t.style.boxShadow="0 6px 28px rgba(0, 0, 0, 0.4), 0 3px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.25)"},title:W?"Unmute":"Mute",children:W||0===oe?S.jsx(dd,{size:Math.max(14,16*Fe),style:{filter:"drop-shadow(0 0 0 transparent)"}}):oe<.5?S.jsx(ld,{size:Math.max(14,16*Fe),style:{filter:"drop-shadow(0 0 0 transparent)"}}):S.jsx(cd,{size:Math.max(14,16*Fe),style:{filter:"drop-shadow(0 0 0 transparent)"}})}),fe&&S.jsxs(S.Fragment,{children:[S.jsx("div",{style:{position:"absolute",bottom:"100%",left:"50%",transform:"translateX(-50%)",width:"60px",height:"20px",marginBottom:"-16px",zIndex:9},onMouseEnter:function(){return ge(!0)},onMouseLeave:function(){return ge(!1)}}),S.jsx("div",{style:{position:"absolute",bottom:"100%",left:"50%",transform:"translateX(-50%)",marginBottom:"4px",background:"linear-gradient(135deg, rgba(0, 0, 0, 0.88) 0%, rgba(20, 20, 20, 0.92) 100%)",backdropFilter:"blur(15px)",padding:"10px 14px",borderRadius:"14px",border:"1px solid rgba(255, 255, 255, 0.15)",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"128px",boxShadow:"0 12px 40px rgba(0, 0, 0, 0.5), 0 4px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.15)",zIndex:10,transition:"transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out, border-color 0.2s ease-in-out"},onMouseEnter:function(e){ge(!0),e.currentTarget.style.boxShadow="0 16px 48px rgba(0, 0, 0, 0.6), 0 6px 16px rgba(0, 0, 0, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 0 24px rgba(59, 130, 246, 0.3)",e.currentTarget.style.borderColor="rgba(59, 130, 246, 0.4)"},onMouseLeave:function(e){ge(!1),e.currentTarget.style.boxShadow="0 12px 40px rgba(0, 0, 0, 0.5), 0 4px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.15)",e.currentTarget.style.borderColor="rgba(255, 255, 255, 0.15)"},children:S.jsxs("div",{style:{position:"relative",width:"8px",height:"104px",cursor:"pointer",transition:"transform 0.2s ease-in-out"},onMouseEnter:function(e){},onMouseLeave:function(e){},onMouseDown:function(e){e.preventDefault();var t=e.currentTarget,i=function(e){if(t){var i=t.getBoundingClientRect(),s=e.clientY-i.top,r=1-Math.max(0,Math.min(1,s/i.height));Ne(r)}},s=function(){document.removeEventListener("mousemove",i),document.removeEventListener("mouseup",s)};document.addEventListener("mousemove",i),document.addEventListener("mouseup",s);var r=t.getBoundingClientRect(),n=e.clientY-r.top,a=1-Math.max(0,Math.min(1,n/r.height));Ne(a)},onClick:function(e){e.stopPropagation();var t=e.currentTarget.getBoundingClientRect(),i=e.clientY-t.top,s=1-Math.max(0,Math.min(1,i/t.height));Ne(s)},children:[S.jsx("div",{style:{position:"absolute",bottom:"0",left:"0",width:"100%",height:"100%",background:"linear-gradient(180deg, rgba(255, 255, 255, 0.4) 0%, rgba(255, 255, 255, 0.15) 100%)",borderRadius:"4px",boxShadow:"inset 0 1px 3px rgba(0, 0, 0, 0.2)"}}),S.jsx("div",{style:{position:"absolute",bottom:"0",left:"0",width:"100%",height:"".concat(100*(W?0:oe),"%"),background:"linear-gradient(180deg, rgba(96, 165, 250, 1) 0%, rgba(59, 130, 246, 0.95) 50%, rgba(37, 99, 235, 0.9) 100%)",borderRadius:"4px",transition:"height 0.15s ease-out, box-shadow 0.2s ease-in-out",boxShadow:"0 0 8px rgba(59, 130, 246, 0.5), inset 0 1px 0 rgba(255, 255, 255, 0.3)"}}),S.jsx("div",{style:{position:"absolute",bottom:"calc(".concat(100*(W?0:oe),"% - 7px)"),left:"50%",transform:"translateX(-50%)",width:"14px",height:"14px",background:"linear-gradient(135deg, #ffffff 0%, #f0f9ff 100%)",borderRadius:"50%",boxShadow:"0 2px 6px rgba(0, 0, 0, 0.3), 0 0 0 2px rgba(59, 130, 246, 0.3), 0 0 12px rgba(59, 130, 246, 0.4)",transition:"bottom 0.15s ease-out, transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out, width 0.2s ease-in-out, height 0.2s ease-in-out",cursor:"grab"},onMouseEnter:function(e){e.currentTarget.style.boxShadow="0 3px 10px rgba(0, 0, 0, 0.4), 0 0 0 3px rgba(59, 130, 246, 0.5), 0 0 20px rgba(59, 130, 246, 0.6)",e.currentTarget.style.cursor="grab"},onMouseLeave:function(e){e.currentTarget.style.boxShadow="0 2px 6px rgba(0, 0, 0, 0.3), 0 0 0 2px rgba(59, 130, 246, 0.3), 0 0 12px rgba(59, 130, 246, 0.4)"},onMouseDown:function(e){e.currentTarget.style.cursor="grabbing"},onMouseUp:function(e){e.currentTarget.style.cursor="grab"}})]})})]})]}),S.jsxs("div",{style:{fontSize:"".concat(14*Fe,"px"),fontFamily:"monospace",color:"rgba(255, 255, 255, 0.9)",display:xe<480?"none":"block"},children:[Ue(te)," / ",Ue(re)]})]}),S.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"".concat(12*Fe,"px")},children:[S.jsxs("div",{style:{position:"relative",display:xe<600?"none":"block"},children:[S.jsxs("button",{onClick:function(){return ve(!me)},style:{background:"linear-gradient(135deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.6) 100%)",backdropFilter:"blur(10px)",border:"".concat(2*Fe,"px solid rgba(255, 255, 255, 0.3)"),color:"#ffffff",cursor:"pointer",padding:"".concat(8*Fe,"px ").concat(14*Fe,"px"),borderRadius:"".concat(14*Fe,"px"),fontSize:"".concat(14*Fe,"px"),fontFamily:"monospace",fontWeight:"700",transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",boxShadow:"0 6px 24px rgba(0, 0, 0, 0.4), 0 3px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.25)",minWidth:"".concat(56*Fe,"px"),minHeight:"".concat(40*Fe,"px")},onMouseEnter:function(e){var t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.8) 0%, rgba(0, 0, 0, 0.7) 100%)",t.style.boxShadow="0 10px 32px rgba(0, 0, 0, 0.6), 0 5px 16px rgba(0, 0, 0, 0.4), inset 0 2px 0 rgba(255, 255, 255, 0.35)"},onMouseLeave:function(e){var t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.6) 100%)",t.style.boxShadow="0 6px 24px rgba(0, 0, 0, 0.4), 0 3px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.25)"},title:"Playback Speed",children:[ce,"x"]}),me&&S.jsx("div",{style:{position:"absolute",bottom:"100%",right:0,marginBottom:"12px",background:"linear-gradient(135deg, rgba(0, 0, 0, 0.9) 0%, rgba(20, 20, 20, 0.95) 100%)",backdropFilter:"blur(20px)",borderRadius:"12px",border:"1px solid rgba(255, 255, 255, 0.1)",overflow:"hidden",minWidth:"90px",boxShadow:"0 16px 48px rgba(0, 0, 0, 0.5), inset 0 1px 0 rgba(255, 255, 255, 0.1)"},children:[.25,.5,.75,1,1.25,1.5,1.75,2].map(function(e){return S.jsxs("button",{onClick:function(){return t=e,F.current&&isFinite(t)&&t>0&&(F.current.playbackRate=t),void ve(!1);var t},style:{display:"block",width:"100%",padding:"10px 16px",background:ce===e?"linear-gradient(135deg, rgba(99, 102, 241, 0.8) 0%, rgba(139, 92, 246, 0.6) 100%)":"transparent",border:"none",color:"white",cursor:"pointer",fontSize:"13px",fontFamily:"monospace",fontWeight:"600",textAlign:"center",transition:"all 0.2s cubic-bezier(0.4, 0, 0.2, 1)",borderBottom:2!==e?"1px solid rgba(255, 255, 255, 0.05)":"none"},onMouseEnter:function(t){ce!==e&&(t.target.style.background="linear-gradient(135deg, rgba(255, 255, 255, 0.15) 0%, rgba(255, 255, 255, 0.05) 100%)")},onMouseLeave:function(t){ce!==e&&(t.target.style.background="transparent")},children:[e,"x"]},e)})})]}),S.jsx("button",{onClick:function(){p?p():U.current&&U.current.toggleFullscreen().catch(function(e){console.error("Fullscreen error:",e)})},style:{background:"linear-gradient(135deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.6) 100%)",backdropFilter:"blur(10px)",border:"".concat(2*Fe,"px solid rgba(255, 255, 255, 0.3)"),color:"#ffffff",cursor:"pointer",padding:"".concat(8*Fe,"px"),borderRadius:"".concat(16*Fe,"px"),display:"flex",alignItems:"center",justifyContent:"center",transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",boxShadow:"0 6px 28px rgba(0, 0, 0, 0.4), 0 3px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.25)",minWidth:"".concat(44*Fe,"px"),minHeight:"".concat(44*Fe,"px")},onMouseEnter:function(e){var t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.8) 0%, rgba(0, 0, 0, 0.7) 100%)",t.style.boxShadow="0 10px 36px rgba(0, 0, 0, 0.6), 0 5px 16px rgba(0, 0, 0, 0.4), inset 0 2px 0 rgba(255, 255, 255, 0.35)"},onMouseLeave:function(e){var t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.6) 100%)",t.style.boxShadow="0 6px 28px rgba(0, 0, 0, 0.4), 0 3px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.25)"},title:z?"Exit Fullscreen":"Enter Fullscreen",children:z?S.jsx(sd,{size:Math.max(14,16*Fe),style:{filter:"drop-shadow(0 0 0 transparent)"}}):S.jsx(rd,{size:Math.max(14,16*Fe),style:{filter:"drop-shadow(0 0 0 transparent)"}})})]})]})]})}):h&&!we&&S.jsxs("div",{style:{position:"absolute",bottom:"".concat(10*Fe,"px"),right:"".concat(10*Fe,"px"),transform:"none",display:"flex",flexDirection:Me?"column":"row",gap:"".concat(10*Fe,"px"),zIndex:10},children:[S.jsxs("div",{style:{position:"relative",display:"flex",alignItems:"center",padding:"8px",margin:"-8px"},onMouseEnter:function(){return ge(!0)},onMouseLeave:function(){return ge(!1)},children:[S.jsx("button",{onClick:function(){U.current&&U.current.toggleMute(),g&&g()},onMouseEnter:function(e){var t=e.currentTarget;t.style.boxShadow="0 14px 48px rgba(0, 0, 0, 0.7), 0 0 0 3px rgba(255, 255, 255, 0.8), inset 0 2px 0 rgba(255, 255, 255, 0.4)",t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.85) 0%, rgba(0, 0, 0, 0.75) 100%)"},onMouseLeave:function(e){var t=e.currentTarget;t.style.boxShadow="0 10px 36px rgba(0, 0, 0, 0.6), 0 0 0 2px rgba(255, 255, 255, 0.7), inset 0 1px 0 rgba(255, 255, 255, 0.3)",t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.75) 0%, rgba(0, 0, 0, 0.65) 100%)"},style:{background:"linear-gradient(135deg, rgba(0, 0, 0, 0.75) 0%, rgba(0, 0, 0, 0.65) 100%)",color:"#ffffff",border:"none",borderRadius:"".concat(18*Fe,"px"),padding:"".concat(8*Fe,"px"),cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",backdropFilter:"blur(20px)",boxShadow:"0 10px 36px rgba(0, 0, 0, 0.6), 0 0 0 2px rgba(255, 255, 255, 0.7), inset 0 1px 0 rgba(255, 255, 255, 0.3)",transition:"all 0.4s cubic-bezier(0.4, 0, 0.2, 1)",minWidth:"".concat(46*Fe,"px"),minHeight:"".concat(46*Fe,"px")},title:W?"Unmute":"Mute",children:W||0===oe?S.jsx(dd,{size:Math.max(14,16*Fe),style:{filter:"drop-shadow(0 2px 4px rgba(0, 0, 0, 0.8))",color:"#ffffff"}}):oe<.5?S.jsx(ld,{size:Math.max(14,16*Fe),style:{filter:"drop-shadow(0 2px 4px rgba(0, 0, 0, 0.8))",color:"#ffffff"}}):S.jsx(cd,{size:Math.max(14,16*Fe),style:{filter:"drop-shadow(0 2px 4px rgba(0, 0, 0, 0.8))",color:"#ffffff"}})}),fe&&S.jsxs(S.Fragment,{children:[S.jsx("div",{style:{position:"absolute",bottom:"100%",left:"50%",transform:"translateX(-50%)",width:"60px",height:"20px",marginBottom:"-16px",zIndex:9},onMouseEnter:function(){return ge(!0)},onMouseLeave:function(){return ge(!1)}}),S.jsx("div",{style:{position:"absolute",bottom:"100%",left:"50%",transform:"translateX(-50%)",marginBottom:"4px",background:"linear-gradient(135deg, rgba(0, 0, 0, 0.96) 0%, rgba(20, 20, 20, 0.92) 100%)",backdropFilter:"blur(20px)",padding:"10px 14px",borderRadius:"14px",border:"2px solid rgba(255, 255, 255, 0.7)",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"128px",boxShadow:"0 12px 40px rgba(0, 0, 0, 0.85), 0 4px 12px rgba(0, 0, 0, 0.6), inset 0 1px 0 rgba(255, 255, 255, 0.35)",zIndex:10,transition:"transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out, border-color 0.2s ease-in-out"},onMouseEnter:function(e){ge(!0),e.currentTarget.style.boxShadow="0 16px 48px rgba(0, 0, 0, 0.9), 0 6px 16px rgba(0, 0, 0, 0.7), inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 0 24px rgba(96, 165, 250, 0.4)",e.currentTarget.style.borderColor="rgba(96, 165, 250, 0.8)"},onMouseLeave:function(e){ge(!1),e.currentTarget.style.boxShadow="0 12px 40px rgba(0, 0, 0, 0.85), 0 4px 12px rgba(0, 0, 0, 0.6), inset 0 1px 0 rgba(255, 255, 255, 0.35)",e.currentTarget.style.borderColor="rgba(255, 255, 255, 0.7)"},children:S.jsxs("div",{style:{position:"relative",width:"8px",height:"104px",cursor:"pointer",transition:"transform 0.2s ease-in-out"},onMouseDown:function(e){e.preventDefault();var t=e.currentTarget,i=function(e){if(t){var i=t.getBoundingClientRect(),s=e.clientY-i.top,r=1-Math.max(0,Math.min(1,s/i.height));Ne(r)}},s=function(){document.removeEventListener("mousemove",i),document.removeEventListener("mouseup",s)};document.addEventListener("mousemove",i),document.addEventListener("mouseup",s);var r=t.getBoundingClientRect(),n=e.clientY-r.top,a=1-Math.max(0,Math.min(1,n/r.height));Ne(a)},onClick:function(e){e.stopPropagation();var t=e.currentTarget.getBoundingClientRect(),i=e.clientY-t.top,s=1-Math.max(0,Math.min(1,i/t.height));Ne(s)},children:[S.jsx("div",{style:{position:"absolute",bottom:"0",left:"0",width:"100%",height:"100%",background:"linear-gradient(180deg, rgba(255, 255, 255, 0.85) 0%, rgba(255, 255, 255, 0.5) 100%)",borderRadius:"4px",border:"1px solid rgba(255, 255, 255, 0.4)",boxShadow:"inset 0 1px 3px rgba(0, 0, 0, 0.3)"}}),S.jsx("div",{style:{position:"absolute",bottom:"0",left:"0",width:"100%",height:"".concat(100*(W?0:oe),"%"),background:"linear-gradient(180deg, rgba(125, 211, 252, 1) 0%, rgba(96, 165, 250, 0.98) 50%, rgba(59, 130, 246, 0.95) 100%)",borderRadius:"4px",transition:"height 0.15s ease-out, box-shadow 0.2s ease-in-out",boxShadow:"0 0 12px rgba(96, 165, 250, 0.6), inset 0 1px 0 rgba(255, 255, 255, 0.4)"}}),S.jsx("div",{style:{position:"absolute",bottom:"calc(".concat(100*(W?0:oe),"% - 8px)"),left:"50%",transform:"translateX(-50%)",width:"16px",height:"16px",background:"linear-gradient(135deg, #ffffff 0%, #f0f9ff 100%)",borderRadius:"50%",border:"2px solid rgba(96, 165, 250, 0.9)",boxShadow:"0 3px 8px rgba(0, 0, 0, 0.5), 0 0 0 2px rgba(96, 165, 250, 0.4), 0 0 16px rgba(96, 165, 250, 0.5)",transition:"bottom 0.15s ease-out, transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out, width 0.2s ease-in-out, height 0.2s ease-in-out",cursor:"grab"},onMouseEnter:function(e){e.currentTarget.style.boxShadow="0 4px 12px rgba(0, 0, 0, 0.6), 0 0 0 3px rgba(96, 165, 250, 0.6), 0 0 24px rgba(96, 165, 250, 0.7)",e.currentTarget.style.cursor="grab"},onMouseLeave:function(e){e.currentTarget.style.boxShadow="0 3px 8px rgba(0, 0, 0, 0.5), 0 0 0 2px rgba(96, 165, 250, 0.4), 0 0 16px rgba(96, 165, 250, 0.5)"},onMouseDown:function(e){e.currentTarget.style.cursor="grabbing"},onMouseUp:function(e){e.currentTarget.style.cursor="grab"}})]})})]})]}),S.jsx("button",{onClick:function(){p?p():U.current&&U.current.toggleFullscreen().catch(function(e){console.error("Fullscreen error:",e)})},onMouseEnter:function(e){var t=e.currentTarget;t.style.boxShadow="0 14px 48px rgba(0, 0, 0, 0.7), 0 0 0 3px rgba(255, 255, 255, 0.8), inset 0 2px 0 rgba(255, 255, 255, 0.4)",t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.85) 0%, rgba(0, 0, 0, 0.75) 100%)"},onMouseLeave:function(e){var t=e.currentTarget;t.style.boxShadow="0 10px 36px rgba(0, 0, 0, 0.6), 0 0 0 2px rgba(255, 255, 255, 0.7), inset 0 1px 0 rgba(255, 255, 255, 0.3)",t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.75) 0%, rgba(0, 0, 0, 0.65) 100%)"},style:{background:"linear-gradient(135deg, rgba(0, 0, 0, 0.75) 0%, rgba(0, 0, 0, 0.65) 100%)",color:"#ffffff",border:"none",borderRadius:"".concat(18*Fe,"px"),padding:"".concat(8*Fe,"px"),cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",backdropFilter:"blur(20px)",boxShadow:"0 10px 36px rgba(0, 0, 0, 0.6), 0 0 0 2px rgba(255, 255, 255, 0.7), inset 0 1px 0 rgba(255, 255, 255, 0.3)",transition:"all 0.4s cubic-bezier(0.4, 0, 0.2, 1)",minWidth:"".concat(46*Fe,"px"),minHeight:"".concat(46*Fe,"px")},title:z?"Exit Fullscreen":"Enter Fullscreen",children:z?S.jsx(sd,{size:Math.max(14,16*Fe),style:{filter:"drop-shadow(0 2px 4px rgba(0, 0, 0, 0.8))",color:"#ffffff"}}):S.jsx(rd,{size:Math.max(14,16*Fe),style:{filter:"drop-shadow(0 2px 4px rgba(0, 0, 0, 0.8))",color:"#ffffff"}})})]}),m&&S.jsx("div",{onClick:m,style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:1,cursor:"pointer"}})]})]})},function(e,t){var i,s,r,n,a,l;try{for(var d=o(ud),c=d.next();!c.done;c=d.next()){if(e[p=c.value]!==t[p])return!1}}catch(e){i={error:e}}finally{try{c&&!c.done&&(s=d.return)&&s.call(d)}finally{if(i)throw i.error}}try{for(var u=o(["autoplay","muted","controls","showCustomControls","className","style","wrapperClassName","wrapperStyle","playsInline","preload","poster","children"]),h=u.next();!h.done;h=u.next()){if(e[p=h.value]!==t[p])return!1}}catch(e){r={error:e}}finally{try{h&&!h.done&&(n=u.return)&&n.call(u)}finally{if(r)throw r.error}}try{for(var f=o(["onReady","onVolumeToggle","onFullscreenToggle","onControlClick"]),g=f.next();!g.done;g=f.next()){var p;if(e[p=g.value]!==t[p])return!1}}catch(e){a={error:e}}finally{try{g&&!g.done&&(l=f.return)&&l.call(f)}finally{if(a)throw a.error}}return!0}),fd=function(){},gd={playing:!1,loop:!1,controls:!0,volume:1,muted:!1,playbackRate:1,width:"100%",height:"auto",style:{},progressInterval:1e3,playsInline:!1,autoplay:!1,preload:"metadata",poster:"",className:"",wrapperClassName:"",wrapperStyle:{},allowNativeHls:!1,lowLatencyMode:!1,driftToleranceMs:1e3,immediateManifestAds:!0,debugAdTiming:!1,showCustomControls:!1,hideLoadingIndicator:!1,licenseKey:"",adFailsafeTimeoutMs:1e4,minSegmentsBeforePlay:2,onStart:fd,onPlay:fd,onPause:fd,onBuffer:fd,onBufferEnd:fd,onEnded:fd,onError:fd,onDuration:fd,onSeek:fd,onProgress:fd,onVolumeToggle:fd,onFullscreenToggle:fd,onControlClick:fd},pd=A.lazy,md=function(e,t){var i=s({},e);return t.forEach(function(e){delete i[e]}),i},vd=function(e){return"undefined"!=typeof window&&window.MediaStream&&e instanceof window.MediaStream},yd=function(e){for(var t,i,s=[],r=1;r<arguments.length;r++)s[r-1]=arguments[r];if(!s.length)return e;var n=s.shift();if(Td(e)&&Td(n))for(var a in n)Td(n[a])?(e[a]||Object.assign(e,((t={})[a]={},t)),yd(e[a],n[a])):Object.assign(e,((i={})[a]=n[a],i));return yd.apply(void 0,d([e],l(s),!1))},Td=function(e){return e&&"object"==typeof e&&!Array.isArray(e)},Ed="undefined"!=typeof window&&window.document,Sd="undefined"!=typeof globalThis&&globalThis.window&&globalThis.window.document,Ad=Ed&&/iPad|iPhone|iPod/.test(navigator.userAgent),bd=Ed&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent),Ld=/\.(m3u8)($|\?)/i,Rd=/\/hls\//i,Id=/\.(mpd)($|\?)/i,kd=/\.(mp4|webm|ogg|avi|mov|wmv|flv|mkv)($|\?)/i,wd=/\.(mp3|wav|ogg|aac|wma|flac|m4a)($|\?)/i,Pd={hls:function(e){return!(!e||"string"!=typeof e)&&(Ld.test(e)||Rd.test(e))},dash:function(e){return!(!e||"string"!=typeof e)&&Id.test(e)},video:function(e){return!(!e||"string"!=typeof e)&&kd.test(e)},audio:function(e){return!(!e||"string"!=typeof e)&&wd.test(e)},file:function(e){return!(!e||"string"!=typeof e)&&(kd.test(e)||wd.test(e))}},Dd=function(e){function t(){var t=e.apply(this,d([],l(arguments),!1))||this;return t.player=null,t.mounted=!1,t.load=function(){return n(t,void 0,void 0,function(){var e,t,i,s,r,n,o,l;return a(this,function(a){switch(a.label){case 0:if(!this.props.videoElement||!this.props.src)return[2];a.label=1;case 1:return a.trys.push([1,3,,4]),this.player&&(this.player.destroy(),this.player=null),e={src:this.props.src,videoElement:this.props.videoElement},void 0!==this.props.autoplay&&(e.autoplay=this.props.autoplay),void 0!==this.props.muted&&(e.muted=this.props.muted),void 0!==this.props.lowLatencyMode&&(e.lowLatencyMode=this.props.lowLatencyMode),void 0!==this.props.allowNativeHls&&(e.allowNativeHls=this.props.allowNativeHls),void 0!==this.props.driftToleranceMs&&(e.driftToleranceMs=this.props.driftToleranceMs),void 0!==this.props.immediateManifestAds&&(e.immediateManifestAds=this.props.immediateManifestAds),void 0!==this.props.debugAdTiming&&(e.debugAdTiming=this.props.debugAdTiming),void 0!==this.props.showCustomControls&&(e.showCustomControls=this.props.showCustomControls),void 0!==this.props.onVolumeToggle&&(e.onVolumeToggle=this.props.onVolumeToggle),void 0!==this.props.onFullscreenToggle&&(e.onFullscreenToggle=this.props.onFullscreenToggle),void 0!==this.props.onControlClick&&(e.onControlClick=this.props.onControlClick),void 0!==this.props.licenseKey&&(e.licenseKey=this.props.licenseKey),void 0!==this.props.adFailsafeTimeoutMs&&(e.adFailsafeTimeoutMs=this.props.adFailsafeTimeoutMs),void 0!==this.props.minSegmentsBeforePlay&&(e.minSegmentsBeforePlay=this.props.minSegmentsBeforePlay),this.player=new jl(e),null===(s=(i=this.props).onMount)||void 0===s||s.call(i,this),[4,this.player.load()];case 2:return a.sent(),this.mounted&&(null===(n=(r=this.props).onReady)||void 0===n||n.call(r)),[3,4];case 3:return t=a.sent(),this.mounted&&(null===(l=(o=this.props).onError)||void 0===l||l.call(o,t)),[3,4];case 4:return[2]}})})},t.play=function(){var e,i,s;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 i,s;console.error("[HlsPlayer] Failed to play:",e),null===(s=(i=t.props).onError)||void 0===s||s.call(i,e)}),null===(s=(i=t.props).onPlay)||void 0===s||s.call(i)):console.warn("[HlsPlayer] Cannot play: video has no valid source")}},t.pause=function(){var e,i;t.props.videoElement&&(t.props.videoElement.pause(),null===(i=(e=t.props).onPause)||void 0===i||i.call(e))},t.stop=function(){t.pause(),t.props.videoElement&&(t.props.videoElement.currentTime=0)},t.seekTo=function(e,i){t.props.videoElement&&(t.props.videoElement.currentTime=e,i||t.pause())},t.setVolume=function(e){t.props.videoElement&&(t.props.videoElement.volume=Math.max(0,Math.min(1,e)))},t.mute=function(){t.props.videoElement&&(t.props.videoElement.muted=!0)},t.unmute=function(){t.props.videoElement&&(t.props.videoElement.muted=!1)},t.setPlaybackRate=function(e){t.props.videoElement&&e>0&&(t.props.videoElement.playbackRate=e)},t.getDuration=function(){return t.props.videoElement&&isFinite(t.props.videoElement.duration)?t.props.videoElement.duration:null},t.getCurrentTime=function(){return t.props.videoElement&&isFinite(t.props.videoElement.currentTime)?t.props.videoElement.currentTime:null},t.getSecondsLoaded=function(){return t.props.videoElement&&t.props.videoElement.buffered.length>0?t.props.videoElement.buffered.end(t.props.videoElement.buffered.length-1):null},t.getInternalPlayer=function(e){return void 0===e&&(e="player"),"player"===e?t.player:"video"===e?t.props.videoElement:"hls"===e&&t.player?t.player.hls:null},t}return i(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=Pd.hls,t}(A.Component),xd=function(e){function t(){var t=e.apply(this,d([],l(arguments),!1))||this;return t.mounted=!1,t.ready=!1,t.load=function(){var e,i;if(t.props.videoElement&&t.props.src){var s=t.props.videoElement,r=function(){var e,i;t.mounted&&!t.ready&&(t.ready=!0,null===(i=(e=t.props).onReady)||void 0===i||i.call(e))},n=function(){var e,i;t.mounted&&(null===(i=(e=t.props).onPlay)||void 0===i||i.call(e))},a=function(){var e,i;t.mounted&&(null===(i=(e=t.props).onPause)||void 0===i||i.call(e))},o=function(){var e,i;t.mounted&&(null===(i=(e=t.props).onEnded)||void 0===i||i.call(e))},l=function(e){var i,s;t.mounted&&(null===(s=(i=t.props).onError)||void 0===s||s.call(i,e))},d=function(){var e,i;t.mounted&&(null===(i=(e=t.props).onLoaded)||void 0===i||i.call(e))};return s.addEventListener("loadedmetadata",r),s.addEventListener("play",n),s.addEventListener("pause",a),s.addEventListener("ended",o),s.addEventListener("error",l),s.addEventListener("loadeddata",d),s.src=t.props.src,void 0!==t.props.autoplay&&(s.autoplay=t.props.autoplay),void 0!==t.props.muted&&(s.muted=t.props.muted),void 0!==t.props.loop&&(s.loop=t.props.loop),void 0!==t.props.controls&&(s.controls=t.props.controls),void 0!==t.props.playsInline&&(s.playsInline=t.props.playsInline),void 0!==t.props.preload&&(s.preload=t.props.preload),void 0!==t.props.poster&&(s.poster=t.props.poster),null===(i=(e=t.props).onMount)||void 0===i||i.call(e,t),function(){s.removeEventListener("loadedmetadata",r),s.removeEventListener("play",n),s.removeEventListener("pause",a),s.removeEventListener("ended",o),s.removeEventListener("error",l),s.removeEventListener("loadeddata",d)}}},t.play=function(){var e;if(t.props.videoElement){var i=t.props.videoElement;i.src||i.currentSrc&&""!==i.currentSrc||i.readyState>=1?null===(e=i.play())||void 0===e||e.catch(function(e){var i,s;console.error("[FilePlayer] Failed to play:",e),null===(s=(i=t.props).onError)||void 0===s||s.call(i,e)}):console.warn("[FilePlayer] Cannot play: video has no valid source")}},t.pause=function(){t.props.videoElement&&t.props.videoElement.pause()},t.stop=function(){t.pause(),t.props.videoElement&&(t.props.videoElement.currentTime=0)},t.seekTo=function(e,i){t.props.videoElement&&(t.props.videoElement.currentTime=e,i||t.pause())},t.setVolume=function(e){t.props.videoElement&&(t.props.videoElement.volume=Math.max(0,Math.min(1,e)))},t.mute=function(){t.props.videoElement&&(t.props.videoElement.muted=!0)},t.unmute=function(){t.props.videoElement&&(t.props.videoElement.muted=!1)},t.setPlaybackRate=function(e){t.props.videoElement&&e>0&&(t.props.videoElement.playbackRate=e)},t.setLoop=function(e){t.props.videoElement&&(t.props.videoElement.loop=e)},t.getDuration=function(){return t.props.videoElement&&isFinite(t.props.videoElement.duration)?t.props.videoElement.duration:null},t.getCurrentTime=function(){return t.props.videoElement&&isFinite(t.props.videoElement.currentTime)?t.props.videoElement.currentTime:null},t.getSecondsLoaded=function(){return t.props.videoElement&&t.props.videoElement.buffered.length>0?t.props.videoElement.buffered.end(t.props.videoElement.buffered.length-1):null},t.getInternalPlayer=function(e){return void 0===e&&(e="player"),"video"===e?t.props.videoElement:null},t.enablePIP=function(){return n(t,void 0,void 0,function(){var e;return a(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 n(t,void 0,void 0,function(){var e;return a(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 i(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=Pd.file,t}(A.Component),Cd=[{key:"hls",name:"HLS Player",canPlay:Pd.hls,lazyPlayer:pd(function(){return Promise.resolve({default:Dd})})},{key:"file",name:"File Player",canPlay:Pd.file,canEnablePIP:function(e){return Pd.file(e)&&(document.pictureInPictureEnabled||"function"==typeof document.webkitSupportsPresentationMode)},lazyPlayer:pd(function(){return Promise.resolve({default:xd})})}],_d=function(e){function t(){var t=e.apply(this,d([],l(arguments),!1))||this;return t.mounted=!1,t.isReady=!1,t.isPlaying=!1,t.isLoading=!0,t.loadOnReady=null,t.startOnPlay=!0,t.seekOnPlay=null,t.onDurationCalled=!1,t.handlePlayerMount=function(e){t.player||(t.player=e,t.player.load(t.props.src)),t.progress()},t.getInternalPlayer=function(e){return t.player?t.player.getInternalPlayer(e):null},t.progress=function(){var e,i;if(t.props.src&&t.player&&t.isReady){var s=t.getCurrentTime()||0,r=t.getSecondsLoaded(),n=t.getDuration();if(n){var a={playedSeconds:s,played:s/n,loaded:0,loadedSeconds:0};null!==r&&(a.loadedSeconds=r,a.loaded=r/n),a.playedSeconds===t.prevPlayed&&a.loadedSeconds===t.prevLoaded||null===(i=(e=t.props).onProgress)||void 0===i||i.call(e,a),t.prevPlayed=a.playedSeconds,t.prevLoaded=a.loadedSeconds}}t.progressTimeout=window.setTimeout(t.progress,t.props.progressInterval||1e3)},t.handleReady=function(){if(t.mounted){t.isReady=!0,t.isLoading=!1;var e=t.props,i=e.onReady,s=e.playing,r=e.volume,n=e.muted;i(),n||null===r||t.player.setVolume(r),t.loadOnReady?(t.player.load(t.loadOnReady,!0),t.loadOnReady=null):s&&t.player.play(),t.handleDurationCheck()}},t.handlePlay=function(){t.isPlaying=!0,t.isLoading=!1;var e=t.props,i=e.onStart,s=e.onPlay,r=e.playbackRate;t.startOnPlay&&(t.player.setPlaybackRate&&1!==r&&t.player.setPlaybackRate(r),null==i||i(),t.startOnPlay=!1),null==s||s(),t.seekOnPlay&&(t.seekTo(t.seekOnPlay),t.seekOnPlay=null),t.handleDurationCheck()},t.handlePause=function(e){var i,s;t.isPlaying=!1,t.isLoading||null===(s=(i=t.props).onPause)||void 0===s||s.call(i,e)},t.handleEnded=function(){var e=t.props,i=e.activePlayer,s=e.loop,r=e.onEnded;i.loopOnEnded&&s&&t.seekTo(0),s||(t.isPlaying=!1,null==r||r())},t.handleError=function(){for(var e,i,s=[],r=0;r<arguments.length;r++)s[r]=arguments[r];t.isLoading=!1,null===(i=(e=t.props).onError)||void 0===i||i.call(e,s[0],s[1],s[2],s[3])},t.handleDurationCheck=function(){var e,i;clearTimeout(t.durationCheckTimeout);var s=t.getDuration();s?t.onDurationCalled||(null===(i=(e=t.props).onDuration)||void 0===i||i.call(e,s),t.onDurationCalled=!0):t.durationCheckTimeout=window.setTimeout(t.handleDurationCheck,100)},t.handleLoaded=function(){t.isLoading=!1},t}return i(t,e),t.prototype.componentDidMount=function(){this.mounted=!0},t.prototype.componentWillUnmount=function(){clearTimeout(this.progressTimeout),clearTimeout(this.durationCheckTimeout),this.mounted=!1},t.prototype.componentDidUpdate=function(e){var t=this;if(this.player){var i=this.props,s=i.src,r=i.playing,n=i.volume,a=i.muted,o=i.playbackRate,l=i.loop,d=i.activePlayer;if(e.src!==s){if(this.isLoading&&!d.forceLoad&&!vd(s))return console.warn("StormcloudPlayer: the attempt to load ".concat(s," is being deferred until the player has loaded")),void(this.loadOnReady=s||null);this.isLoading=!0,this.startOnPlay=!0,this.onDurationCalled=!1,this.player.load(s,this.isReady)}e.playing||!r||this.isPlaying||this.player.play(),e.playing&&!r&&this.isPlaying&&this.player.pause(),e.volume!==n&&null!==n&&this.player.setVolume(n),e.muted!==a&&(a?this.player.mute():(this.player.unmute(),null!==n&&setTimeout(function(){return t.player.setVolume(n)}))),e.playbackRate!==o&&this.player.setPlaybackRate&&this.player.setPlaybackRate(o),e.loop!==l&&this.player.setLoop&&this.player.setLoop(l)}},t.prototype.getDuration=function(){return this.isReady?this.player.getDuration():null},t.prototype.getCurrentTime=function(){return this.isReady?this.player.getCurrentTime():null},t.prototype.getSecondsLoaded=function(){return this.isReady?this.player.getSecondsLoaded():null},t.prototype.seekTo=function(e,t,i){var s=this;if(this.isReady){if(t?"fraction"===t:e>0&&e<1){var r=this.player.getDuration();return r?void this.player.seekTo(r*e,i):void console.warn("StormcloudPlayer: could not seek using fraction – duration not yet available")}this.player.seekTo(e,i)}else 0!==e&&(this.seekOnPlay=e,setTimeout(function(){s.seekOnPlay=null},5e3))},t.prototype.render=function(){var e=this.props.activePlayer;return e?b.createElement(e,s(s({},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=gd,t}(A.Component),Md="undefined"!=typeof window&&window.document,Od="undefined"!=typeof globalThis&&globalThis.window&&globalThis.window.document,Fd=Md||Od?A.Suspense:function(){return null},Ud=["src","playing","loop","controls","volume","muted","playbackRate","width","height","style","progressInterval","playsInline","autoplay","preload","poster","className","wrapperClassName","wrapperStyle","allowNativeHls","lowLatencyMode","driftToleranceMs","immediateManifestAds","debugAdTiming","showCustomControls","licenseKey","adFailsafeTimeoutMs","minSegmentsBeforePlay","onReady","onStart","onPlay","onPause","onBuffer","onBufferEnd","onEnded","onError","onDuration","onSeek","onProgress","onVolumeToggle","onFullscreenToggle","onControlClick"],Nd=[],Bd=function(e,t){var r;return r=function(r){function n(){var i=r.apply(this,d([],l(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(i){var s,r;if(!i)return null;try{for(var n=o(d(d([],l(Nd),!1),l(e),!1)),a=n.next();!a.done;a=n.next()){var c=a.value;if(c.canPlay(i))return c}}catch(e){s={error:e}}finally{try{a&&!a.done&&(r=n.return)&&r.call(n)}finally{if(s)throw s.error}}return t||null},i.getAttributes=function(e){return md(i.props,Ud)},i.handleReady=function(){var e,t;null===(t=(e=i.props).onReady)||void 0===t||t.call(e,i)},i.seekTo=function(e,t,s){if(!i.player)return null;i.player.seekTo(e,t,s)},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?b.createElement(_d,s(s({},i.props),{key:t.key,ref:i.references.player,activePlayer:t.lazyPlayer||t,onReady:i.handleReady})):null},i}return i(n,r),n.prototype.render=function(){var e=this.props,t=e.src,i=e.style,r=e.width,n=e.height,a=e.fallback,o=e.wrapper,l=this.getAttributes(t),d="string"==typeof o?this.references.wrapper:void 0;return b.createElement(o,s({ref:d,style:s(s({},i),{width:r,height:n})},l),b.createElement(Fd,{fallback:a},this.renderActivePlayer(t)))},n}(A.Component),r.displayName="StormcloudPlayer",r.defaultProps=s(s({},gd),{fallback:null,wrapper:"div"}),r.addCustomPlayer=function(e){Nd.push(e)},r.removeCustomPlayers=function(){Nd.length=0},r.canPlay=function(t){var i,s;try{for(var r=o(d(d([],l(Nd),!1),l(e),!1)),n=r.next();!n.done;n=r.next()){if(n.value.canPlay(t))return!0}}catch(e){i={error:e}}finally{try{n&&!n.done&&(s=r.return)&&s.call(r)}finally{if(i)throw i.error}}return!1},r.canEnablePIP=function(t){var i,s;try{for(var r=o(d(d([],l(Nd),!1),l(e),!1)),n=r.next();!n.done;n=r.next()){var a=n.value;if(a.canEnablePIP&&a.canEnablePIP(t))return!0}}catch(e){i={error:e}}finally{try{n&&!n.done&&(s=r.return)&&s.call(r)}finally{if(i)throw i.error}}return!1},r},$d=Bd(Cd,Cd[Cd.length-1]);e.IS_BROWSER=Ed,e.IS_GLOBAL=Sd,e.IS_IOS=Ad,e.IS_SAFARI=bd,e.SUPPORTS_DASH=function(){if(!Ed)return!1;var e=document.createElement("video");return Boolean(e.canPlayType("application/dash+xml"))},e.SUPPORTS_HLS=function(){if(!Ed)return!1;var e=document.createElement("video");return Boolean(e.canPlayType("application/vnd.apple.mpegurl"))},e.StormcloudPlayer=$d,e.StormcloudVideoPlayer=jl,e.StormcloudVideoPlayerComponent=hd,e.canPlay=Pd,e.createHlsAdPlayer=Nl,e.createImaController=Ul,e.createStormcloudPlayer=Bd,e.default=hd,e.detectBrowser=_l,e.getBrowserConfigOverrides=Fl,e.getBrowserID=Vl,e.getClientInfo=$l,e.getRecommendedAdPlayer=function(){return _l().recommendedAdPlayer},e.initializePolyfills=Kl,e.isMediaStream=vd,e.lazy=pd,e.logBrowserInfo=Ol,e.merge=yd,e.omit=md,e.parseQuery=function(e){var t={},i=e.split("?")[1]||"";if(!i)return t;var s=function(e){e.split("&").forEach(function(e){var i=l(e.split("="),2),s=i[0],r=i[1];if(s)try{t[decodeURIComponent(s)]=r?decodeURIComponent(r.replace(/\+/g," ")):""}catch(e){t[s]=r||""}})};if("undefined"!=typeof URLSearchParams)try{return new URLSearchParams(i).forEach(function(e,i){t[i]=e}),t}catch(e){s(i)}else s(i);return t},e.players=Cd,e.randomString=function(){return Math.random().toString(36).substr(2,9)},e.sendHeartbeat=Hl,e.sendInitialTracking=Gl,e.supportsFeature=function(e){switch(e){case"ima":return Ml();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.supportsGoogleIMA=Ml,e.supportsModernJS=function(){try{return"undefined"!=typeof Promise&&"undefined"!=typeof Map&&"undefined"!=typeof Set&&void 0!==Array.from&&void 0!==Object.assign&&void 0!==Array.prototype.forEach&&void 0!==String.prototype.includes}catch(e){return!1}},e.supportsWebKitPresentationMode=function(){return"undefined"!=typeof window&&"webkitSupportsPresentationMode"in document.createElement("video")},Object.defineProperty(e,"__esModule",{value:!0})});
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).StormcloudVP={})}(this,function(e){"use strict";function t(e,t){this.v=e,this.k=t}function r(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=Array(t);r<t;r++)i[r]=e[r];return i}function i(e){if(Array.isArray(e))return e}function n(e,t,r){return t=c(t),g(e,h()?Reflect.construct(t,r||[],c(e).constructor):t.apply(e,r))}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,k(i.key),i)}}function o(e,t,r){return t&&s(e.prototype,t),r&&s(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function l(e,t,r){return(t=k(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function u(){return u="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(e,t,r){var i=y(e,t);if(i){var n=Object.getOwnPropertyDescriptor(i,t);return n.get?n.get.call(arguments.length<3?e:r):n.value}},u.apply(null,arguments)}function c(e){return c=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},c(e)}function d(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&p(e,t)}function h(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(h=function(){return!!e})()}function f(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function v(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function g(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}function p(e,t){return p=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},p(e,t)}function m(e,t){return i(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var i,n,a,s,o=[],l=!0,u=!1;try{if(a=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;l=!1}else for(;!(l=(i=a.call(r)).done)&&(o.push(i.value),o.length!==t);l=!0);}catch(e){u=!0,n=e}finally{try{if(!l&&null!=r.return&&(s=r.return(),Object(s)!==s))return}finally{if(u)throw n}}return o}}(e,t)||b(e,t)||v()}function y(e,t){for(;!{}.hasOwnProperty.call(e,t)&&null!==(e=c(e)););return e}function T(e,t,r,i){var n=u(c(1&i?e.prototype:e),t,r);return 2&i&&"function"==typeof n?function(e){return n.apply(r,e)}:n}function E(e){return function(e){if(Array.isArray(e))return r(e)}(e)||f(e)||b(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function k(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var i=r.call(e,t||"default");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}function S(e){return S="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},S(e)}function b(e,t){if(e){if("string"==typeof e)return r(e,t);var i={}.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?r(e,t):void 0}}function A(e){var r,i;function n(r,i){try{var s=e[r](i),o=s.value,l=o instanceof t;Promise.resolve(l?o.v:o).then(function(t){if(l){var i="return"===r?"return":"next";if(!o.k||t.done)return n(i,t);t=e[i](t).value}a(s.done?"return":"normal",t)},function(e){n("throw",e)})}catch(e){a("throw",e)}}function a(e,t){switch(e){case"return":r.resolve({value:t,done:!0});break;case"throw":r.reject(t);break;default:r.resolve({value:t,done:!1})}(r=r.next)?n(r.key,r.arg):i=null}this._invoke=function(e,t){return new Promise(function(a,s){var o={key:e,arg:t,resolve:a,reject:s,next:null};i?i=i.next=o:(r=i=o,n(e,t))})},"function"!=typeof e.return&&(this.return=void 0)}function L(e){var t="function"==typeof Map?new Map:void 0;return L=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return function(e,t,r){if(h())return Reflect.construct.apply(null,arguments);var i=[null];i.push.apply(i,t);var n=new(e.bind.apply(e,i));return r&&p(n,r.prototype),n}(e,arguments,c(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),p(r,e)},L(e)}A.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},A.prototype.next=function(e){return this._invoke("next",e)},A.prototype.throw=function(e){return this._invoke("throw",e)},A.prototype.return=function(e){return this._invoke("return",e)};var R=function(e,t){return R=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])},R(e,t)};function I(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}R(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var w=function(){return w=Object.assign||function(e){for(var t,r=1,i=arguments.length;r<i;r++)for(var n in t=arguments[r])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e},w.apply(this,arguments)};function P(e,t){var r={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(r[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(e);n<i.length;n++)t.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(e,i[n])&&(r[i[n]]=e[i[n]])}return r}function D(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 x(e,t){var r,i,n,a={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]},s=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return s.next=o(0),s.throw=o(1),s.return=o(2),"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(o){return function(l){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,o[0]&&(a=0)),a;)try{if(r=1,i&&(n=2&o[0]?i.return:o[0]?i.throw||((n=i.return)&&n.call(i),0):i.next)&&!(n=n.call(i,o[1])).done)return n;switch(i=0,n&&(o=[2&o[0],n.value]),o[0]){case 0:case 1:n=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,i=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!(n=a.trys,(n=n.length>0&&n[n.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!n||o[1]>n[0]&&o[1]<n[3])){a.label=o[1];break}if(6===o[0]&&a.label<n[1]){a.label=n[1],n=o;break}if(n&&a.label<n[2]){a.label=n[2],a.ops.push(o);break}n[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],i=0}finally{r=n=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}}Object.create;function C(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],i=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function _(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var i,n,a=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(i=a.next()).done;)s.push(i.value)}catch(e){n={error:e}}finally{try{i&&!i.done&&(r=a.return)&&r.call(a)}finally{if(n)throw n.error}}return s}function M(e,t,r){if(r||2===arguments.length)for(var i,n=0,a=t.length;n<a;n++)!i&&n in t||(i||(i=Array.prototype.slice.call(t,0,n)),i[n]=t[n]);return e.concat(i||Array.prototype.slice.call(t))}Object.create;"function"==typeof SuppressedError&&SuppressedError;"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function O(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var F,U={exports:{}},N={};var B,V={exports:{}},G={};function H(){if(B)return G;B=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),n=Symbol.for("react.profiler"),a=Symbol.for("react.consumer"),s=Symbol.for("react.context"),o=Symbol.for("react.forward_ref"),l=Symbol.for("react.suspense"),u=Symbol.for("react.memo"),c=Symbol.for("react.lazy"),d=Symbol.for("react.activity"),h=Symbol.iterator;var f={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},v=Object.assign,g={};function p(e,t,r){this.props=e,this.context=t,this.refs=g,this.updater=r||f}function m(){}function y(e,t,r){this.props=e,this.context=t,this.refs=g,this.updater=r||f}p.prototype.isReactComponent={},p.prototype.setState=function(e,t){if("object"!==S(e)&&"function"!=typeof e&&null!=e)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")},p.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")},m.prototype=p.prototype;var T=y.prototype=new m;T.constructor=y,v(T,p.prototype),T.isPureReactComponent=!0;var E=Array.isArray;function k(){}var b={H:null,A:null,T:null,S:null},A=Object.prototype.hasOwnProperty;function L(t,r,i){var n=i.ref;return{$$typeof:e,type:t,key:r,ref:void 0!==n?n:null,props:i}}function R(t){return"object"===S(t)&&null!==t&&t.$$typeof===e}var I=/\/+/g;function w(e,t){return"object"===S(e)&&null!==e&&null!=e.key?(r=""+e.key,i={"=":"=0",":":"=2"},"$"+r.replace(/[=:]/g,function(e){return i[e]})):t.toString(36);var r,i}function P(r,i,n,a,s){var o=S(r);"undefined"!==o&&"boolean"!==o||(r=null);var l,u,d=!1;if(null===r)d=!0;else switch(o){case"bigint":case"string":case"number":d=!0;break;case"object":switch(r.$$typeof){case e:case t:d=!0;break;case c:return P((d=r._init)(r._payload),i,n,a,s)}}if(d)return s=s(r),d=""===a?"."+w(r,0):a,E(s)?(n="",null!=d&&(n=d.replace(I,"$&/")+"/"),P(s,i,n,"",function(e){return e})):null!=s&&(R(s)&&(l=s,u=n+(null==s.key||r&&r.key===s.key?"":(""+s.key).replace(I,"$&/")+"/")+d,s=L(l.type,u,l.props)),i.push(s)),1;d=0;var f,v=""===a?".":a+":";if(E(r))for(var g=0;g<r.length;g++)d+=P(a=r[g],i,n,o=v+w(a,g),s);else if("function"==typeof(g=null===(f=r)||"object"!==S(f)?null:"function"==typeof(f=h&&f[h]||f["@@iterator"])?f:null))for(r=g.call(r),g=0;!(a=r.next()).done;)d+=P(a=a.value,i,n,o=v+w(a,g++),s);else if("object"===o){if("function"==typeof r.then)return P(function(e){switch(e.status){case"fulfilled":return e.value;case"rejected":throw e.reason;default:switch("string"==typeof e.status?e.then(k,k):(e.status="pending",e.then(function(t){"pending"===e.status&&(e.status="fulfilled",e.value=t)},function(t){"pending"===e.status&&(e.status="rejected",e.reason=t)})),e.status){case"fulfilled":return e.value;case"rejected":throw e.reason}}throw e}(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 P(e,i,"","",function(e){return t.call(r,e,n++)}),i}function x(e){if(-1===e._status){var t=e._result;(t=t()).then(function(t){0!==e._status&&-1!==e._status||(e._status=1,e._result=t)},function(t){0!==e._status&&-1!==e._status||(e._status=2,e._result=t)}),-1===e._status&&(e._status=0,e._result=t)}if(1===e._status)return e._result.default;throw e._result}var C="function"==typeof reportError?reportError:function(e){if("object"===("undefined"==typeof window?"undefined":S(window))&&"function"==typeof window.ErrorEvent){var t=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:"object"===S(e)&&null!==e&&"string"==typeof e.message?String(e.message):String(e),error:e});if(!window.dispatchEvent(t))return}else if("object"===("undefined"==typeof process?"undefined":S(process))&&"function"==typeof process.emit)return void process.emit("uncaughtException",e);console.error(e)},_={map: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(!R(e))throw Error("React.Children.only expected to receive a single React element child.");return e}};return G.Activity=d,G.Children=_,G.Component=p,G.Fragment=r,G.Profiler=n,G.PureComponent=y,G.StrictMode=i,G.Suspense=l,G.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=b,G.__COMPILER_RUNTIME={__proto__:null,c:function(e){return b.H.useMemoCache(e)}},G.cache=function(e){return function(){return e.apply(null,arguments)}},G.cacheSignal=function(){return null},G.cloneElement=function(e,t,r){if(null==e)throw Error("The argument must be a React element, but you passed "+e+".");var i=v({},e.props),n=e.key;if(null!=t)for(a in void 0!==t.key&&(n=""+t.key),t)!A.call(t,a)||"key"===a||"__self"===a||"__source"===a||"ref"===a&&void 0===t.ref||(i[a]=t[a]);var a=arguments.length-2;if(1===a)i.children=r;else if(1<a){for(var s=Array(a),o=0;o<a;o++)s[o]=arguments[o+2];i.children=s}return L(e.type,n,i)},G.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},G.createElement=function(e,t,r){var i,n={},a=null;if(null!=t)for(i in void 0!==t.key&&(a=""+t.key),t)A.call(t,i)&&"key"!==i&&"__self"!==i&&"__source"!==i&&(n[i]=t[i]);var s=arguments.length-2;if(1===s)n.children=r;else if(1<s){for(var o=Array(s),l=0;l<s;l++)o[l]=arguments[l+2];n.children=o}if(e&&e.defaultProps)for(i in s=e.defaultProps)void 0===n[i]&&(n[i]=s[i]);return L(e,a,n)},G.createRef=function(){return{current:null}},G.forwardRef=function(e){return{$$typeof:o,render:e}},G.isValidElement=R,G.lazy=function(e){return{$$typeof:c,_payload:{_status:-1,_result:e},_init:x}},G.memo=function(e,t){return{$$typeof:u,type:e,compare:void 0===t?null:t}},G.startTransition=function(e){var t=b.T,r={};b.T=r;try{var i=e(),n=b.S;null!==n&&n(r,i),"object"===S(i)&&null!==i&&"function"==typeof i.then&&i.then(k,C)}catch(e){C(e)}finally{null!==t&&null!==r.types&&(t.types=r.types),b.T=t}},G.unstable_useCacheRefresh=function(){return b.H.useCacheRefresh()},G.use=function(e){return b.H.use(e)},G.useActionState=function(e,t,r){return b.H.useActionState(e,t,r)},G.useCallback=function(e,t){return b.H.useCallback(e,t)},G.useContext=function(e){return b.H.useContext(e)},G.useDebugValue=function(){},G.useDeferredValue=function(e,t){return b.H.useDeferredValue(e,t)},G.useEffect=function(e,t){return b.H.useEffect(e,t)},G.useEffectEvent=function(e){return b.H.useEffectEvent(e)},G.useId=function(){return b.H.useId()},G.useImperativeHandle=function(e,t,r){return b.H.useImperativeHandle(e,t,r)},G.useInsertionEffect=function(e,t){return b.H.useInsertionEffect(e,t)},G.useLayoutEffect=function(e,t){return b.H.useLayoutEffect(e,t)},G.useMemo=function(e,t){return b.H.useMemo(e,t)},G.useOptimistic=function(e,t){return b.H.useOptimistic(e,t)},G.useReducer=function(e,t,r){return b.H.useReducer(e,t,r)},G.useRef=function(e){return b.H.useRef(e)},G.useState=function(e){return b.H.useState(e)},G.useSyncExternalStore=function(e,t,r){return b.H.useSyncExternalStore(e,t,r)},G.useTransition=function(){return b.H.useTransition()},G.version="19.2.0",G}var K;V.exports;function j(){return K||(K=1,V.exports=H()),V.exports}var q;U.exports;var W=(q||(q=1,U.exports=function(){if(F)return N;F=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function r(t,r,i){var n=null;if(void 0!==i&&(n=""+i),void 0!==r.key&&(n=""+r.key),"key"in r)for(var a in i={},r)"key"!==a&&(i[a]=r[a]);else i=r;return r=i.ref,{$$typeof:e,type:t,key:n,ref:void 0!==r?r:null,props:i}}return N.Fragment=t,N.jsx=r,N.jsxs=r,N}()),U.exports),Y=j(),z=O(Y),X=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},Q=Number.isSafeInteger||function(e){return"number"==typeof e&&Math.abs(e)<=$},$=Number.MAX_SAFE_INTEGER||9007199254740991,J=function(e){return e.NETWORK_ERROR="networkError",e.MEDIA_ERROR="mediaError",e.KEY_SYSTEM_ERROR="keySystemError",e.MUX_ERROR="muxError",e.OTHER_ERROR="otherError",e}({}),Z=function(e){return e.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",e.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",e.KEY_SYSTEM_NO_SESSION="keySystemNoSession",e.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",e.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",e.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",e.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",e.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",e.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",e.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",e.MANIFEST_LOAD_ERROR="manifestLoadError",e.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",e.MANIFEST_PARSING_ERROR="manifestParsingError",e.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",e.LEVEL_EMPTY_ERROR="levelEmptyError",e.LEVEL_LOAD_ERROR="levelLoadError",e.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",e.LEVEL_PARSING_ERROR="levelParsingError",e.LEVEL_SWITCH_ERROR="levelSwitchError",e.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",e.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",e.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",e.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",e.FRAG_LOAD_ERROR="fragLoadError",e.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",e.FRAG_DECRYPT_ERROR="fragDecryptError",e.FRAG_PARSING_ERROR="fragParsingError",e.FRAG_GAP="fragGap",e.REMUX_ALLOC_ERROR="remuxAllocError",e.KEY_LOAD_ERROR="keyLoadError",e.KEY_LOAD_TIMEOUT="keyLoadTimeOut",e.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",e.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",e.BUFFER_APPEND_ERROR="bufferAppendError",e.BUFFER_APPENDING_ERROR="bufferAppendingError",e.BUFFER_STALLED_ERROR="bufferStalledError",e.BUFFER_FULL_ERROR="bufferFullError",e.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",e.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",e.ASSET_LIST_LOAD_ERROR="assetListLoadError",e.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",e.ASSET_LIST_PARSING_ERROR="assetListParsingError",e.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",e.INTERNAL_EXCEPTION="internalException",e.INTERNAL_ABORTED="aborted",e.ATTACH_MEDIA_ERROR="attachMediaError",e.UNKNOWN="unknown",e}({}),ee=function(e){return e.MEDIA_ATTACHING="hlsMediaAttaching",e.MEDIA_ATTACHED="hlsMediaAttached",e.MEDIA_DETACHING="hlsMediaDetaching",e.MEDIA_DETACHED="hlsMediaDetached",e.MEDIA_ENDED="hlsMediaEnded",e.STALL_RESOLVED="hlsStallResolved",e.BUFFER_RESET="hlsBufferReset",e.BUFFER_CODECS="hlsBufferCodecs",e.BUFFER_CREATED="hlsBufferCreated",e.BUFFER_APPENDING="hlsBufferAppending",e.BUFFER_APPENDED="hlsBufferAppended",e.BUFFER_EOS="hlsBufferEos",e.BUFFERED_TO_END="hlsBufferedToEnd",e.BUFFER_FLUSHING="hlsBufferFlushing",e.BUFFER_FLUSHED="hlsBufferFlushed",e.MANIFEST_LOADING="hlsManifestLoading",e.MANIFEST_LOADED="hlsManifestLoaded",e.MANIFEST_PARSED="hlsManifestParsed",e.LEVEL_SWITCHING="hlsLevelSwitching",e.LEVEL_SWITCHED="hlsLevelSwitched",e.LEVEL_LOADING="hlsLevelLoading",e.LEVEL_LOADED="hlsLevelLoaded",e.LEVEL_UPDATED="hlsLevelUpdated",e.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",e.LEVELS_UPDATED="hlsLevelsUpdated",e.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",e.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",e.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",e.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",e.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",e.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",e.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",e.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",e.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",e.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",e.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",e.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",e.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",e.CUES_PARSED="hlsCuesParsed",e.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",e.INIT_PTS_FOUND="hlsInitPtsFound",e.FRAG_LOADING="hlsFragLoading",e.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",e.FRAG_LOADED="hlsFragLoaded",e.FRAG_DECRYPTED="hlsFragDecrypted",e.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",e.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",e.FRAG_PARSING_METADATA="hlsFragParsingMetadata",e.FRAG_PARSED="hlsFragParsed",e.FRAG_BUFFERED="hlsFragBuffered",e.FRAG_CHANGED="hlsFragChanged",e.FPS_DROP="hlsFpsDrop",e.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",e.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",e.ERROR="hlsError",e.DESTROYING="hlsDestroying",e.KEY_LOADING="hlsKeyLoading",e.KEY_LOADED="hlsKeyLoaded",e.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",e.BACK_BUFFER_REACHED="hlsBackBufferReached",e.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",e.ASSET_LIST_LOADING="hlsAssetListLoading",e.ASSET_LIST_LOADED="hlsAssetListLoaded",e.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",e.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",e.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",e.INTERSTITIAL_STARTED="hlsInterstitialStarted",e.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",e.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",e.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",e.INTERSTITIAL_ENDED="hlsInterstitialEnded",e.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",e.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",e.EVENT_CUE_ENTER="hlsEventCueEnter",e}({}),te="manifest",re="level",ie="audioTrack",ne="subtitleTrack",ae="main",se="audio",oe="subtitle",le=function(){return o(function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;a(this,e),this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=r,this.totalWeight_=i},[{key:"sample",value:function(e,t){var r=Math.pow(this.alpha_,e);this.estimate_=t*(1-r)+r*this.estimate_,this.totalWeight_+=e}},{key:"getTotalWeight",value:function(){return this.totalWeight_}},{key:"getEstimate",value:function(){if(this.alpha_){var e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}])}(),ue=function(){return o(function e(t,r,i){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:100;a(this,e),this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new le(t),this.fast_=new le(r),this.defaultTTFB_=n,this.ttfb_=new le(t)},[{key:"update",value:function(e,t){var r=this.slow_,i=this.fast_,n=this.ttfb_;r.halfLife!==e&&(this.slow_=new le(e,r.getEstimate(),r.getTotalWeight())),i.halfLife!==t&&(this.fast_=new le(t,i.getEstimate(),i.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new le(e,n.getEstimate(),n.getTotalWeight()))}},{key:"sample",value:function(e,t){var r=(e=Math.max(e,this.minDelayMs_))/1e3,i=8*t/r;this.fast_.sample(r,i),this.slow_.sample(r,i)}},{key:"sampleTTFB",value:function(e){var t=e/1e3,r=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(r,Math.max(e,5))}},{key:"canEstimate",value:function(){return this.fast_.getTotalWeight()>=this.minWeight_}},{key:"getEstimate",value:function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}},{key:"getEstimateTTFB",value:function(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}},{key:"defaultEstimate",get:function(){return this.defaultEstimate_}},{key:"destroy",value:function(){}}])}();function ce(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=S(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var i=r.call(e,t);if("object"!=S(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==S(t)?t:t+""}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function de(){return de=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var i in r)({}).hasOwnProperty.call(r,i)&&(e[i]=r[i])}return e},de.apply(null,arguments)}function he(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,i)}return r}function fe(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?he(Object(r),!0).forEach(function(t){ce(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):he(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}var ve=o(function e(t,r){a(this,e),this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;var i="[".concat(t,"]:");this.trace=ge,this.debug=r.debug.bind(null,i),this.log=r.log.bind(null,i),this.warn=r.warn.bind(null,i),this.info=r.info.bind(null,i),this.error=r.error.bind(null,i)}),ge=function(){},pe={trace:ge,debug:ge,log:ge,warn:ge,info:ge,error:ge};function me(){return de({},pe)}function ye(e,t,r){return t[e]?t[e].bind(t):function(e,t){var r=self.console[e];return r?r.bind(self.console,"".concat(t?"["+t+"] ":"","[").concat(e,"] >")):ge}(e,r)}var Te=me();var Ee=Te;function ke(){if("undefined"!=typeof self)return(!(arguments.length>0&&void 0!==arguments[0])||arguments[0]||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Se(e,t){var r=Object.keys(e),i=Object.keys(t),n=r.length,a=i.length;return!n||!a||n===a&&!r.some(function(e){return-1===i.indexOf(e)})}function be(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if("undefined"!=typeof TextDecoder){var r=new TextDecoder("utf-8").decode(e);if(t){var i=r.indexOf("\0");return-1!==i?r.substring(0,i):r}return r.replace(/\0/g,"")}for(var n,a,s,o=e.length,l="",u=0;u<o;){if(0===(n=e[u++])&&t)return l;if(0!==n&&3!==n)switch(n>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:l+=String.fromCharCode(n);break;case 12:case 13:a=e[u++],l+=String.fromCharCode((31&n)<<6|63&a);break;case 14:a=e[u++],s=e[u++],l+=String.fromCharCode((15&n)<<12|(63&a)<<6|63&s)}}return l}function Ae(e){for(var t="",r=0;r<e.length;r++){var i=e[r].toString(16);i.length<2&&(i="0"+i),t+=i}return t}function Le(e){return Uint8Array.from(e.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function Re(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ie,we={exports:{}};var Pe=(Ie||(Ie=1,function(e){var t,r,i,n,a;t=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,i=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(e,t,i){if(i=i||{},e=e.trim(),!(t=t.trim())){if(!i.alwaysNormalize)return e;var n=a.parseURL(e);if(!n)throw new Error("Error trying to parse base URL.");return n.path=a.normalizePath(n.path),a.buildURLFromParts(n)}var s=a.parseURL(t);if(!s)throw new Error("Error trying to parse relative URL.");if(s.scheme)return i.alwaysNormalize?(s.path=a.normalizePath(s.path),a.buildURLFromParts(s)):t;var o=a.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=r.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var u={scheme:o.scheme,netLoc:s.netLoc,path:null,params:s.params,query:s.query,fragment:s.fragment};if(!s.netLoc&&(u.netLoc=o.netLoc,"/"!==s.path[0]))if(s.path){var c=o.path,d=c.substring(0,c.lastIndexOf("/")+1)+s.path;u.path=a.normalizePath(d)}else u.path=o.path,s.params||(u.params=o.params,s.query||(u.query=o.query));return null===u.path&&(u.path=i.alwaysNormalize?a.normalizePath(s.path):s.path),a.buildURLFromParts(u)},parseURL:function(e){var r=t.exec(e);return r?{scheme:r[1]||"",netLoc:r[2]||"",path:r[3]||"",params:r[4]||"",query:r[5]||"",fragment:r[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(i,"");e.length!==(e=e.replace(n,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}},e.exports=a}(we)),we.exports),De=o(function e(){a(this,e),this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}),xe="audio",Ce="video",_e="audiovideo",Me=function(){return o(function e(t){var r,i,n;a(this,e),this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof t&&(t={url:t}),this.base=t,(n=Ne(r=this,i="stats"))&&(n.enumerable=!0,Object.defineProperty(r,i,n))},[{key:"setByteRange",value:function(e,t){var r,i=e.split("@",2);r=1===i.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(i[1]),this._byteRange=[r,parseInt(i[0])+r]}},{key:"baseurl",get:function(){return this.base.url}},{key:"byteRange",get:function(){return null===this._byteRange?[]:this._byteRange}},{key:"byteRangeStartOffset",get:function(){return this.byteRange[0]}},{key:"byteRangeEndOffset",get:function(){return this.byteRange[1]}},{key:"elementaryStreams",get:function(){return null===this._streams&&(this._streams=l(l(l({},xe,null),Ce,null),_e,null)),this._streams},set:function(e){this._streams=e}},{key:"hasStats",get:function(){return null!==this._stats}},{key:"hasStreams",get:function(){return null!==this._streams}},{key:"stats",get:function(){return null===this._stats&&(this._stats=new De),this._stats},set:function(e){this._stats=e}},{key:"url",get:function(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Pe.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""},set:function(e){this._url=e}},{key:"clearElementaryStreamInfo",value:function(){var e=this.elementaryStreams;e[xe]=null,e[Ce]=null,e[_e]=null}}])}();function Oe(e){return"initSegment"!==e.sn}var Fe=function(e){function t(e,r){var i;return a(this,t),(i=n(this,t,[r]))._decryptdata=null,i._programDateTime=null,i._ref=null,i._bitrate=void 0,i.rawProgramDateTime=null,i.tagList=[],i.duration=0,i.sn=0,i.levelkeys=void 0,i.type=void 0,i.loader=null,i.keyLoader=null,i.level=-1,i.cc=0,i.startPTS=void 0,i.endPTS=void 0,i.startDTS=void 0,i.endDTS=void 0,i.start=0,i.playlistOffset=0,i.deltaPTS=void 0,i.maxStartPTS=void 0,i.minEndPTS=void 0,i.data=void 0,i.bitrateTest=!1,i.title=null,i.initSegment=null,i.endList=void 0,i.gap=void 0,i.urlId=0,i.type=e,i}return d(t,e),o(t,[{key:"byteLength",get:function(){if(this.hasStats){var e=this.stats.total;if(e)return e}if(this.byteRange.length){var t=this.byteRange[0],r=this.byteRange[1];if(X(t)&&X(r))return r-t}return null}},{key:"bitrate",get:function(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null},set:function(e){this._bitrate=e}},{key:"decryptdata",get:function(){var e,t=this.levelkeys;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(null==(e=this._decryptdata)||!e.keyId){var r=Object.keys(t);if(1===r.length){var i=this._decryptdata=t[r[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,t))}}return this._decryptdata}},{key:"end",get:function(){return this.start+this.duration}},{key:"endProgramDateTime",get:function(){if(null===this.programDateTime)return null;var e=X(this.duration)?this.duration:0;return this.programDateTime+1e3*e}},{key:"encrypted",get:function(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){var t,r=Object.keys(this.levelkeys),i=r.length;if(i>1||1===i&&null!=(t=this.levelkeys[r[0]])&&t.encrypted)return!0}return!1}},{key:"programDateTime",get:function(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime},set:function(e){X(e)?this._programDateTime=e:this._programDateTime=this.rawProgramDateTime=null}},{key:"ref",get:function(){return Oe(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}},{key:"addStart",value:function(e){this.setStart(this.start+e)}},{key:"setStart",value:function(e){this.start=e,this._ref&&(this._ref.start=e)}},{key:"setDuration",value:function(e){this.duration=e,this._ref&&(this._ref.duration=e)}},{key:"setKeyFormat",value:function(e){var t=this.levelkeys;if(t){var r,i=t[e];!i||null!=(r=this._decryptdata)&&r.keyId||(this._decryptdata=i.getDecryptData(this.sn,t))}}},{key:"abortRequests",value:function(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()}},{key:"setElementaryStreamInfo",value:function(e,t,r,i,n){var a=arguments.length>5&&void 0!==arguments[5]&&arguments[5],s=this.elementaryStreams,o=s[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,r),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,n)):s[e]={startPTS:t,endPTS:r,startDTS:i,endDTS:n,partial:a}}}])}(Me),Ue=function(e){function t(e,r,i,s,o){var l;a(this,t),(l=n(this,t,[i])).fragOffset=0,l.duration=0,l.gap=!1,l.independent=!1,l.relurl=void 0,l.fragment=void 0,l.index=void 0,l.duration=e.decimalFloatingPoint("DURATION"),l.gap=e.bool("GAP"),l.independent=e.bool("INDEPENDENT"),l.relurl=e.enumeratedString("URI"),l.fragment=r,l.index=s;var u=e.enumeratedString("BYTERANGE");return u&&l.setByteRange(u,o),o&&(l.fragOffset=o.fragOffset+o.duration),l}return d(t,e),o(t,[{key:"start",get:function(){return this.fragment.start+this.fragOffset}},{key:"end",get:function(){return this.start+this.duration}},{key:"loaded",get:function(){var e=this.elementaryStreams;return!!(e.audio||e.video||e.audiovideo)}}])}(Me);function Ne(e,t){var r=Object.getPrototypeOf(e);if(r){var i=Object.getOwnPropertyDescriptor(r,t);return i||Ne(r,t)}}var Be=Math.pow(2,32)-1,Ve=[].push,Ge={video:1,audio:2,id3:3,text:4};function He(e){return String.fromCharCode.apply(null,e)}function Ke(e,t){var r=e[t]<<8|e[t+1];return r<0?65536+r:r}function je(e,t){var r=We(e,t);return r<0?4294967296+r:r}function qe(e,t){var r=je(e,t);return r*=Math.pow(2,32),r+=je(e,t+4)}function We(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function Ye(e,t){var r=[];if(!t.length)return r;for(var i=e.byteLength,n=0;n<i;){var a=je(e,n),s=a>1?n+a:i;if(He(e.subarray(n+4,n+8))===t[0])if(1===t.length)r.push(e.subarray(n+8,s));else{var o=Ye(e.subarray(n+8,s),t.slice(1));o.length&&Ve.apply(r,o)}n=s}return r}function ze(e){var t=[],r=e[0],i=8,n=je(e,i);i+=4;var a=0,s=0;0===r?(a=je(e,i),s=je(e,i+4),i+=8):(a=qe(e,i),s=qe(e,i+8),i+=16),i+=2;var o=e.length+s,l=Ke(e,i);i+=2;for(var u=0;u<l;u++){var c=i,d=je(e,c);c+=4;var h=2147483647&d;if(1===(2147483648&d)>>>31)return Ee.warn("SIDX has hierarchical references (not supported)"),null;var f=je(e,c);c+=4,t.push({referenceSize:h,subsegmentDuration:f,info:{duration:f/n,start:o,end:o+h-1}}),o+=h,i=c+=4}return{earliestPresentationTime:a,timescale:n,version:r,referencesCount:l,references:t}}function Xe(e){for(var t=[],r=Ye(e,["moov","trak"]),i=0;i<r.length;i++){var n=r[i],a=Ye(n,["tkhd"])[0];if(a){var s=a[0],o=je(a,0===s?12:20),l=Ye(n,["mdia","mdhd"])[0];if(l){var u=je(l,0===(s=l[0])?12:20),c=Ye(n,["mdia","hdlr"])[0];if(c){var d=He(c.subarray(8,12)),h={soun:xe,vide:Ce}[d],f=Qe(Ye(n,["mdia","minf","stbl","stsd"])[0]);h?(t[o]={timescale:u,type:h,stsd:f},t[h]=fe({timescale:u,id:o},f)):t[o]={timescale:u,type:d,stsd:f}}}}}return Ye(e,["moov","mvex","trex"]).forEach(function(e){var r=je(e,4),i=t[r];i&&(i.default={duration:je(e,12),flags:je(e,20)})}),t}function Qe(e){var t,r=e.subarray(8),i=r.subarray(86),n=He(r.subarray(4,8)),a=n,s="enca"===n||"encv"===n;if(s){var o=Ye(r,[n])[0];Ye(o.subarray("enca"===n?28:78),["sinf"]).forEach(function(e){var t=Ye(e,["schm"])[0];if(t){var r=He(t.subarray(4,8));if("cbcs"===r||"cenc"===r){var i=Ye(e,["frma"])[0];i&&(a=He(i))}}})}var l=a;switch(a){case"avc1":case"avc2":case"avc3":case"avc4":var u=Ye(i,["avcC"])[0];u&&u.length>3&&(a+="."+Ze(u[1])+Ze(u[2])+Ze(u[3]),t=$e("avc1"===l?"dva1":"dvav",i));break;case"mp4a":var c=Ye(r,[n])[0],d=Ye(c.subarray(28),["esds"])[0];if(d&&d.length>7){var h=4;if(3!==d[h++])break;h=Je(d,h),h+=2;var f=d[h++];if(128&f&&(h+=2),64&f&&(h+=d[h++]),4!==d[h++])break;h=Je(d,h);var v=d[h++];if(64!==v)break;if(a+="."+Ze(v),h+=12,5!==d[h++])break;h=Je(d,h);var g=d[h++],p=(248&g)>>3;31===p&&(p+=1+((7&g)<<3)+((224&d[h])>>5)),a+="."+p}break;case"hvc1":case"hev1":var m=Ye(i,["hvcC"])[0];if(m&&m.length>12){var y=m[1],T=["","A","B","C"][y>>6],E=31&y,k=je(m,2),S=(32&y)>>5?"H":"L",b=m[12],A=m.subarray(6,12);a+="."+T+E,a+="."+function(e){for(var t=0,r=0;r<32;r++)t|=(e>>r&1)<<31-r;return t>>>0}(k).toString(16).toUpperCase(),a+="."+S+b;for(var L="",R=A.length;R--;){var I=A[R];if(I||L)L="."+I.toString(16).toUpperCase()+L}a+=L}t=$e("hev1"==l?"dvhe":"dvh1",i);break;case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":a=$e(a,i)||a;break;case"vp09":var w=Ye(i,["vpcC"])[0];if(w&&w.length>6){var P=w[4],D=w[5],x=w[6]>>4&15;a+="."+et(P)+"."+et(D)+"."+et(x)}break;case"av01":var C=Ye(i,["av1C"])[0];if(C&&C.length>2){var _=C[1]>>>5,M=31&C[1],O=C[2]>>>7?"H":"M",F=(64&C[2])>>6,U=(32&C[2])>>5,N=2===_&&F?U?12:10:F?10:8,B=(16&C[2])>>4,V=(8&C[2])>>3,G=(4&C[2])>>2,H=3&C[2];a+="."+_+"."+et(M)+O+"."+et(N)+"."+B+"."+V+G+H+"."+et(1)+"."+et(1)+"."+et(1)+".0",t=$e("dav1",i)}}return{codec:a,encrypted:s,supplemental:t}}function $e(e,t){var r=Ye(t,["dvvC"]),i=r.length?r[0]:Ye(t,["dvcC"])[0];if(i){var n=i[2]>>1&127,a=i[2]<<5&32|i[3]>>3&31;return e+"."+et(n)+"."+et(a)}}function Je(e,t){for(var r=t+5;128&e[t++]&&t<r;);return t}function Ze(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function et(e){return(e<10?"0":"")+e}function tt(e,t){Ye(e,["moov","trak"]).forEach(function(e){var r=Ye(e,["mdia","minf","stbl","stsd"])[0];if(r){var i=r.subarray(8),n=Ye(i,["enca"]),a=n.length>0;a||(n=Ye(i,["encv"])),n.forEach(function(e){Ye(a?e.subarray(28):e.subarray(78),["sinf"]).forEach(function(e){var r=rt(e);r&&t(r,a)})})}})}function rt(e){var t=Ye(e,["schm"])[0];if(t){var r=He(t.subarray(4,8));if("cbcs"===r||"cenc"===r){var i=Ye(e,["schi","tenc"])[0];if(i)return i}}}function it(e,t){var r=new Uint8Array(e.length+t.length);return r.set(e),r.set(t,e.length),r}function nt(e,t){var r=[],i=t.samples,n=t.timescale,a=t.id,s=!1;return Ye(i,["moof"]).map(function(o){var l=o.byteOffset-8;Ye(o,["traf"]).map(function(o){var u=Ye(o,["tfdt"]).map(function(e){var t=e[0],r=je(e,4);return 1===t&&(r*=Math.pow(2,32),r+=je(e,8)),r/n})[0];return void 0!==u&&(e=u),Ye(o,["tfhd"]).map(function(u){var c=je(u,4),d=16777215&je(u,0),h=0,f=!!(16&d),v=0,g=!!(32&d),p=8;c===a&&(!!(1&d)&&(p+=8),!!(2&d)&&(p+=4),!!(8&d)&&(h=je(u,p),p+=4),f&&(v=je(u,p),p+=4),g&&(p+=4),"video"===t.type&&(s=at(t.codec)),Ye(o,["trun"]).map(function(a){var o=a[0],u=16777215&je(a,0),c=!!(1&u),d=0,f=!!(4&u),g=!!(256&u),p=0,m=!!(512&u),y=0,T=!!(1024&u),E=!!(2048&u),k=0,S=je(a,4),b=8;c&&(d=je(a,b),b+=4),f&&(b+=4);for(var A=d+l,L=0;L<S;L++){if(g?(p=je(a,b),b+=4):p=h,m?(y=je(a,b),b+=4):y=v,T&&(b+=4),E&&(k=0===o?je(a,b):We(a,b),b+=4),t.type===Ce)for(var R=0;R<y;){var I=je(i,A);if(st(s,i[A+=4]))ot(i.subarray(A,A+I),s?2:1,e+k/n,r);A+=I,R+=I+4}e+=p/n}}))})})}),r}function at(e){if(!e)return!1;var t=e.substring(0,4);return"hvc1"===t||"hev1"===t||"dvh1"===t||"dvhe"===t}function st(e,t){if(e){var r=t>>1&63;return 39===r||40===r}return 6===(31&t)}function ot(e,t,r,i){var n=lt(e),a=0;a+=t;for(var s=0,o=0,l=0;a<n.length;){s=0;do{if(a>=n.length)break;s+=l=n[a++]}while(255===l);o=0;do{if(a>=n.length)break;o+=l=n[a++]}while(255===l);var u=n.length-a,c=a;if(o<u)a+=o;else if(o>u){Ee.error("Malformed SEI payload. ".concat(o," is too small, only ").concat(u," bytes left to parse."));break}if(4===s){if(181===n[c++]){var d=Ke(n,c);if(c+=2,49===d){var h=je(n,c);if(c+=4,1195456820===h){var f=n[c++];if(3===f){var v=n[c++],g=64&v,p=g?2+3*(31&v):0,m=new Uint8Array(p);if(g){m[0]=v;for(var y=1;y<p;y++)m[y]=n[c++]}i.push({type:f,payloadType:s,pts:r,bytes:m})}}}}}else if(5===s&&o>16){for(var T=[],E=0;E<16;E++){var k=n[c++].toString(16);T.push(1==k.length?"0"+k:k),3!==E&&5!==E&&7!==E&&9!==E||T.push("-")}for(var S=o-16,b=new Uint8Array(S),A=0;A<S;A++)b[A]=n[c++];i.push({payloadType:s,pts:r,uuid:T.join(""),userData:be(b),userDataBytes:b})}}}function lt(e){for(var t=e.byteLength,r=[],i=1;i<t-2;)0===e[i]&&0===e[i+1]&&3===e[i+2]?(r.push(i+2),i+=2):i++;if(0===r.length)return e;var n=t-r.length,a=new Uint8Array(n),s=0;for(i=0;i<n;s++,i++)s===r[0]&&(s++,r.shift()),a[i]=e[s];return a}function ut(e,t,r){if(16!==e.byteLength)throw new RangeError("Invalid system id");var i,n;i=new Uint8Array,n=new Uint8Array;var a=new Uint8Array(4);return r.byteLength>0&&new DataView(a.buffer).setUint32(0,r.byteLength,!1),function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];for(var n=r.length,a=8,s=n;s--;)a+=r[s].byteLength;var o=new Uint8Array(a);for(o[0]=a>>24&255,o[1]=a>>16&255,o[2]=a>>8&255,o[3]=255&a,o.set(e,4),s=0,a=8;s<n;s++)o.set(r[s],a),a+=r[s].byteLength;return o}([112,115,115,104],new Uint8Array([0,0,0,0]),e,n,i,a,r)}function ct(e){var t=e.getUint32(0),r=e.byteOffset,i=e.byteLength;if(i<t)return{offset:r,size:i};if(1886614376!==e.getUint32(4))return{offset:r,size:t};var n=e.getUint32(8)>>>24;if(0!==n&&1!==n)return{offset:r,size:t};var a=e.buffer,s=Ae(new Uint8Array(a,r+12,16)),o=null,l=0;if(0===n)l=28;else{var u=e.getUint32(28);if(!u||i<32+16*u)return{offset:r,size:t};o=[];for(var c=0;c<u;c++)o.push(new Uint8Array(a,r+32+16*c,16));l=32+16*u}if(!l)return{offset:r,size:t};var d=e.getUint32(l);return t-32<d?{offset:r,size:t}:{version:n,systemId:s,kids:o,data:new Uint8Array(a,r+l+4,d),offset:r,size:t}}var dt=function(){return/\(Windows.+Firefox\//i.test(navigator.userAgent)},ht={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function ft(e,t){var r=ht[t];return!!r&&!!r[e.slice(0,4)]}function vt(e,t){var r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return!e.split(",").some(function(e){return!gt(e,t,r)})}function gt(e,t){var r,i=ke(!(arguments.length>2&&void 0!==arguments[2])||arguments[2]);return null!=(r=null==i?void 0:i.isTypeSupported(pt(e,t)))&&r}function pt(e,t){return"".concat(t,"/mp4;codecs=").concat(e)}function mt(e){if(e){var t=e.substring(0,4);return ht.video[t]}return 2}function yt(e){var t=dt();return e.split(",").reduce(function(e,r){var i=t&&at(r)?9:ht.video[r];return i?(2*i+e)/(e?3:2):(ht.audio[r]+e)/(e?2:1)},0)}var Tt={};var Et=/flac|opus|mp4a\.40\.34/i;function kt(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return e.replace(Et,function(e){return function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(Tt[e])return Tt[e];for(var r={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e],i=0;i<r.length;i++){var n;if(gt(r[i],"audio",t))return Tt[e]=r[i],r[i];if("mp3"===r[i]&&null!=(n=ke(t))&&n.isTypeSupported("audio/mpeg"))return""}return e}(e.toLowerCase(),t)})}function St(e,t){if(e&&(e.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e))&&(bt(e,"audio")||bt(e,"video")))return e;if(t){var r=t.split(",");if(r.length>1){if(e)for(var i=r.length;i--;)if(r[i].substring(0,4)===e.substring(0,4))return r[i];return r[0]}}return t||e}function bt(e,t){return ft(e,t)&>(e,t)}function At(e){if(e.startsWith("av01.")){for(var t=e.split("."),r=["0","111","01","01","01","0"],i=t.length;i>4&&i<10;i++)t[i]=r[i-4];return t.join(".")}return e}function Lt(e){var t=ke(e)||{isTypeSupported:function(){return!1}};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Rt(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}var It={supported:!1,smooth:!1,powerEfficient:!1},wt={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function Pt(e,t){return{supported:!1,configurations:t,decodingInfoResults:[It],error:e}}function Dt(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},n=e.videoCodec;if(!n&&!e.audioCodec||!r)return Promise.resolve(wt);for(var a=[],s=function(e){var t,r=null==(t=e.videoCodec)?void 0:t.split(","),i=Ct(e),n=e.width||640,a=e.height||480,s=e.frameRate||30,o=e.videoRange.toLowerCase();return r?r.map(function(e){var t={contentType:pt(At(e),"video"),width:n,height:a,bitrate:i,framerate:s};return"sdr"!==o&&(t.transferFunction=o),t}):[]}(e),o=s.length,l=function(e,t,r){var i,n=null==(i=e.audioCodec)?void 0:i.split(","),a=Ct(e);if(n&&e.audioGroups)return e.audioGroups.reduce(function(e,i){var s,o=i?null==(s=t.groups[i])?void 0:s.tracks:null;return o?o.reduce(function(e,t){if(t.groupId===i){var s=parseFloat(t.channels||"");n.forEach(function(t){var i={contentType:pt(t,"audio"),bitrate:r?xt(t,a):a};s&&(i.channels=""+s),e.push(i)})}return e},e):e},[]);return[]}(e,t,o>0),u=l.length,c=o||1*u||1;c--;){var d={type:"media-source"};if(o&&(d.video=s[c%o]),u){d.audio=l[c%u];var h=d.audio.bitrate;d.video&&h&&(d.video.bitrate-=h)}a.push(d)}if(n){var f=navigator.userAgent;if(n.split(",").some(function(e){return at(e)})&&dt())return Promise.resolve(Pt(new Error("Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (".concat(f,")")),a))}return Promise.all(a.map(function(e){var t=function(e){var t="",r=e.audio,i=e.video;if(i){var n=Rt(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=Rt(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 xt(e,t){if(t<=1)return 1;var r=128e3;return"ec-3"===e?r=768e3:"ac-3"===e&&(r=64e4),Math.min(t/2,r)}function Ct(e){return 1e3*Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)/1e3)||1}var _t=["NONE","TYPE-0","TYPE-1",null];var Mt=["SDR","PQ","HLG"];var Ot="",Ft="YES",Ut="v2";function Nt(e){var t=e.canSkipUntil,r=e.canSkipDateRanges,i=e.age;return t&&i<t/2?r?Ut:Ft:Ot}var Bt=function(){return o(function e(t,r,i){a(this,e),this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=r,this.skip=i},[{key:"addDirectives",value:function(e){var t=new self.URL(e);return void 0!==this.msn&&t.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}])}(),Vt=function(){return o(function e(t){if(a(this,e),this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[t.url],this._attrs=[t.attrs],this.bitrate=t.bitrate,t.details&&(this.details=t.details),this.id=t.id||0,this.name=t.name,this.width=t.width||0,this.height=t.height||0,this.frameRate=t.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=t.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,this.codecSet=[t.videoCodec,t.audioCodec].filter(function(e){return!!e}).map(function(e){return e.substring(0,4)}).join(","),"supplemental"in t){var r;this.supplemental=t.supplemental;var i=null==(r=t.supplemental)?void 0:r.videoCodec;i&&i!==t.videoCodec&&(this.codecSet+=",".concat(i.substring(0,4)))}this.addGroupId("audio",t.attrs.AUDIO),this.addGroupId("text",t.attrs.SUBTITLES)},[{key:"maxBitrate",get:function(){return Math.max(this.realBitrate,this.bitrate)}},{key:"averageBitrate",get:function(){return this._avgBitrate||this.realBitrate||this.bitrate}},{key:"attrs",get:function(){return this._attrs[0]}},{key:"codecs",get:function(){return this.attrs.CODECS||""}},{key:"pathwayId",get:function(){return this.attrs["PATHWAY-ID"]||"."}},{key:"videoRange",get:function(){return this.attrs["VIDEO-RANGE"]||"SDR"}},{key:"score",get:function(){return this.attrs.optionalFloat("SCORE",0)}},{key:"uri",get:function(){return this.url[0]||""}},{key:"hasAudioGroup",value:function(e){return Gt(this._audioGroups,e)}},{key:"hasSubtitleGroup",value:function(e){return Gt(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 Gt(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}function Ht(e,t){var r=!1,i=[];if(e&&(r="SDR"!==e,i=[e]),t){var n="SDR"!==(i=t.allowedVideoRanges||Mt.slice(0)).join("")&&!t.videoCodec;(r=void 0!==t.preferHDR?t.preferHDR:n&&function(){if("function"==typeof matchMedia){var e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}())||(i=["SDR"])}return{preferHDR:r,allowedVideoRanges:i}}var Kt=function(e,t){return JSON.stringify(e,function(e){var t=new WeakSet;return function(r,i){if(e&&(i=e(r,i)),"object"===S(i)&&null!==i){if(t.has(i))return;t.add(i)}return i}}(t))};function jt(e,t){Ee.log('[abr] start candidates with "'.concat(e,'" ignored because ').concat(t))}function qt(e){return e.reduce(function(e,t){var r=e.groups[t.groupId];r||(r=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),r.tracks.push(t);var i=t.channels||"2";return r.channels[i]=(r.channels[i]||0)+1,r.hasDefault=r.hasDefault||t.default,r.hasAutoSelect=r.hasAutoSelect||t.autoselect,r.hasDefault&&(e.hasDefaultAudio=!0),r.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Wt(e){return e?{lang:e.lang,assocLang:e.assocLang,characteristics:e.characteristics,channels:e.channels,audioCodec:e.audioCodec}:e}function Yt(e,t,r){if("attrs"in e){var i=t.indexOf(e);if(-1!==i)return i}for(var n=0;n<t.length;n++){if(zt(e,t[n],r))return n}return-1}function zt(e,t,r){var i=e.groupId,n=e.name,a=e.lang,s=e.assocLang,o=e.default,l=e.forced;return(void 0===i||t.groupId===i)&&(void 0===n||t.name===n)&&(void 0===a||function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"--";if(e.length===t.length)return e===t;return e.startsWith(t)||t.startsWith(e)}(a,t.lang))&&(void 0===a||t.assocLang===s)&&(void 0===o||t.default===o)&&(void 0===l||t.forced===l)&&(!("characteristics"in e)||function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",r=e.split(","),i=t.split(",");return r.length===i.length&&!r.some(function(e){return-1===i.indexOf(e)})}(e.characteristics||"",t.characteristics))&&(void 0===r||r(e,t))}function Xt(e,t){var r=e.audioCodec,i=e.channels;return!(void 0!==r&&(t.audioCodec||"").substring(0,4)!==r.substring(0,4)||void 0!==i&&i!==(t.channels||"2"))}function Qt(e,t,r){for(var i=t;i>-1;i--)if(r(e[i]))return i;for(var n=t+1;n<e.length;n++)if(r(e[n]))return n;return-1}function $t(e,t){var r;return!!e&&e!==(null==(r=t.loadLevelObj)?void 0:r.uri)}var Jt=function(e){function t(e){var r;return a(this,t),(r=n(this,t,["abr",e.logger])).hls=void 0,r.lastLevelLoadSec=0,r.lastLoadedFragLevel=-1,r.firstSelection=-1,r._nextAutoLevel=-1,r.nextAutoLevelKey="",r.audioTracksByGroup=null,r.codecTiers=null,r.timer=-1,r.fragCurrent=null,r.partCurrent=null,r.bitrateTestDelay=0,r.rebufferNotice=-1,r.supportedCache={},r.bwEstimator=void 0,r._abandonRulesCheck=function(e){var t,i=r,n=i.fragCurrent,a=i.partCurrent,s=i.hls,o=s.autoLevelEnabled,l=s.media;if(n&&l){var u=performance.now(),c=a?a.stats:n.stats,d=a?a.duration:n.duration,h=u-c.loading.start,f=s.minAutoLevel,v=n.level,g=r._nextAutoLevel;if(c.aborted||c.loaded&&c.loaded===c.total||v<=f)return r.clearTimer(),void(r._nextAutoLevel=-1);if(o){var p=g>-1&&g!==v,m=!!e||p;if(m||!l.paused&&l.playbackRate&&l.readyState){var y=s.mainForwardBufferInfo;if(m||null!==y){var T=r.bwEstimator.getEstimateTTFB(),E=Math.abs(l.playbackRate);if(!(h<=Math.max(T,d/(2*E)*1e3))){var k=y?y.len/E:0,S=c.loading.first?c.loading.first-c.loading.start:-1,b=c.loaded&&S>-1,A=r.getBwEstimate(),L=s.levels,R=L[v],I=Math.max(c.loaded,Math.round(d*(n.bitrate||R.averageBitrate)/8)),w=b?h-S:h;w<1&&b&&(w=Math.min(h,8*c.loaded/A));var P=b?1e3*c.loaded/w:0,D=T/1e3,x=P?(I-c.loaded)/P:8*I/A+D;if(!(x<=k)){var C,_=P?8*P:A,M=!0===(null==(t=(null==e?void 0:e.details)||r.hls.latestLevelDetails)?void 0:t.live),O=r.hls.config.abrBandWidthUpFactor,F=Number.POSITIVE_INFINITY;for(C=v-1;C>f;C--){var U=L[C].maxBitrate,N=!L[C].details||M;if((F=r.getTimeToLoadFrag(D,_,d*U,N))<Math.min(k,d+D))break}if(!(F>=x||F>10*d)){b?r.bwEstimator.sample(h-Math.min(T,S),c.loaded):r.bwEstimator.sampleTTFB(h);var B=L[C].maxBitrate;r.getBwEstimate()*O>B&&r.resetEstimator(B);var V=r.findBestLevel(B,f,C,0,k,1,1);V>-1&&(C=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(k.toFixed(3)," s\n Estimated load time for current fragment: ").concat(x.toFixed(3)," s\n Estimated load time for down switch fragment: ").concat(F.toFixed(3)," s\n TTFB estimate: ").concat(0|S," ms\n Current BW estimate: ").concat(X(A)?0|A:"Unknown"," bps\n New BW estimate: ").concat(0|r.getBwEstimate()," bps\n Switching to level ").concat(C," @ ").concat(0|B," bps")),s.nextLoadLevel=s.nextAutoLevel=C,r.clearTimer();var G=function(){if(r.clearTimer(),r.fragCurrent===n&&r.hls.loadLevel===C&&C>0){var e=r.getStarvationDelay();if(r.warn("Aborting inflight request ".concat(C>0?"and switching down":"","\n Fragment duration: ").concat(n.duration.toFixed(3)," s\n Time to underbuffer: ").concat(e.toFixed(3)," s")),n.abortRequests(),r.fragCurrent=r.partCurrent=null,C>f){var t=r.findBestLevel(r.hls.levels[f].bitrate,f,C,0,e,1,1);-1===t&&(t=f),r.hls.nextLoadLevel=r.hls.nextAutoLevel=t,r.resetEstimator(r.hls.levels[t].bitrate)}}};p||x>2*F?G():r.timer=self.setInterval(G,1e3*F),s.trigger(ee.FRAG_LOAD_EMERGENCY_ABORTED,{frag:n,part:a,stats:c})}}}}}}}},r.hls=e,r.bwEstimator=r.initEstimator(),r.registerListeners(),r}return d(t,e),o(t,[{key:"resetEstimator",value:function(e){e&&(this.log("setting initial bwe to ".concat(e)),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}},{key:"initEstimator",value:function(){var e=this.hls.config;return new ue(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}},{key:"registerListeners",value:function(){var e=this.hls;e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.FRAG_LOADING,this.onFragLoading,this),e.on(ee.FRAG_LOADED,this.onFragLoaded,this),e.on(ee.FRAG_BUFFERED,this.onFragBuffered,this),e.on(ee.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(ee.LEVEL_LOADED,this.onLevelLoaded,this),e.on(ee.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(ee.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(ee.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.FRAG_LOADING,this.onFragLoading,this),e.off(ee.FRAG_LOADED,this.onFragLoaded,this),e.off(ee.FRAG_BUFFERED,this.onFragBuffered,this),e.off(ee.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(ee.LEVEL_LOADED,this.onLevelLoaded,this),e.off(ee.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(ee.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(ee.ERROR,this.onError,this))}},{key:"destroy",value:function(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}},{key:"onManifestLoading",value:function(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}},{key:"onLevelsUpdated",value:function(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}},{key:"onMaxAutoLevelUpdated",value:function(){this.firstSelection=-1,this.nextAutoLevelKey=""}},{key:"onFragLoading",value:function(e,t){var r=t.frag;if(!this.ignoreFragment(r)){var i;if(!r.bitrateTest)this.fragCurrent=r,this.partCurrent=null!=(i=t.part)?i:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}},{key:"onLevelSwitching",value:function(e,t){this.clearTimer()}},{key:"onError",value:function(e,t){if(!t.fatal)switch(t.details){case Z.BUFFER_ADD_CODEC_ERROR:case Z.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case Z.FRAG_LOAD_TIMEOUT:var r=t.frag,i=this.fragCurrent,n=this.partCurrent;if(r&&i&&r.sn===i.sn&&r.level===i.level){var a=performance.now(),s=n?n.stats:r.stats,o=a-s.loading.start,l=s.loading.first?s.loading.first-s.loading.start:-1;if(s.loaded&&l>-1){var u=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(o-Math.min(u,l),s.loaded)}else this.bwEstimator.sampleTTFB(o)}}}},{key:"getTimeToLoadFrag",value:function(e,t,r,i){return e+r/t+(i?e+this.lastLevelLoadSec:0)}},{key:"onLevelLoaded",value:function(e,t){var r=this.hls.config,i=t.stats.loading,n=i.end-i.first;X(n)&&(this.lastLevelLoadSec=n/1e3),t.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}},{key:"onFragLoaded",value:function(e,t){var r=t.frag,i=t.part,n=i?i.stats:r.stats;if(r.type===ae&&this.bwEstimator.sampleTTFB(n.loading.first-n.loading.start),!this.ignoreFragment(r)){if(this.clearTimer(),r.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){var a=i?i.duration:r.duration,s=this.hls.levels[r.level],o=(s.loaded?s.loaded.bytes:0)+n.loaded,l=(s.loaded?s.loaded.duration:0)+a;s.loaded={bytes:o,duration:l},s.realBitrate=Math.round(8*o/l)}if(r.bitrateTest){var u={stats:n,frag:r,part:i,id:r.type};this.onFragBuffered(ee.FRAG_BUFFERED,u),r.bitrateTest=!1}else this.lastLoadedFragLevel=r.level}}},{key:"onFragBuffered",value:function(e,t){var r=t.frag,i=t.part,n=null!=i&&i.stats.loaded?i.stats:r.stats;if(!n.aborted&&!this.ignoreFragment(r)){var a=n.parsing.end-n.loading.start-Math.min(n.loading.first-n.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,n.loaded),n.bwEstimate=this.getBwEstimate(),r.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}}},{key:"ignoreFragment",value:function(e){return e.type!==ae||"initSegment"===e.sn}},{key:"clearTimer",value:function(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}},{key:"firstAutoLevel",get:function(){var e=this.hls,t=e.maxAutoLevel,r=e.minAutoLevel,i=this.getBwEstimate(),n=this.hls.config.maxStarvationDelay,a=this.findBestLevel(i,r,t,0,n,1,1);if(a>-1)return a;var s=this.hls.firstLevel,o=Math.min(Math.max(s,r),t);return this.warn("Could not find best starting auto level. Defaulting to first in playlist ".concat(s," clamped to ").concat(o)),o}},{key:"forcedAutoLevel",get:function(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}},{key:"nextAutoLevel",get:function(){var e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),r=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&r&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;var i=t&&r?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){var n=this.hls.levels;if(n.length>Math.max(e,i)&&n[e].loadError<=n[i].loadError)return e}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i},set:function(e){var t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}},{key:"getAutoLevelKey",value:function(){return"".concat(this.getBwEstimate(),"_").concat(this.getStarvationDelay().toFixed(2))}},{key:"getNextABRAutoLevel",value:function(){var e=this.fragCurrent,t=this.partCurrent,r=this.hls;if(r.levels.length<=1)return r.loadLevel;var i=r.maxAutoLevel,n=r.config,a=r.minAutoLevel,s=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay(),u=n.abrBandWidthFactor,c=n.abrBandWidthUpFactor;if(l){var d=this.findBestLevel(o,a,i,l,0,u,c);if(d>=0)return this.rebufferNotice=-1,d}var h=s?Math.min(s,n.maxStarvationDelay):n.maxStarvationDelay;if(!l){var f=this.bitrateTestDelay;if(f)h=(s?Math.min(s,n.maxLoadingDelay):n.maxLoadingDelay)-f,this.info("bitrate test took ".concat(Math.round(1e3*f),"ms, set first fragment max fetchDuration to ").concat(Math.round(1e3*h)," ms")),u=c=1}var v=this.findBestLevel(o,a,i,l,h,u,c);if(this.rebufferNotice!==v&&(this.rebufferNotice=v,this.info("".concat(l?"rebuffering expected":"buffer is empty",", optimal quality level ").concat(v))),v>-1)return v;var g=r.levels[a],p=r.loadLevelObj;return p&&(null==g?void 0:g.bitrate)<p.bitrate?a:r.loadLevel}},{key:"getStarvationDelay",value:function(){var e=this.hls,t=e.media;if(!t)return 1/0;var r=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/r}},{key:"getBwEstimate",value:function(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}},{key:"findBestLevel",value:function(e,t,r,i,n,a,s){var o,l=this,u=i+n,c=this.lastLoadedFragLevel,d=-1===c?this.hls.firstLevel:c,h=this.fragCurrent,f=this.partCurrent,v=this.hls,g=v.levels,p=v.allAudioTracks,m=v.loadLevel,y=v.config;if(1===g.length)return 0;var T,E=g[d],k=!(null==(o=this.hls.latestLevelDetails)||!o.live),S=-1===m||-1===c,b="SDR",A=(null==E?void 0:E.frameRate)||0,L=y.audioPreference,R=y.videoPreference,I=this.audioTracksByGroup||(this.audioTracksByGroup=qt(p)),w=-1;if(S){if(-1!==this.firstSelection)return this.firstSelection;var P=this.codecTiers||(this.codecTiers=function(e,t,r,i){return e.slice(r,i+1).reduce(function(e,r,i){if(!r.codecSet)return e;var n=r.audioGroups,a=e[r.codecSet];a||(e[r.codecSet]=a={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:i,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!n,fragmentError:0}),a.minBitrate=Math.min(a.minBitrate,r.bitrate);var s=Math.min(r.height,r.width);return a.minHeight=Math.min(a.minHeight,s),a.minFramerate=Math.min(a.minFramerate,r.frameRate),a.minIndex=Math.min(a.minIndex,i),a.maxScore=Math.max(a.maxScore,r.score),a.fragmentError+=r.fragmentError,a.videoRanges[r.videoRange]=(a.videoRanges[r.videoRange]||0)+1,n&&n.forEach(function(e){if(e){var r=t.groups[e];r&&(a.hasDefaultAudio=a.hasDefaultAudio||t.hasDefaultAudio?r.hasDefault:r.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(r.channels).forEach(function(e){a.channels[e]=(a.channels[e]||0)+r.channels[e]}))}}),e},{})}(g,I,t,r)),D=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=Ht(t,n),T=y.preferHDR,E=y.allowedVideoRanges,k=function(){var t=e[a[S]];c||(c=t.channels[2]>0),h=Math.min(h,t.minHeight),f=Math.min(f,t.minFramerate),v=Math.min(v,t.minBitrate),E.filter(function(e){return t.videoRanges[e]>0}).length>0&&(d=!0)},S=a.length;S--;)k();h=X(h)?h:0,f=X(f)?f:0;var b=Math.max(1080,h),A=Math.max(30,f);v=X(v)?v:r,r=Math.max(v,r),d||(t=void 0);var L=a.length>1;return{codecSet:a.reduce(function(t,i){var n=e[i];if(i===t)return t;if(m=d?E.filter(function(e){return n.videoRanges[e]>0}):[],L){if(n.minBitrate>r)return jt(i,"min bitrate of ".concat(n.minBitrate," > current estimate of ").concat(r)),t;if(!n.hasDefaultAudio)return jt(i,"no renditions with default or auto-select sound found"),t;if(o&&i.indexOf(o.substring(0,4))%5!=0)return jt(i,'audio codec preference "'.concat(o,'" not found')),t;if(s&&!u){if(!n.channels[s])return jt(i,"no renditions with ".concat(s," channel sound found (channels options: ").concat(Object.keys(n.channels),")")),t}else if((!o||u)&&c&&0===n.channels[2])return jt(i,"no renditions with stereo sound found"),t;if(n.minHeight>b)return jt(i,"min resolution of ".concat(n.minHeight," > maximum of ").concat(b)),t;if(n.minFramerate>A)return jt(i,"min framerate of ".concat(n.minFramerate," > maximum of ").concat(A)),t;if(!m.some(function(e){return n.videoRanges[e]>0}))return jt(i,"no variants with VIDEO-RANGE of ".concat(Kt(m)," found")),t;if(l&&i.indexOf(l.substring(0,4))%5!=0)return jt(i,'video codec preference "'.concat(l,'" not found')),t;if(n.maxScore<p)return jt(i,"max score of ".concat(n.maxScore," < selected max of ").concat(p)),t}return t&&(yt(i)>=yt(t)||n.fragmentError>e[t].fragmentError)?t:(g=n.minIndex,p=n.maxScore,i)},void 0),videoRanges:m,preferHDR:T,minFramerate:f,minBitrate:v,minIndex:g}}(P,b,e,L,R),x=D.codecSet,C=D.videoRanges,_=D.minFramerate,M=D.minBitrate,O=D.minIndex,F=D.preferHDR;w=O,T=x,b=F?C[C.length-1]:C[0],A=_,e=Math.max(e,M),this.log("picked start tier ".concat(Kt(D)))}else T=null==E?void 0:E.codecSet,b=null==E?void 0:E.videoRange;for(var U,N,B=f?f.duration:h?h.duration:0,V=this.bwEstimator.getEstimateTTFB()/1e3,G=[],H=function(){var t=g[K],o=K>d;if(!t)return 0;if(y.useMediaCapabilities&&!t.supportedResult&&!t.supportedPromise){var h=navigator.mediaCapabilities;"function"==typeof(null==h?void 0:h.decodingInfo)&&function(e,t,r,i,n,a){var s=e.videoCodec,o=e.audioCodec?e.audioGroups:null,l=null==a?void 0:a.audioCodec,u=null==a?void 0:a.channels,c=u?parseInt(u):l?1/0:2,d=null;if(null!=o&&o.length)try{d=1===o.length&&o[0]?t.groups[o[0]].channels:o.reduce(function(e,r){if(r){var i=t.groups[r];if(!i)throw new Error("Audio track group ".concat(r," not found"));Object.keys(i.channels).forEach(function(t){e[t]=(e[t]||0)+i.channels[t]})}return e},{2:0})}catch(e){return!0}return void 0!==s&&(s.split(",").some(function(e){return at(e)})||e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(i,30)||"SDR"!==e.videoRange&&e.videoRange!==r||e.bitrate>Math.max(n,8e6))||!!d&&X(c)&&Object.keys(d).some(function(e){return parseInt(e)>c})}(t,I,b,A,e,L)?(t.supportedPromise=Dt(t,I,h,l.supportedCache),t.supportedPromise.then(function(e){if(l.hls){t.supportedResult=e;var r=l.hls.levels,i=r.indexOf(t);e.error?l.warn('MediaCapabilities decodingInfo error: "'.concat(e.error,'" for level ').concat(i," ").concat(Kt(e))):e.supported?e.decodingInfoResults.some(function(e){return!1===e.smooth||!1===e.powerEfficient})&&l.log("MediaCapabilities decodingInfo for level ".concat(i," not smooth or powerEfficient: ").concat(Kt(e))):(l.warn("Unsupported MediaCapabilities decodingInfo result for level ".concat(i," ").concat(Kt(e))),i>-1&&r.length>1&&(l.log("Removing unsupported level ".concat(i)),l.hls.removeLevel(i),-1===l.hls.loadLevel&&(l.hls.nextLoadLevel=0)))}}).catch(function(e){l.warn("Error handling MediaCapabilities decodingInfo: ".concat(e))})):t.supportedResult=wt}if((T&&t.codecSet!==T||b&&t.videoRange!==b||o&&A>t.frameRate||!o&&A>0&&A<t.frameRate||null!=(U=t.supportedResult)&&null!=(U=U.decodingInfoResults)&&U.some(function(e){return!1===e.smooth}))&&(!S||K!==w))return G.push(K),0;var v,p=t.details,E=(f?null==p?void 0:p.partTarget:null==p?void 0:p.averagetargetduration)||B;v=o?s*e:a*e;var R=B&&i>=2*B&&0===n?t.averageBitrate:t.maxBitrate,P=l.getTimeToLoadFrag(V,v,R*E,void 0===p);if(v>=R&&(K===c||0===t.loadError&&0===t.fragmentError)&&(P<=V||!X(P)||k&&!l.bitrateTestDelay||P<u)){var D=l.forcedAutoLevel;return K===m||-1!==D&&D===m||(G.length&&l.trace("Skipped level(s) ".concat(G.join(",")," of ").concat(r,' max with CODECS and VIDEO-RANGE:"').concat(g[G[0]].codecs,'" ').concat(g[G[0]].videoRange,'; not compatible with "').concat(T,'" ').concat(b)),l.info("switch candidate:".concat(d,"->").concat(K," adjustedbw(").concat(Math.round(v),")-bitrate=").concat(Math.round(v-R)," ttfb:").concat(V.toFixed(1)," avgDuration:").concat(E.toFixed(1)," maxFetchDuration:").concat(u.toFixed(1)," fetchDuration:").concat(P.toFixed(1)," firstSelection:").concat(S," codecSet:").concat(t.codecSet," videoRange:").concat(t.videoRange," hls.loadLevel:").concat(m))),S&&(l.firstSelection=K),{v:K}}},K=r;K>=t;K--)if(0!==(N=H())&&N)return N.v;return-1}},{key:"deriveNextAutoLevel",value:function(e){var t=this.hls,r=t.maxAutoLevel,i=t.minAutoLevel;return Math.min(Math.max(e,i),r)}}])}(ve),Zt=function(e,t){for(var r=0,i=e.length-1,n=null,a=null;r<=i;){var s=t(a=e[n=(r+i)/2|0]);if(s>0)r=n+1;else{if(!(s<0))return a;i=n-1}}return null};function er(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:.005,a=null;if(e){a=t[1+e.sn-t[0].sn]||null;var s=e.endDTS-r;s>0&&s<15e-7&&(r+=15e-7),a&&e.level!==a.level&&a.end<=e.end&&(a=t[2+e.sn-t[0].sn]||null)}else 0===r&&0===t[0].start&&(a=t[0]);if(a&&((!e||e.level===a.level)&&0===tr(r,i,a)||function(e,t,r){if(t&&0===t.start&&t.level<e.level&&(t.endPTS||0)>0){var i=t.tagList.reduce(function(e,t){return"INF"===t[0]&&(e+=parseFloat(t[1])),e},r);return e.start<=i}return!1}(a,e,Math.min(n,i))))return a;var o=Zt(t,tr.bind(null,r,i));return!o||o===e&&a?a:o}function tr(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2?arguments[2]:void 0;if(r.start<=e&&r.start+r.duration>e)return 0;var i=Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-i<=e?1:r.start-i>e&&r.start?-1:0}function rr(e,t,r){var i=1e3*Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-i>e}function ir(e,t,r){if(e&&e.startCC<=t&&e.endCC>=t){var i,n=e.fragments,a=e.fragmentHint;return a&&(n=n.concat(a)),Zt(n,function(e){return e.cc<t?1:e.cc>t?-1:(i=e,e.end<=r?1:e.start>r?-1:0)}),i||null}return null}function nr(e){switch(e.details){case Z.FRAG_LOAD_TIMEOUT:case Z.KEY_LOAD_TIMEOUT:case Z.LEVEL_LOAD_TIMEOUT:case Z.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function ar(e){return e.details.startsWith("key")}function sr(e){return ar(e)&&!!e.frag&&!e.frag.decryptdata}function or(e,t){var r=nr(t);return e.default["".concat(r?"timeout":"error","Retry")]}function lr(e,t){var r="linear"===e.backoff?1:Math.pow(2,t);return Math.min(r*e.retryDelayMs,e.maxRetryDelayMs)}function ur(e){return fe(fe({},e),{errorRetry:null,timeoutRetry:null})}function cr(e,t,r,i){if(!e)return!1;var n=null==i?void 0:i.code,a=t<e.maxNumRetry&&(function(e){return dr(e)||!!e&&(e<400||e>499)}(n)||!!r);return e.shouldRetry?e.shouldRetry(e,t,r,i,a):a}function dr(e){return 0===e&&!1===navigator.onLine}var hr=0,fr=2,vr=3,gr=5,pr=0,mr=1,yr=2,Tr=4,Er=function(e){function t(e){var r;return a(this,t),(r=n(this,t,["error-controller",e.logger])).hls=void 0,r.playlistError=0,r.hls=e,r.registerListeners(),r}return d(t,e),o(t,[{key:"registerListeners",value:function(){var e=this.hls;e.on(ee.ERROR,this.onError,this),e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.LEVEL_UPDATED,this.onLevelUpdated,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ee.ERROR,this.onError,this),e.off(ee.ERROR,this.onErrorOut,this),e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.LEVEL_UPDATED,this.onLevelUpdated,this))}},{key:"destroy",value:function(){this.unregisterListeners(),this.hls=null}},{key:"startLoad",value:function(e){}},{key:"stopLoad",value:function(){this.playlistError=0}},{key:"getVariantLevelIndex",value:function(e){return(null==e?void 0:e.type)===ae?e.level:this.getVariantIndex()}},{key:"getVariantIndex",value:function(){var e,t=this.hls,r=t.currentLevel;return null!=(e=t.loadLevelObj)&&e.details||-1===r?t.loadLevel:r}},{key:"variantHasKey",value:function(e,t){if(e){var r;if(null!=(r=e.details)&&r.hasKey(t))return!0;var i=e.audioGroups;if(i)return this.hls.allAudioTracks.filter(function(e){return i.indexOf(e.groupId)>=0}).some(function(e){var r;return null==(r=e.details)?void 0:r.hasKey(t)})}return!1}},{key:"onManifestLoading",value:function(){this.playlistError=0}},{key:"onLevelUpdated",value:function(){this.playlistError=0}},{key:"onError",value:function(e,t){var r;if(!t.fatal){var i=this.hls,n=t.context;switch(t.details){case Z.FRAG_LOAD_ERROR:case Z.FRAG_LOAD_TIMEOUT:case Z.KEY_LOAD_ERROR:case Z.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case Z.FRAG_PARSING_ERROR:if(null!=(r=t.frag)&&r.gap)return void(t.errorAction=kr());case Z.FRAG_GAP:case Z.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=fr);case Z.LEVEL_EMPTY_ERROR:case Z.LEVEL_PARSING_ERROR:var a,s=t.parent===ae?t.level:i.loadLevel;return void(t.details===Z.LEVEL_EMPTY_ERROR&&null!=(a=t.context)&&null!=(a=a.levelDetails)&&a.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,s)));case Z.LEVEL_LOAD_ERROR:case Z.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==n?void 0:n.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level)));case Z.AUDIO_TRACK_LOAD_ERROR:case Z.AUDIO_TRACK_LOAD_TIMEOUT:case Z.SUBTITLE_LOAD_ERROR:case Z.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){var o=i.loadLevelObj;if(o&&(n.type===ie&&o.hasAudioGroup(n.groupId)||n.type===ne&&o.hasSubtitleGroup(n.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.loadLevel),t.errorAction.action=fr,void(t.errorAction.flags=mr)}return;case Z.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(t.errorAction={action:fr,flags:yr});case Z.KEY_SYSTEM_SESSION_UPDATE_FAILED:case Z.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case Z.KEY_SYSTEM_NO_SESSION:return void(t.errorAction={action:fr,flags:Tr});case Z.BUFFER_ADD_CODEC_ERROR:case Z.REMUX_ALLOC_ERROR:case Z.BUFFER_APPEND_ERROR:var l;if(!t.errorAction)t.errorAction=this.getLevelSwitchAction(t,null!=(l=t.level)?l:i.loadLevel);return;case Z.INTERNAL_EXCEPTION:case Z.BUFFER_APPENDING_ERROR:case Z.BUFFER_FULL_ERROR:case Z.LEVEL_SWITCH_ERROR:case Z.BUFFER_STALLED_ERROR:case Z.BUFFER_SEEK_OVER_HOLE:case Z.BUFFER_NUDGE_ON_STALL:return void(t.errorAction=kr())}t.type===J.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=kr())}}},{key:"getPlaylistRetryOrSwitchAction",value:function(e,t){var r=or(this.hls.config.playlistLoadPolicy,e),i=this.playlistError++;if(cr(r,i,nr(e),e.response))return{action:gr,flags:pr,retryConfig:r,retryCount:i};var n=this.getLevelSwitchAction(e,t);return r&&(n.retryConfig=r,n.retryCount=i),n}},{key:"getFragRetryOrSwitchAction",value:function(e){var t=this.hls,r=this.getVariantLevelIndex(e.frag),i=t.levels[r],n=t.config,a=n.fragLoadPolicy,s=n.keyLoadPolicy,o=or(ar(e)?s:a,e),l=t.levels.reduce(function(e,t){return e+t.fragmentError},0);if(i&&(e.details!==Z.FRAG_GAP&&i.fragmentError++,!sr(e)&&cr(o,l,nr(e),e.response)))return{action:gr,flags:pr,retryConfig:o,retryCount:l};var u=this.getLevelSwitchAction(e,r);return o&&(u.retryConfig=o,u.retryCount=l),u}},{key:"getLevelSwitchAction",value:function(e,t){var r=this.hls;null==t&&(t=r.loadLevel);var i=this.hls.levels[t];if(i){var n,a,s=e.details;i.loadError++,s===Z.BUFFER_APPEND_ERROR&&i.fragmentError++;var o=-1,l=r.levels,u=r.loadLevel,c=r.minAutoLevel,d=r.maxAutoLevel;r.autoLevelEnabled||r.config.preserveManualLevelOnError||(r.loadLevel=-1);for(var h,f,v,g=null==(n=e.frag)?void 0:n.type,p=(g===se&&s===Z.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&(s===Z.BUFFER_ADD_CODEC_ERROR||s===Z.BUFFER_APPEND_ERROR))&&l.some(function(e){var t=e.audioCodec;return i.audioCodec!==t}),m="video"===e.sourceBufferName&&(s===Z.BUFFER_ADD_CODEC_ERROR||s===Z.BUFFER_APPEND_ERROR)&&l.some(function(e){var t=e.codecSet,r=e.audioCodec;return i.codecSet!==t&&i.audioCodec===r}),y=null!=(a=e.context)?a:{},T=y.type,E=y.groupId,k=function(){var t=(S+u)%l.length;if(t!==u&&t>=c&&t<=d&&0===l[t].loadError){var r=l[t];if(s===Z.FRAG_GAP&&g===ae&&e.frag){var n=l[t].details;if(n){var a=er(e.frag,n.fragments,e.frag.start);if(null!=a&&a.gap)return 0}}else{if(T===ie&&r.hasAudioGroup(E)||T===ne&&r.hasSubtitleGroup(E))return 0;if(g===se&&null!=(h=i.audioGroups)&&h.some(function(e){return r.hasAudioGroup(e)})||g===oe&&null!=(f=i.subtitleGroups)&&f.some(function(e){return r.hasSubtitleGroup(e)})||p&&i.audioCodec===r.audioCodec||m&&i.codecSet===r.codecSet||!p&&i.codecSet!==r.codecSet)return 0}return o=t,1}},S=l.length;S--&&(0===(v=k())||1!==v););if(o>-1&&r.loadLevel!==o)return e.levelRetry=!0,this.playlistError=0,{action:fr,flags:pr,nextAutoLevel:o}}return{action:fr,flags:mr}}},{key:"onErrorOut",value:function(e,t){var r;switch(null==(r=t.errorAction)?void 0:r.action){case hr:break;case fr:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===Z.FRAG_GAP?/MediaSource readyState: ended/.test(t.error.message)&&(this.warn('MediaSource ended after "'.concat(t.sourceBufferName,'" sourceBuffer append error. Attempting to recover from media error.')),this.hls.recoverMediaError()):t.fatal=!0}t.fatal&&this.hls.stopLoad()}},{key:"sendAlternateToPenaltyBox",value:function(e){var t=this.hls,r=e.errorAction;if(r){var i=r.flags,n=r.nextAutoLevel;switch(i){case pr:this.switchLevel(e,n);break;case yr:var a=this.getVariantLevelIndex(e.frag),s=t.levels[a],o=null==s?void 0:s.attrs["HDCP-LEVEL"];if(r.hdcpLevel=o,"NONE"===o)this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(o){t.maxHdcpLevel=_t[_t.indexOf(o)-1],r.resolved=!0,this.warn('Restricting playback to HDCP-LEVEL of "'.concat(t.maxHdcpLevel,'" or lower'));break}case Tr:var l=e.decryptdata;if(l){for(var u=this.hls.levels,c=u.length,d=c;d--;){var h,f;if(this.variantHasKey(u[d],l))this.log("Banned key found in level ".concat(d," (").concat(u[d].bitrate,'bps) or audio group "').concat(null==(h=u[d].audioGroups)?void 0:h.join(","),'" (').concat(null==(f=e.frag)?void 0:f.type," fragment) ").concat(Ae(l.keyId||[]))),u[d].fragmentError++,u[d].loadError++,this.log("Removing level ".concat(d," with key error (").concat(e.error,")")),this.hls.removeLevel(d)}var v=e.frag;if(this.hls.levels.length<c)r.resolved=!0;else if(v&&v.type!==ae){var g=v.decryptdata;g&&!l.matches(g)&&(r.resolved=!0)}}}r.resolved||this.switchLevel(e,n)}}},{key:"switchLevel",value:function(e,t){if(void 0!==t&&e.errorAction&&(this.warn("switching to level ".concat(t," after ").concat(e.details)),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===Z.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&"audiovideo"!==e.sourceBufferName))for(var r=Rt(e.mimeType),i=this.hls.levels,n=i.length;n--;)i[n]["".concat(e.sourceBufferName,"Codec")]===r&&(this.log("Removing level ".concat(n," for ").concat(e.details,' ("').concat(r,'" not supported)')),this.hls.removeLevel(n))}}])}(ve);function kr(e){var t={action:hr,flags:pr};return e&&(t.resolved=!0),t}var Sr="NOT_LOADED",br="APPENDING",Ar="PARTIAL",Lr="OK",Rr=function(){return o(function e(t){a(this,e),this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=t,this._registerListeners()},[{key:"_registerListeners",value:function(){var e=this.hls;e&&(e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.BUFFER_APPENDED,this.onBufferAppended,this),e.on(ee.FRAG_BUFFERED,this.onFragBuffered,this),e.on(ee.FRAG_LOADED,this.onFragLoaded,this))}},{key:"_unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.BUFFER_APPENDED,this.onBufferAppended,this),e.off(ee.FRAG_BUFFERED,this.onFragBuffered,this),e.off(ee.FRAG_LOADED,this.onFragLoaded,this))}},{key:"destroy",value:function(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}},{key:"getAppendedFrag",value:function(e,t){var r=this.activePartLists[t];if(r)for(var i=r.length;i--;){var n=r[i];if(!n)break;if(n.start<=e&&e<=n.end&&n.loaded)return n}return this.getBufferedFrag(e,t)}},{key:"getBufferedFrag",value:function(e,t){return this.getFragAtPos(e,t,!0)}},{key:"getFragAtPos",value:function(e,t,r){for(var i=this.fragments,n=Object.keys(i),a=n.length;a--;){var s=i[n[a]];if((null==s?void 0:s.body.type)===t&&(!r||s.buffered)){var o=s.body;if(o.start<=e&&e<=o.end)return o}}return null}},{key:"detectEvictedFragments",value:function(e,t,r,i,n){var a=this;this.timeRanges&&(this.timeRanges[e]=t);var s=(null==i?void 0:i.fragment.sn)||-1;Object.keys(this.fragments).forEach(function(i){var o=a.fragments[i];if(o&&!(s>=o.body.sn))if(o.buffered||o.loaded&&!n){var l=o.range[e];l&&(0!==l.time.length?l.time.some(function(e){var r=!a.isTimeBuffered(e.startPTS,e.endPTS,t);return r&&a.removeFragment(o.body),r}):a.removeFragment(o.body))}else o.body.type===r&&a.removeFragment(o.body)})}},{key:"detectPartialFragments",value:function(e){var t=this,r=this.timeRanges;if(r&&"initSegment"!==e.frag.sn){var i=e.frag,n=wr(i),a=this.fragments[n];if(!(!a||a.buffered&&i.gap)){var s=!i.relurl;if(Object.keys(r).forEach(function(n){var o=i.elementaryStreams[n];if(o){var l=r[n],u=s||!0===o.partial;a.range[n]=t.getBufferedTimes(i,e.part,u,l)}}),a.loaded=null,Object.keys(a.range).length)a.buffered=!0,(a.body.endList=i.endList||a.body.endList)&&(this.endListFragments[a.body.type]=a),Ir(a)||this.removeParts(i.sn-1,i.type);else this.removeFragment(a.body)}}}},{key:"removeParts",value:function(e,t){var r=this.activePartLists[t];r&&(this.activePartLists[t]=Pr(r,function(t){return t.fragment.sn>=e}))}},{key:"fragBuffered",value:function(e,t){var r=wr(e),i=this.fragments[r];!i&&t&&(i=this.fragments[r]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,i.buffered=!0)}},{key:"getBufferedTimes",value:function(e,t,r,i){for(var n={time:[],partial:r},a=e.start,s=e.end,o=e.minEndPTS||s,l=e.maxStartPTS||a,u=0;u<i.length;u++){var c=i.start(u)-this.bufferPadding,d=i.end(u)+this.bufferPadding;if(l>=c&&o<=d){n.time.push({startPTS:Math.max(a,i.start(u)),endPTS:Math.min(s,i.end(u))});break}if(a<d&&s>c){var h=Math.max(a,i.start(u)),f=Math.min(s,i.end(u));f>h&&(n.partial=!0,n.time.push({startPTS:h,endPTS:f}))}else if(s<=c)break}return n}},{key:"getPartialFragment",value:function(e){var t,r,i,n=null,a=0,s=this.bufferPadding,o=this.fragments;return Object.keys(o).forEach(function(l){var u=o[l];u&&Ir(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||Ir(t))}},{key:"getState",value:function(e){var t=wr(e),r=this.fragments[t];return r?r.buffered?Ir(r)?Ar:Lr:br:Sr}},{key:"isTimeBuffered",value:function(e,t,r){for(var i,n,a=0;a<r.length;a++){if(i=r.start(a)-this.bufferPadding,n=r.end(a)+this.bufferPadding,e>=i&&t<=n)return!0;if(t<=i)return!1}return!1}},{key:"onManifestLoading",value:function(){this.removeAllFragments()}},{key:"onFragLoaded",value:function(e,t){if("initSegment"!==t.frag.sn&&!t.frag.bitrateTest){var r=t.frag,i=t.part?null:t,n=wr(r);this.fragments[n]={body:r,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}}},{key:"onBufferAppended",value:function(e,t){var r=t.frag,i=t.part,n=t.timeRanges,a=t.type;if("initSegment"!==r.sn){var s=r.type;if(i){var o=this.activePartLists[s];o||(this.activePartLists[s]=o=[]),o.push(i)}this.timeRanges=n;var l=n[a];this.detectEvictedFragments(a,l,s,i)}}},{key:"onFragBuffered",value:function(e,t){this.detectPartialFragments(t)}},{key:"hasFragment",value:function(e){var t=wr(e);return!!this.fragments[t]}},{key:"hasFragments",value:function(e){var t=this.fragments,r=Object.keys(t);if(!e)return r.length>0;for(var i=r.length;i--;){var n=t[r[i]];if((null==n?void 0:n.body.type)===e)return!0}return!1}},{key:"hasParts",value:function(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)}},{key:"removeFragmentsInRange",value:function(e,t,r,i,n){var a=this;i&&!this.hasGaps||Object.keys(this.fragments).forEach(function(s){var o=a.fragments[s];if(o){var l=o.body;l.type!==r||i&&!l.gap||l.start<t&&l.end>e&&(o.buffered||n)&&a.removeFragment(l)}})}},{key:"removeFragment",value:function(e){var t=wr(e);e.clearElementaryStreamInfo();var r=this.activePartLists[e.type];if(r){var i=e.sn;this.activePartLists[e.type]=Pr(r,function(e){return e.fragment.sn!==i})}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}},{key:"removeAllFragments",value:function(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;var t=null==(e=this.hls)||null==(e=e.latestLevelDetails)?void 0:e.partList;t&&t.forEach(function(e){return e.clearElementaryStreamInfo()})}}])}();function Ir(e){var t,r,i;return e.buffered&&!!(e.body.gap||null!=(t=e.range.video)&&t.partial||null!=(r=e.range.audio)&&r.partial||null!=(i=e.range.audiovideo)&&i.partial)}function wr(e){return"".concat(e.type,"_").concat(e.level,"_").concat(e.sn)}function Pr(e,t){return e.filter(function(e){var r=t(e);return r||e.clearElementaryStreamInfo(),r})}var Dr=0,xr=1,Cr=function(){return o(function e(t,r,i){a(this,e),this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=r,this.aesMode=i},[{key:"decrypt",value:function(e,t){switch(this.aesMode){case Dr:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case xr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error("[AESCrypto] invalid aes mode ".concat(this.aesMode))}}}])}();var _r=function(){return o(function e(){a(this,e),this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()},[{key:"uint8ArrayToUint32Array_",value:function(e){for(var t=new DataView(e),r=new Uint32Array(4),i=0;i<4;i++)r[i]=t.getUint32(4*i);return r}},{key:"initTable",value:function(){var e=this.sBox,t=this.invSBox,r=this.subMix,i=r[0],n=r[1],a=r[2],s=r[3],o=this.invSubMix,l=o[0],u=o[1],c=o[2],d=o[3],h=new Uint32Array(256),f=0,v=0,g=0;for(g=0;g<256;g++)h[g]=g<128?g<<1:g<<1^283;for(g=0;g<256;g++){var p=v^v<<1^v<<2^v<<3^v<<4;p=p>>>8^255&p^99,e[f]=p,t[p]=f;var m=h[f],y=h[m],T=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*T^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[T^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,T=this.invSBox,E=this.invSubMix,k=E[0],S=E[1],b=E[2],A=E[3],L=this.uint8ArrayToUint32Array_(r),R=L[0],I=L[1],w=L[2],P=L[3],D=new Int32Array(e),x=new Int32Array(D.length),C=this.networkToHostOrderSwap;t<D.length;){for(d=C(D[t]),h=C(D[t+1]),f=C(D[t+2]),v=C(D[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=k[o>>>24]^S[l>>16&255]^b[u>>8&255]^A[255&c]^y[g],n=k[l>>>24]^S[u>>16&255]^b[c>>8&255]^A[255&o]^y[g+1],a=k[u>>>24]^S[c>>16&255]^b[o>>8&255]^A[255&l]^y[g+2],s=k[c>>>24]^S[o>>16&255]^b[l>>8&255]^A[255&u]^y[g+3],o=i,l=n,u=a,c=s,g+=4;i=T[o>>>24]<<24^T[l>>16&255]<<16^T[u>>8&255]<<8^T[255&c]^y[g],n=T[l>>>24]<<24^T[u>>16&255]<<16^T[c>>8&255]<<8^T[255&o]^y[g+1],a=T[u>>>24]<<24^T[c>>16&255]<<16^T[o>>8&255]<<8^T[255&l]^y[g+2],s=T[c>>>24]<<24^T[o>>16&255]<<16^T[l>>8&255]<<8^T[255&u]^y[g+3],x[t]=C(i^R),x[t+1]=C(s^I),x[t+2]=C(a^w),x[t+3]=C(n^P),R=d,I=h,w=f,P=v,t+=4}return x.buffer}}])}(),Mr=function(){return o(function e(t,r,i){a(this,e),this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=t,this.key=r,this.aesMode=i},[{key:"expandKey",value:function(){var e=function(e){switch(e){case Dr:return"AES-CBC";case xr:return"AES-CTR";default:throw new Error("[FastAESKey] invalid aes mode ".concat(e))}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}])}();var Or=function(){return o(function e(t){var r=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}).removePKCS7Padding,i=void 0===r||r;if(a(this,e),this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=t.enableSoftwareAES,this.removePKCS7Padding=i,i)try{var n=self.crypto;n&&(this.subtle=n.subtle||n.webkitSubtle)}catch(e){}this.useSoftware=!this.subtle},[{key:"destroy",value:function(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}},{key:"isSync",value:function(){return this.useSoftware}},{key:"flush",value:function(){var e=this.currentResult,t=this.remainderData;if(!e||t)return this.reset(),null;var r,i,n,a=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?(i=(r=a).byteLength,(n=i&&new DataView(r.buffer).getUint8(i-1))?r.slice(0,i-n):r):a}},{key:"reset",value:function(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}},{key:"decrypt",value:function(e,t,r,i){var n=this;return this.useSoftware?new Promise(function(a,s){var o=ArrayBuffer.isView(e)?e:new Uint8Array(e);n.softwareDecrypt(o,t,r,i);var l=n.flush();l?a(l.buffer):s(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,r,i)}},{key:"softwareDecrypt",value:function(e,t,r,i){var n=this.currentIV,a=this.currentResult,s=this.remainderData;if(i!==Dr||16!==t.byteLength)return Ee.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),s&&(e=it(s,e),this.remainderData=null);var o=this.getValidChunk(e);if(!o.length)return null;n&&(r=n);var l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new _r),l.expandKey(t);var u=a;return this.currentResult=l.decrypt(o.buffer,0,r),this.currentIV=o.slice(-16).buffer,u||null}},{key:"webCryptoDecrypt",value:function(e,t,r,i){var n=this;if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,r,i));this.key=t,this.fastAesKey=new Mr(this.subtle,t,i)}return this.fastAesKey.expandKey().then(function(t){return n.subtle?(n.logOnce("WebCrypto AES decrypt"),new Cr(n.subtle,new Uint8Array(r),i).decrypt(e.buffer,t)):Promise.reject(new Error("web crypto not initialized"))}).catch(function(a){return Ee.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&&(Ee.log("[decrypter]: ".concat(e)),this.logEnabled=!1)}}])}(),Fr=Math.pow(2,17),Ur=function(){return o(function e(t){a(this,e),this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t},[{key:"destroy",value:function(){this.loader&&(this.loader.destroy(),this.loader=null)}},{key:"abort",value:function(){this.loader&&this.loader.abort()}},{key:"load",value:function(e,t){var r=this,i=e.url;if(!i)return Promise.reject(new Vr({type:J.NETWORK_ERROR,details:Z.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a ".concat(i?"part list":"url")),networkDetails:null}));this.abort();var n=this.config,a=n.fLoader,s=n.loader;return new Promise(function(o,l){if(r.loader&&r.loader.destroy(),e.gap){if(e.tagList.some(function(e){return"GAP"===e[0]}))return void l(Br(e));e.gap=!1}var u=r.loader=a?new a(n):new s(n),c=Nr(e);e.loader=u;var d=ur(n.fragLoadPolicy.default),h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:Fr};e.stats=u.stats;var f={onSuccess:function(t,i,n,a){r.resetLoader(e,u);var s=t.data;n.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(s.slice(0,16)),s=s.slice(16)),o({frag:e,part:null,payload:s,networkDetails:a})},onError:function(t,n,a,s){r.resetLoader(e,u),l(new Vr({type:J.NETWORK_ERROR,details:Z.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:fe({url:i,data:void 0},t),error:new Error("HTTP Error ".concat(t.code," ").concat(t.text)),networkDetails:a,stats:s}))},onAbort:function(t,i,n){r.resetLoader(e,u),l(new Vr({type:J.NETWORK_ERROR,details:Z.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:n,stats:t}))},onTimeout:function(t,i,n){r.resetLoader(e,u),l(new Vr({type:J.NETWORK_ERROR,details:Z.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error("Timeout after ".concat(h.timeout,"ms")),networkDetails:n,stats:t}))}};t&&(f.onProgress=function(r,i,n,a){return t({frag:e,part:null,payload:n,networkDetails:a})}),u.load(c,h,f)})}},{key:"loadPart",value:function(e,t,r){var i=this;this.abort();var n=this.config,a=n.fLoader,s=n.loader;return new Promise(function(o,l){if(i.loader&&i.loader.destroy(),e.gap||t.gap)l(Br(e,t));else{var u=i.loader=a?new a(n):new s(n),c=Nr(e,t);e.loader=u;var d=ur(n.fragLoadPolicy.default),h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Fr};t.stats=u.stats,u.load(c,h,{onSuccess:function(n,a,s,l){i.resetLoader(e,u),i.updateStatsFromPart(e,t);var c={frag:e,part:t,payload:n.data,networkDetails:l};r(c),o(c)},onError:function(r,n,a,s){i.resetLoader(e,u),l(new Vr({type:J.NETWORK_ERROR,details:Z.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:fe({url:c.url,data:void 0},r),error:new Error("HTTP Error ".concat(r.code," ").concat(r.text)),networkDetails:a,stats:s}))},onAbort:function(r,n,a){e.stats.aborted=t.stats.aborted,i.resetLoader(e,u),l(new Vr({type:J.NETWORK_ERROR,details:Z.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:a,stats:r}))},onTimeout:function(r,n,a){i.resetLoader(e,u),l(new Vr({type:J.NETWORK_ERROR,details:Z.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error("Timeout after ".concat(h.timeout,"ms")),networkDetails:a,stats:r}))}})}})}},{key:"updateStatsFromPart",value:function(e,t){var r=e.stats,i=t.stats,n=i.total;if(r.loaded+=i.loaded,n){var a=Math.round(e.duration/t.duration),s=Math.min(Math.round(r.loaded/n),a),o=(a-s)*Math.round(r.loaded/s);r.total=r.loaded+o}else r.total=Math.max(r.loaded,r.total);var l=r.loading,u=i.loading;l.start?l.first+=u.first-u.start:(l.start=u.start,l.first=u.first),l.end=u.end}},{key:"resetLoader",value:function(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}])}();function Nr(e){var t,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,i=r||e,n={frag:e,part:r,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},a=i.byteRangeStartOffset,s=i.byteRangeEndOffset;if(X(a)&&X(s)){var o,l=a,u=s;if("initSegment"===e.sn&&("AES-128"===(t=null==(o=e.decryptdata)?void 0:o.method)||"AES-256"===t)){var c=s-a;c%16&&(u=s+(16-c%16)),0!==a&&(n.resetIV=!0,l=a-16)}n.rangeStart=l,n.rangeEnd=u}return n}function Br(e,t){var r=new Error("GAP ".concat(e.gap?"tag":"attribute"," found")),i={type:J.MEDIA_ERROR,details:Z.FRAG_GAP,fatal:!1,frag:e,error:r,networkDetails:null};return t&&(i.part=t),(t||e).stats.aborted=!0,new Vr(i)}var Vr=function(e){function t(e){var r;return a(this,t),(r=n(this,t,[e.error.message])).data=void 0,r.data=e,r}return d(t,e),o(t)}(L(Error)),Gr=function(e){function t(e,r){var i;return a(this,t),(i=n(this,t,[e,r]))._boundTick=void 0,i._tickTimer=null,i._tickInterval=null,i._tickCallCount=0,i._boundTick=i.tick.bind(i),i}return d(t,e),o(t,[{key:"destroy",value:function(){this.onHandlerDestroying(),this.onHandlerDestroyed()}},{key:"onHandlerDestroying",value:function(){this.clearNextTick(),this.clearInterval()}},{key:"onHandlerDestroyed",value:function(){}},{key:"hasInterval",value:function(){return!!this._tickInterval}},{key:"hasNextTick",value:function(){return!!this._tickTimer}},{key:"setInterval",value:function(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}},{key:"clearInterval",value:function(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}},{key:"clearNextTick",value:function(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}},{key:"tick",value:function(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}},{key:"tickImmediate",value:function(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}},{key:"doTick",value:function(){}}])}(ve),Hr=o(function e(t,r,i){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,s=arguments.length>4&&void 0!==arguments[4]?arguments[4]:-1,o=arguments.length>5&&void 0!==arguments[5]&&arguments[5];a(this,e),this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=t,this.sn=r,this.id=i,this.size=n,this.part=s,this.partial=o});var Kr={length:0,start:function(){return 0},end:function(){return 0}},jr=function(){function e(){a(this,e)}return o(e,null,[{key:"isBuffered",value:function(t,r){if(t)for(var i=e.getBuffered(t),n=i.length;n--;)if(r>=i.start(n)&&r<=i.end(n))return!0;return!1}},{key:"bufferedRanges",value:function(t){if(t){var r=e.getBuffered(t);return e.timeRangesToArray(r)}return[]}},{key:"timeRangesToArray",value:function(e){for(var t=[],r=0;r<e.length;r++)t.push({start:e.start(r),end:e.end(r)});return t}},{key:"bufferInfo",value:function(t,r,i){if(t){var n=e.bufferedRanges(t);if(n.length)return e.bufferedInfo(n,r,i)}return{len:0,start:r,end:r,bufferedIndex:-1}}},{key:"bufferedInfo",value:function(e,t,r){t=Math.max(0,t),e.length>1&&e.sort(function(e,t){return e.start-t.start||t.end-e.end});var i=-1,n=[];if(r)for(var a=0;a<e.length;a++){t>=e[a].start&&t<=e[a].end&&(i=a);var s=n.length;if(s){var o=n[s-1].end;e[a].start-o<r?e[a].end>o&&(n[s-1].end=e[a].end):n.push(e[a])}else n.push(e[a])}else n=e;for(var l,u=0,c=t,d=t,h=0;h<n.length;h++){var f=n[h].start,v=n[h].end;if(-1===i&&t>=f&&t<=v&&(i=h),t+r>=f&&t<v)c=f,u=(d=v)-t;else if(t+r<f){l=f;break}}return{len:u,start:c||0,end:d||0,nextStart:l,buffered:e,bufferedIndex:i}}},{key:"getBuffered",value:function(e){try{return e.buffered||Kr}catch(e){return Ee.log("failed to get media.buffered",e),Kr}}}])}(),qr=/\{\$([a-zA-Z0-9-_]+)\}/g;function Wr(e){return qr.test(e)}function Yr(e,t){if(null!==e.variableList||e.hasVariableRefs){var r=e.variableList;return t.replace(qr,function(t){var i=t.substring(2,t.length-1),n=null==r?void 0:r[i];return void 0===n?(e.playlistParsingError||(e.playlistParsingError=new Error('Missing preceding EXT-X-DEFINE tag for Variable Reference: "'.concat(i,'"'))),t):n})}return t}function zr(e,t,r){var i,n,a=e.variableList;if(a||(e.variableList=a={}),"QUERYPARAM"in t){i=t.QUERYPARAM;try{var s=new self.URL(r).searchParams;if(!s.has(i))throw new Error('"'.concat(i,'" does not match any query parameter in URI: "').concat(r,'"'));n=s.get(i)}catch(t){e.playlistParsingError||(e.playlistParsingError=new Error("EXT-X-DEFINE QUERYPARAM: ".concat(t.message)))}}else i=t.NAME,n=t.VALUE;i in a?e.playlistParsingError||(e.playlistParsingError=new Error('EXT-X-DEFINE duplicate Variable Name declarations: "'.concat(i,'"'))):a[i]=n||""}function Xr(e,t,r){var i=t.IMPORT;if(r&&i in r){var n=e.variableList;n||(e.variableList=n={}),n[i]=r[i]}else e.playlistParsingError||(e.playlistParsingError=new Error('EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "'.concat(i,'"')))}var Qr=/^(\d+)x(\d+)$/,$r=/(.+?)=(".*?"|.*?)(?:,|$)/g,Jr=function(){return o(function e(t,r){a(this,e),"string"==typeof t&&(t=e.parseAttrList(t,r)),de(this,t)},[{key:"clientAttrs",get:function(){return Object.keys(this).filter(function(e){return"X-"===e.substring(0,2)})}},{key:"decimalInteger",value:function(e){var t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}},{key:"hexadecimalInteger",value:function(e){if(this[e]){var t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;for(var r=new Uint8Array(t.length/2),i=0;i<t.length/2;i++)r[i]=parseInt(t.slice(2*i,2*i+2),16);return r}return null}},{key:"hexadecimalIntegerAsNumber",value:function(e){var t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}},{key:"decimalFloatingPoint",value:function(e){return parseFloat(this[e])}},{key:"optionalFloat",value:function(e,t){var r=this[e];return r?parseFloat(r):t}},{key:"enumeratedString",value:function(e){return this[e]}},{key:"enumeratedStringList",value:function(e,t){var r=this[e];return(r?r.split(/[ ,]+/):[]).reduce(function(e,t){return e[t.toLowerCase()]=!0,e},t)}},{key:"bool",value:function(e){return"YES"===this[e]}},{key:"decimalResolution",value:function(e){var t=Qr.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}}],[{key:"parseAttrList",value:function(e,t){var r,i={};for($r.lastIndex=0;null!==(r=$r.exec(e));){var n=r[1].trim(),a=r[2],s=0===a.indexOf('"')&&a.lastIndexOf('"')===a.length-1,o=!1;if(s)a=a.slice(1,-1);else switch(n){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(t&&(s||o))a=Yr(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":Ee.warn("".concat(e,": attribute ").concat(n," is missing quotes"))}i[n]=a}return i}}])}();function Zr(e){return"ID"!==e&&"CLASS"!==e&&"CUE"!==e&&"START-DATE"!==e&&"DURATION"!==e&&"END-DATE"!==e&&"END-ON-NEXT"!==e}function ei(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e||"SCTE35-CMD"===e}var ti=function(){return o(function e(t,r){var i,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;if(a(this,e),this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==r?void 0:r.tagAnchor)||null,this.tagOrder=null!=(i=null==r?void 0:r.tagOrder)?i:n,r){var s=r.attr;for(var o in s)if(Object.prototype.hasOwnProperty.call(t,o)&&t[o]!==s[o]){Ee.warn('DATERANGE tag attribute: "'.concat(o,'" does not match for tags with ID: "').concat(t.ID,'"')),this._badValueForSameId=o;break}t=de(new Jr({}),s,t)}if(this.attr=t,r?(this._startDate=r._startDate,this._cue=r._cue,this._endDate=r._endDate,this._dateAtEnd=r._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){var l=(null==r?void 0:r.endDate)||new Date(this.attr["END-DATE"]);X(l.getTime())&&(this._endDate=l)}},[{key:"id",get:function(){return this.attr.ID}},{key:"class",get:function(){return this.attr.CLASS}},{key:"cue",get:function(){var e=this._cue;return void 0===e?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}},{key:"startTime",get:function(){var e=this.tagAnchor;return null===e||null===e.programDateTime?(Ee.warn('Expected tagAnchor Fragment with PDT set for DateRange "'.concat(this.id,'": ').concat(e)),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}},{key:"startDate",get:function(){return this._startDate}},{key:"endDate",get:function(){var e=this._endDate||this._dateAtEnd;if(e)return e;var t=this.duration;return null!==t?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*t):null}},{key:"duration",get:function(){if("DURATION"in this.attr){var e=this.attr.decimalFloatingPoint("DURATION");if(X(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}},{key:"plannedDuration",get:function(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}},{key:"endOnNext",get:function(){return this.attr.bool("END-ON-NEXT")}},{key:"isInterstitial",get:function(){return"com.apple.hls.interstitial"===this.class}},{key:"isValid",get:function(){return!!this.id&&!this._badValueForSameId&&X(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}])}(),ri=function(){return o(function e(t){a(this,e),this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=t},[{key:"reloaded",value:function(e){if(!e)return this.advanced=!0,void(this.updated=!0);var t=this.lastPartSn-e.lastPartSn,r=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!r||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&r>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1}},{key:"hasKey",value:function(e){return this.encryptedFragments.some(function(t){var r=t.decryptdata;return r||(t.setKeyFormat(e.keyFormat),r=t.decryptdata),!!r&&e.matches(r)})}},{key:"hasProgramDateTime",get:function(){return!!this.fragments.length&&X(this.fragments[this.fragments.length-1].programDateTime)}},{key:"levelTargetDuration",get:function(){return this.averagetargetduration||this.targetduration||10}},{key:"drift",get:function(){var e=this.driftEndTime-this.driftStartTime;return e>0?1e3*(this.driftEnd-this.driftStart)/e:1}},{key:"edge",get:function(){return this.partEnd||this.fragmentEnd}},{key:"partEnd",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}},{key:"fragmentEnd",get:function(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}},{key:"fragmentStart",get:function(){return this.fragments.length?this.fragments[0].start:0}},{key:"age",get:function(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}},{key:"lastPartIndex",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}},{key:"maxPartIndex",get:function(){var e=this.partList;if(e){var t=this.lastPartIndex;if(-1!==t){for(var r=e.length;r--;)if(e[r].index>t)return e[r].index;return t}}return 0}},{key:"lastPartSn",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}},{key:"expired",get:function(){if(this.live&&this.age&&this.misses<3){var e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}])}();function ii(e,t){return e.length===t.length&&!e.some(function(e,r){return e!==t[r]})}function ni(e,t){return!e&&!t||!(!e||!t)&&ii(e,t)}function ai(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function si(e){switch(e){case"AES-128":case"AES-256":return Dr;case"AES-256-CTR":return xr;default:throw new Error("invalid full segment method ".concat(e))}}function oi(e){return Uint8Array.from(atob(e),function(e){return e.charCodeAt(0)})}function li(e){return Uint8Array.from(unescape(encodeURIComponent(e)),function(e){return e.charCodeAt(0)})}function ui(e){var t=function(e,t,r){var i=e[t];e[t]=e[r],e[r]=i};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function ci(e){var t,r,i=e.split(":"),n=null;if("data"===i[0]&&2===i.length){var a=i[1].split(";"),s=a[a.length-1].split(",");if(2===s.length){var o="base64"===s[0],l=s[1];o?(a.splice(-1,1),n=oi(l)):(t=li(l).subarray(0,16),(r=new Uint8Array(16)).set(t,16-t.length),n=r)}}return n}var di="undefined"!=typeof self?self:void 0,hi={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},fi="org.w3.clearkey",vi="com.apple.streamingkeydelivery",gi="com.microsoft.playready",pi="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function mi(e){switch(e){case vi:return hi.FAIRPLAY;case gi:return hi.PLAYREADY;case pi:return hi.WIDEVINE;case fi:return hi.CLEARKEY}}function yi(e){switch(e){case hi.FAIRPLAY:return vi;case hi.PLAYREADY:return gi;case hi.WIDEVINE:return pi;case hi.CLEARKEY:return fi}}function Ti(e){var t=e.drmSystems,r=e.widevineLicenseUrl,i=t?[hi.FAIRPLAY,hi.WIDEVINE,hi.PLAYREADY,hi.CLEARKEY].filter(function(e){return!!t[e]}):[];return!i[hi.WIDEVINE]&&r&&i.push(hi.WIDEVINE),i}var Ei,ki=null!=di&&null!=(Ei=di.navigator)&&Ei.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function Si(e){var t=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),r=String.fromCharCode.apply(null,Array.from(t)),i=r.substring(r.indexOf("<"),r.length),n=(new DOMParser).parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(n){var a=n.childNodes[0]?n.childNodes[0].nodeValue:n.getAttribute("VALUE");if(a){var s=oi(a).subarray(0,16);return ui(s),s}}return null}var bi={},Ai=function(){function e(t,r,i){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[1],s=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null,o=arguments.length>5?arguments[5]:void 0;a(this,e),this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=t,this.uri=r,this.keyFormat=i,this.keyFormatVersions=n,this.iv=s,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&!ai(t),null!=o&&o.startsWith("0x")&&(this.keyId=new Uint8Array(Le(o)))}return o(e,[{key:"matches",value:function(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&ii(e.keyFormatVersions,this.keyFormatVersions)&&ni(e.iv,this.iv)&&ni(e.keyId,this.keyId)}},{key:"isSupported",value:function(){if(this.method){if(ai(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case vi:case pi:case gi:case fi:return-1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}},{key:"getDecryptData",value:function(t,r){if(!this.encrypted||!this.uri)return null;if(ai(this.method)){var i=this.iv;return i||("number"!=typeof t&&(Ee.warn('missing IV for initialization segment with method="'.concat(this.method,'" - compliance issue')),t=0),i=function(e){for(var t=new Uint8Array(16),r=12;r<16;r++)t[r]=e>>8*(15-r)&255;return t}(t)),new e(this.method,this.uri,"identity",this.keyFormatVersions,i)}if(this.keyId){var n=bi[this.uri];if(n&&!ii(this.keyId,n)&&e.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}var a,s=ci(this.uri);if(s)switch(this.keyFormat){case pi:if(this.pssh=s,!this.keyId){var o=function(e){var t=[];if(e instanceof ArrayBuffer)for(var r=e.byteLength,i=0;i+32<r;){var n=ct(new DataView(e,i));t.push(n),i+=n.size}return t}(s.buffer);if(o.length){var l,u=o[0];this.keyId=null!=(l=u.kids)&&l.length?u.kids[0]:null}}this.keyId||(this.keyId=Li(r));break;case gi:var c=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=ut(c,0,s),this.keyId=Si(s);break;default:var d=s.subarray(0,16);if(16!==d.length){var h=new Uint8Array(16);h.set(d,16-d.length),d=h}this.keyId=d}this.keyId&&16===this.keyId.byteLength||(a=function(e){var t=null==e?void 0:e[pi];if(t)return t.keyId;return null}(r),a||(a=Li(r))||(a=bi[this.uri]),a&&(this.keyId=a,e.setKeyIdForUri(this.uri,a)));return this}}],[{key:"clearKeyUriToKeyIdMap",value:function(){bi={}}},{key:"setKeyIdForUri",value:function(e,t){bi[e]=t}}])}();function Li(e){var t=null==e?void 0:e[gi];if(t){var r=ci(t.uri);if(r)return Si(r)}return null}var Ri=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,Ii=/#EXT-X-MEDIA:(.*)/g,wi=/^#EXT(?:INF|-X-TARGETDURATION):/m,Pi=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Di=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|")),xi=function(){function e(){a(this,e)}return o(e,null,[{key:"findGroup",value:function(e,t){for(var r=0;r<e.length;r++){var i=e[r];if(i.id===t)return i}}},{key:"resolve",value:function(e,t){return Pe.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}},{key:"isMediaPlaylist",value:function(e){return wi.test(e)}},{key:"parseMasterPlaylist",value:function(t,r){var i,n={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:Wr(t)},a=[];if(Ri.lastIndex=0,!t.startsWith("#EXTM3U"))return n.playlistParsingError=new Error("no EXTM3U delimiter"),n;for(;null!=(i=Ri.exec(t));)if(i[1]){var s,o=new Jr(i[1],n),l=Yr(n,i[2]),u={attrs:o,bitrate:o.decimalInteger("BANDWIDTH")||o.decimalInteger("AVERAGE-BANDWIDTH"),name:o.NAME,url:e.resolve(l,r)},c=o.decimalResolution("RESOLUTION");c&&(u.width=c.width,u.height=c.height),Fi(o.CODECS,u);var d=o["SUPPLEMENTAL-CODECS"];d&&(u.supplemental={},Fi(d,u.supplemental)),null!=(s=u.unknownCodecs)&&s.length||a.push(u),n.levels.push(u)}else if(i[3]){var h=i[3],f=i[4];switch(h){case"SESSION-DATA":var v=new Jr(f,n),g=v["DATA-ID"];g&&(null===n.sessionData&&(n.sessionData={}),n.sessionData[g]=v);break;case"SESSION-KEY":var p=Mi(f,r,n);p.encrypted&&p.isSupported()?(null===n.sessionKeys&&(n.sessionKeys=[]),n.sessionKeys.push(p)):Ee.warn('[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "'.concat(f,'"'));break;case"DEFINE":zr(n,new Jr(f,n),r);break;case"CONTENT-STEERING":var m=new Jr(f,n);n.contentSteering={uri:e.resolve(m["SERVER-URI"],r),pathwayId:m["PATHWAY-ID"]||"."};break;case"START":n.startTimeOffset=Oi(f)}}var y=a.length>0&&a.length<n.levels.length;return n.levels=y?a:n.levels,0===n.levels.length&&(n.playlistParsingError=new Error("no levels found in manifest")),n}},{key:"parseMasterPlaylistMedia",value:function(t,r,i){var n,a={},s=i.levels,o={AUDIO:s.map(function(e){return{id:e.attrs.AUDIO,audioCodec:e.audioCodec}}),SUBTITLES:s.map(function(e){return{id:e.attrs.SUBTITLES,textCodec:e.textCodec}}),"CLOSED-CAPTIONS":[]},l=0;for(Ii.lastIndex=0;null!==(n=Ii.exec(t));){var u=new Jr(n[1],i),c=u.TYPE;if(c){var d=o[c],h=a[c]||[];a[c]=h;var f=u.LANGUAGE,v=u["ASSOC-LANGUAGE"],g=u.CHANNELS,p=u.CHARACTERISTICS,m=u["INSTREAM-ID"],y={attrs:u,bitrate:0,id:l++,groupId:u["GROUP-ID"]||"",name:u.NAME||f||"",type:c,default:u.bool("DEFAULT"),autoselect:u.bool("AUTOSELECT"),forced:u.bool("FORCED"),lang:f,url:u.URI?e.resolve(u.URI,r):""};if(v&&(y.assocLang=v),g&&(y.channels=g),p&&(y.characteristics=p),m&&(y.instreamId=m),null!=d&&d.length){var T=e.findGroup(d,y.groupId)||d[0];Ui(y,T,"audioCodec"),Ui(y,T,"textCodec")}h.push(y)}}return a}},{key:"parseLevelPlaylist",value:function(e,t,r,i,n,a){var s,o,l,u,c,d={url:t},h=new ri(t),f=h.fragments,v=[],g=null,p=0,m=0,y=0,T=0,E=0,k=null,S=new Fe(i,d),b=-1,A=!1,L=null;if(Pi.lastIndex=0,h.m3u8=e,h.hasVariableRefs=Wr(e),"#EXTM3U"!==(null==(s=Pi.exec(e))?void 0:s[0]))return h.playlistParsingError=new Error("Missing format identifier #EXTM3U"),h;for(;null!==(o=Pi.exec(e));){A&&(A=!1,(S=new Fe(i,d)).playlistOffset=y,S.setStart(y),S.sn=p,S.cc=T,E&&(S.bitrate=E),S.level=r,g&&(S.initSegment=g,g.rawProgramDateTime&&(S.rawProgramDateTime=g.rawProgramDateTime,g.rawProgramDateTime=null),L&&(S.setByteRange(L),L=null)));var R=o[1];if(R){S.duration=parseFloat(R);var I=(" "+o[2]).slice(1);S.title=I||null,S.tagList.push(I?["INF",R,I]:["INF",R])}else if(o[3]){if(X(S.duration)){S.playlistOffset=y,S.setStart(y),u&&Vi(S,u,h),S.sn=p,S.level=r,S.cc=T,f.push(S);var w=(" "+o[3]).slice(1);S.relurl=Yr(h,w),Ni(S,k,v),k=S,y+=S.duration,p++,m=0,A=!0}}else{if(!(o=o[0].match(Di))){Ee.warn("No matches on slow regex match for level playlist!");continue}for(l=1;l<o.length&&void 0===o[l];l++);var P=(" "+o[l]).slice(1),D=(" "+o[l+1]).slice(1),x=o[l+2]?(" "+o[l+2]).slice(1):null;switch(P){case"BYTERANGE":k?S.setByteRange(D,k):S.setByteRange(D);break;case"PROGRAM-DATE-TIME":S.rawProgramDateTime=D,S.tagList.push(["PROGRAM-DATE-TIME",D]),-1===b&&(b=f.length);break;case"PLAYLIST-TYPE":h.type&&Gi(h,P,o),h.type=D.toUpperCase();break;case"MEDIA-SEQUENCE":0!==h.startSN?Gi(h,P,o):f.length>0&&Hi(h,P,o),p=h.startSN=parseInt(D);break;case"SKIP":h.skippedSegments&&Gi(h,P,o);var C=new Jr(D,h),_=C.decimalInteger("SKIPPED-SEGMENTS");if(X(_)){h.skippedSegments+=_;for(var M=_;M--;)f.push(null);p+=_}var O=C.enumeratedString("RECENTLY-REMOVED-DATERANGES");O&&(h.recentlyRemovedDateranges=(h.recentlyRemovedDateranges||[]).concat(O.split("\t")));break;case"TARGETDURATION":0!==h.targetduration&&Gi(h,P,o),h.targetduration=Math.max(parseInt(D),1);break;case"VERSION":null!==h.version&&Gi(h,P,o),h.version=parseInt(D);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":h.live||Gi(h,P,o),h.live=!1;break;case"#":(D||x)&&S.tagList.push(x?[D,x]:[D]);break;case"DISCONTINUITY":T++,S.tagList.push(["DIS"]);break;case"GAP":S.gap=!0,S.tagList.push([P]);break;case"BITRATE":S.tagList.push([P,D]),E=1e3*parseInt(D),X(E)?S.bitrate=E:E=0;break;case"DATERANGE":var F=new Jr(D,h),U=new ti(F,h.dateRanges[F.ID],h.dateRangeTagCount);h.dateRangeTagCount++,U.isValid||h.skippedSegments?h.dateRanges[U.id]=U:Ee.warn('Ignoring invalid DATERANGE tag: "'.concat(D,'"')),S.tagList.push(["EXT-X-DATERANGE",D]);break;case"DEFINE":var N=new Jr(D,h);"IMPORT"in N?Xr(h,N,a):zr(h,N,t);break;case"DISCONTINUITY-SEQUENCE":0!==h.startCC?Gi(h,P,o):f.length>0&&Hi(h,P,o),h.startCC=T=parseInt(D);break;case"KEY":var B=Mi(D,t,h);if(B.isSupported()){if("NONE"===B.method){u=void 0;break}u||(u={});var V=u[B.keyFormat];null!=V&&V.matches(B)||(V&&(u=de({},u)),u[B.keyFormat]=B)}else Ee.warn('[Keys] Ignoring unsupported EXT-X-KEY tag: "'.concat(D,'"'));break;case"START":h.startTimeOffset=Oi(D);break;case"MAP":var G=new Jr(D,h);if(S.duration){var H=new Fe(i,d);Bi(H,G,r,u),g=H,S.initSegment=g,g.rawProgramDateTime&&!S.rawProgramDateTime&&(S.rawProgramDateTime=g.rawProgramDateTime)}else{var K=S.byteRangeEndOffset;if(K){var j=S.byteRangeStartOffset;L="".concat(K-j,"@").concat(j)}else L=null;Bi(S,G,r,u),g=S,A=!0}g.cc=T;break;case"SERVER-CONTROL":c&&Gi(h,P,o),c=new Jr(D),h.canBlockReload=c.bool("CAN-BLOCK-RELOAD"),h.canSkipUntil=c.optionalFloat("CAN-SKIP-UNTIL",0),h.canSkipDateRanges=h.canSkipUntil>0&&c.bool("CAN-SKIP-DATERANGES"),h.partHoldBack=c.optionalFloat("PART-HOLD-BACK",0),h.holdBack=c.optionalFloat("HOLD-BACK",0);break;case"PART-INF":h.partTarget&&Gi(h,P,o);var q=new Jr(D);h.partTarget=q.decimalFloatingPoint("PART-TARGET");break;case"PART":var W=h.partList;W||(W=h.partList=[]);var Y=m>0?W[W.length-1]:void 0,z=m++,Q=new Jr(D,h),$=new Ue(Q,S,d,z,Y);W.push($),S.duration+=$.duration;break;case"PRELOAD-HINT":var J=new Jr(D,h);h.preloadHint=J;break;case"RENDITION-REPORT":var Z=new Jr(D,h);h.renditionReports=h.renditionReports||[],h.renditionReports.push(Z);break;default:Ee.warn("line parsed but not handled: ".concat(o))}}}k&&!k.relurl?(f.pop(),y-=k.duration,h.partList&&(h.fragmentHint=k)):h.partList&&(Ni(S,k,v),S.cc=T,h.fragmentHint=S,u&&Vi(S,u,h)),h.targetduration||(h.playlistParsingError=new Error("Missing Target Duration"));var ee=f.length,te=f[0],re=f[ee-1];if((y+=h.skippedSegments*h.targetduration)>0&&ee&&re){h.averagetargetduration=y/ee;var ie=re.sn;h.endSN="initSegment"!==ie?ie:0,h.live||(re.endList=!0),b>0&&(!function(e,t){for(var r=e[t],i=t;i--;){var n=e[i];if(!n)return;n.programDateTime=r.programDateTime-1e3*n.duration,r=n}}(f,b),te&&v.unshift(te))}return h.fragmentHint&&(y+=h.fragmentHint.duration),h.totalduration=y,v.length&&h.dateRangeTagCount&&te&&Ci(v,h),h.endCC=T,h}}])}();function Ci(e,t){var r=e.length;if(!r){if(!t.hasProgramDateTime)return;var i=t.fragments[t.fragments.length-1];e.push(i),r++}for(var n=e[r-1],a=t.live?1/0:t.totalduration,s=Object.keys(t.dateRanges),o=s.length;o--;){var l=t.dateRanges[s[o]],u=l.startDate.getTime();l.tagAnchor=n.ref;for(var c=r;c--;){var d;if((null==(d=e[c])?void 0:d.sn)<t.startSN)break;var h=_i(t,u,e,c,a);if(-1!==h){l.tagAnchor=t.fragments[h].ref;break}}}}function _i(e,t,r,i,n){var a=r[i];if(a){var s,o=a.programDateTime;if(t>=o||0===i)if(t<=o+1e3*(((null==(s=r[i+1])?void 0:s.start)||n)-a.start)){var l=r[i].sn-e.startSN;if(l<0)return-1;var u=e.fragments;if(u.length>r.length)for(var c=(r[i+1]||u[u.length-1]).sn-e.startSN;c>l;c--){var d=u[c].programDateTime;if(t>=d&&t<d+1e3*u[c].duration)return c}return l}}return-1}function Mi(e,t,r){var i,n,a=new Jr(e,r),s=null!=(i=a.METHOD)?i:"",o=a.URI,l=a.hexadecimalInteger("IV"),u=a.KEYFORMATVERSIONS,c=null!=(n=a.KEYFORMAT)?n:"identity";o&&a.IV&&!l&&Ee.error("Invalid IV: ".concat(a.IV));var d=o?xi.resolve(o,t):"",h=(u||"1").split("/").map(Number).filter(Number.isFinite);return new Ai(s,d,c,h,l,a.KEYID)}function Oi(e){var t=new Jr(e).decimalFloatingPoint("TIME-OFFSET");return X(t)?t:null}function Fi(e,t){var r=(e||"").split(/[ ,]+/).filter(function(e){return e});["video","audio","text"].forEach(function(e){var i=r.filter(function(t){return ft(t,e)});i.length&&(t["".concat(e,"Codec")]=i.map(function(e){return e.split("/")[0]}).join(","),r=r.filter(function(e){return-1===i.indexOf(e)}))}),t.unknownCodecs=r}function Ui(e,t,r){var i=t[r];i&&(e[r]=i)}function Ni(e,t,r){e.rawProgramDateTime?r.push(e):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function Bi(e,t,r,i){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=r,e.sn="initSegment",i&&(e.levelkeys=i),e.initSegment=null}function Vi(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 Gi(e,t,r){e.playlistParsingError=new Error("#EXT-X-".concat(t," must not appear more than once (").concat(r[0],")"))}function Hi(e,t,r){e.playlistParsingError=new Error("#EXT-X-".concat(t," must appear before the first Media Segment (").concat(r[0],")"))}function Ki(e,t){var r=t.startPTS;if(X(r)){var i,n=0;t.sn>e.sn?(n=r-e.start,i=e):(n=e.start-r,i=t),i.duration!==n&&i.setDuration(n)}else if(t.sn>e.sn){e.cc===t.cc&&e.minEndPTS?t.setStart(e.start+(e.minEndPTS-e.start)):t.setStart(e.start+e.duration)}else t.setStart(Math.max(e.start-t.duration,0))}function ji(e,t,r,i,n,a,s){i-r<=0&&(s.warn("Fragment should have a positive duration",t),i=r+t.duration,a=n+t.duration);var o=r,l=i,u=t.startPTS,c=t.endPTS;if(X(u)){var d=Math.abs(u-r);e&&d>e.totalduration?s.warn("media timestamps and playlist times differ by ".concat(d,"s for level ").concat(t.level," ").concat(e.url)):X(t.deltaPTS)?t.deltaPTS=Math.max(d,t.deltaPTS):t.deltaPTS=d,o=Math.max(r,u),r=Math.min(r,u),n=void 0!==t.startDTS?Math.min(n,t.startDTS):n,l=Math.min(i,c),i=Math.max(i,c),a=void 0!==t.endDTS?Math.max(a,t.endDTS):a}var h=r-t.start;0!==t.start&&t.setStart(r),t.setDuration(i-t.start),t.startPTS=r,t.maxStartPTS=o,t.startDTS=n,t.endPTS=i,t.minEndPTS=l,t.endDTS=a;var f,v=t.sn;if(!e||v<e.startSN||v>e.endSN)return 0;var g=v-e.startSN,p=e.fragments;for(p[g]=t,f=g;f>0;f--)Ki(p[f],p[f-1]);for(f=g;f<p.length-1;f++)Ki(p[f],p[f+1]);return e.fragmentHint&&Ki(p[p.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,h}function qi(e,t,r){if(e!==t){for(var i,n=null,a=e.fragments,s=a.length-1;s>=0;s--){var o=a[s].initSegment;if(o){n=o;break}}e.fragmentHint&&delete e.fragmentHint.endPTS,function(e,t,r){for(var i=t.skippedSegments,n=Math.max(e.startSN,t.startSN)-t.startSN,a=(e.fragmentHint?1:0)+(i?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,s=t.startSN-e.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,u=n;u<=a;u++){var c=l[s+u],d=o[u];if(i&&!d&&c&&(d=t.fragments[u]=c),c&&d){r(c,d,u,o);var h=c.relurl,f=d.relurl;if(h&&en(h,f))return void(t.playlistParsingError=Wi("media sequence mismatch ".concat(d.sn,":"),e,t,c,d));if(c.cc!==d.cc)return void(t.playlistParsingError=Wi("discontinuity sequence mismatch (".concat(c.cc,"!=").concat(d.cc,")"),e,t,c,d))}}}(e,t,function(e,r,a,s){if((!t.startCC||t.skippedSegments)&&r.cc!==e.cc){for(var o=e.cc-r.cc,l=a;l<s.length;l++)s[l].cc+=o;t.endCC=s[s.length-1].cc}X(e.startPTS)&&X(e.endPTS)&&(r.setStart(r.startPTS=e.startPTS),r.startDTS=e.startDTS,r.maxStartPTS=e.maxStartPTS,r.endPTS=e.endPTS,r.endDTS=e.endDTS,r.minEndPTS=e.minEndPTS,r.setDuration(e.endPTS-e.startPTS),r.duration&&(i=r),t.PTSKnown=t.alignedSliding=!0),e.hasStreams&&(r.elementaryStreams=e.elementaryStreams),r.loader=e.loader,e.hasStats&&(r.stats=e.stats),e.initSegment&&(r.initSegment=e.initSegment,n=e.initSegment)});var l=t.fragments,u=t.fragmentHint?l.concat(t.fragmentHint):l;if(n&&u.forEach(function(e){var t;!e||e.initSegment&&e.initSegment.relurl!==(null==(t=n)?void 0:t.relurl)||(e.initSegment=n)}),t.skippedSegments){if(t.deltaUpdateFailed=l.some(function(e){return!e}),t.deltaUpdateFailed){r.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(var c=t.skippedSegments;c--;)l.shift();t.startSN=l[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=function(e,t,r){var i=t.dateRanges,n=t.recentlyRemovedDateranges,a=de({},e);n&&n.forEach(function(e){delete a[e]});var s=Object.keys(a).length;if(!s)return i;return Object.keys(i).forEach(function(e){var t=a[e],n=new ti(i[e].attr,t);n.isValid?(a[e]=n,t||(n.tagOrder+=s)):r.warn('Ignoring invalid Playlist Delta Update DATERANGE tag: "'.concat(Kt(i[e].attr),'"'))}),a}(e.dateRanges,t,r));var d=e.fragments.filter(function(e){return e.rawProgramDateTime});if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(var h=1;h<u.length;h++)null===u[h].programDateTime&&Ni(u[h],u[h-1],d);Ci(d,t)}t.endCC=l[l.length-1].cc}if(!t.startCC){var f,v=Qi(e,t.startSN-1);t.startCC=null!=(f=null==v?void 0:v.cc)?f:l[0].cc}!function(e,t,r){if(e&&t)for(var i=0,n=0,a=e.length;n<=a;n++){var s=e[n],o=t[n+i];s&&o&&s.index===o.index&&s.fragment.sn===o.fragment.sn?r(s,o):i--}}(e.partList,t.partList,function(e,t){t.elementaryStreams=e.elementaryStreams,t.stats=e.stats}),i?ji(t,i,i.startPTS,i.endPTS,i.startDTS,i.endDTS,r):Yi(e,t),l.length&&(t.totalduration=t.edge-l[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;var g=t.advancedDateTime;if(t.advanced&&g){var p=t.edge;t.driftStart||(t.driftStartTime=g,t.driftStart=p),t.driftEndTime=g,t.driftEnd=p}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;-1===t.requestScheduled&&(t.requestScheduled=e.requestScheduled)}}function Wi(e,t,r,i,n){return new Error("".concat(e," ").concat(n.url,"\nPlaylist starting @").concat(t.startSN,"\n").concat(t.m3u8,"\n\nPlaylist starting @").concat(r.startSN,"\n").concat(r.m3u8))}function Yi(e,t){var r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],i=t.startSN+t.skippedSegments-e.startSN,n=e.fragments,a=i>=0,s=0;if(a&&i<n.length)s=n[i].start;else if(a&&t.startSN===e.endSN+1)s=e.fragmentEnd;else if(a&&r)s=e.fragmentStart+i*t.levelTargetDuration;else{if(t.skippedSegments||0!==t.fragmentStart)return;s=e.fragmentStart}zi(t,s)}function zi(e,t){if(t){for(var r=e.fragments,i=e.skippedSegments;i<r.length;i++)r[i].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}function Xi(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1/0,r=1e3*e.targetduration;if(e.updated){var i=e.fragments;if(i.length&&4*r>t){var n=1e3*i[i.length-1].duration;n<r&&(r=n)}}else r/=2;return Math.round(r)}function Qi(e,t,r){if(!e)return null;var i=e.fragments[t-e.startSN];return i||((i=e.fragmentHint)&&i.sn===t?i:t<e.startSN&&r&&r.sn===t?r:null)}function $i(e,t,r){return e?Ji(e.partList,t,r):null}function Ji(e,t,r){if(e)for(var i=e.length;i--;){var n=e[i];if(n.index===r&&n.fragment.sn===t)return n}return null}function Zi(e){e.forEach(function(e,t){var r;null==(r=e.details)||r.fragments.forEach(function(e){e.level=t,e.initSegment&&(e.initSegment.level=t)})})}function en(e,t){return!(e===t||!t)&&tn(e)!==tn(t)}function tn(e){return e.replace(/\?[^?]*$/,"")}function rn(e,t){for(var r=0,i=e.length;r<i;r++){var n;if((null==(n=e[r])?void 0:n.cc)===t)return e[r]}return null}function nn(e,t){var r=e.start+t;e.startPTS=r,e.setStart(r),e.endPTS=r+e.duration}function an(e,t){for(var r=t.fragments,i=0,n=r.length;i<n;i++)nn(r[i],e);t.fragmentHint&&nn(t.fragmentHint,e),t.alignedSliding=!0}function sn(e,t){if(function(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}(t,e)){var r=Math.min(t.endCC,e.endCC),i=rn(t.fragments,r),n=rn(e.fragments,r);if(i&&n)Ee.log("Aligning playlist at start of dicontinuity sequence ".concat(r)),an(i.start-n.start,e)}}function on(e,t){if(e.hasProgramDateTime&&t.hasProgramDateTime){var r=e.fragments,i=t.fragments;if(r.length&&i.length){var n,a,s=Math.min(t.endCC,e.endCC);t.startCC<s&&e.startCC<s&&(n=rn(i,s),a=rn(r,s)),n&&a||(a=rn(r,(n=i[Math.floor(i.length/2)]).cc)||r[Math.floor(r.length/2)]);var o=n.programDateTime,l=a.programDateTime;if(o&&l)an((l-o)/1e3-(a.start-n.start),e)}}}function ln(e,t,r){un(e,t,r),e.addEventListener(t,r)}function un(e,t,r){e.removeEventListener(t,r)}var cn=function(e){for(var t="",r=e.length,i=0;i<r;i++)t+="[".concat(e.start(i).toFixed(3),"-").concat(e.end(i).toFixed(3),"]");return t},dn="STOPPED",hn="IDLE",fn="KEY_LOADING",vn="FRAG_LOADING",gn="FRAG_LOADING_WAITING_RETRY",pn="WAITING_TRACK",mn="PARSING",yn="PARSED",Tn="ENDED",En="ERROR",kn="WAITING_INIT_PTS",Sn="WAITING_LEVEL",bn=function(e){function t(e,r,i,s,o){var l;return a(this,t),(l=n(this,t,[s,e.logger])).hls=void 0,l.fragPrevious=null,l.fragCurrent=null,l.fragmentTracker=void 0,l.transmuxer=null,l._state=dn,l.playlistType=void 0,l.media=null,l.mediaBuffer=null,l.config=void 0,l.bitrateTest=!1,l.lastCurrentTime=0,l.nextLoadPosition=0,l.startPosition=0,l.startTimeOffset=null,l.retryDate=0,l.levels=null,l.fragmentLoader=void 0,l.keyLoader=void 0,l.levelLastLoaded=null,l.startFragRequested=!1,l.decrypter=void 0,l.initPTS=[],l.buffering=!0,l.loadingParts=!1,l.loopSn=void 0,l.onMediaSeeking=function(){var e=l,t=e.config,r=e.fragCurrent,i=e.media,n=e.mediaBuffer,a=e.state,s=i?i.currentTime:0,o=jr.bufferInfo(n||i,s,t.maxBufferHole),u=!o.len;if(l.log("Media seeking to ".concat(X(s)?s.toFixed(3):s,", state: ").concat(a,", ").concat(u?"out of":"in"," buffer")),l.state===Tn)l.resetLoadingState();else if(r){var c=t.maxFragLookUpTolerance,d=r.start-c,h=r.start+r.duration+c;if(u||h<o.start||d>o.end){var f=s>h;(s<d||f)&&(f&&r.loader&&(l.log("Cancelling fragment load for seek (sn: ".concat(r.sn,")")),r.abortRequests(),l.resetLoadingState()),l.fragPrevious=null)}}if(i&&(l.fragmentTracker.removeFragmentsInRange(s,1/0,l.playlistType,!0),s>l.lastCurrentTime&&(l.lastCurrentTime=s),!l.loadingParts)){var v=Math.max(o.end,s),g=l.shouldLoadParts(l.getLevelDetails(),v);g&&(l.log("LL-Part loading ON after seeking to ".concat(s.toFixed(2)," with buffer @").concat(v.toFixed(2))),l.loadingParts=g)}l.hls.hasEnoughToStart||(l.log("Setting ".concat(u?"startPosition":"nextLoadPosition"," to ").concat(s," for seek without enough to start")),l.nextLoadPosition=s,u&&(l.startPosition=s)),u&&l.state===hn&&l.tickImmediate()},l.onMediaEnded=function(){l.log("setting startPosition to 0 because media ended"),l.startPosition=l.lastCurrentTime=0},l.playlistType=o,l.hls=e,l.fragmentLoader=new Ur(e.config),l.keyLoader=i,l.fragmentTracker=r,l.config=e.config,l.decrypter=new Or(e.config),l}return d(t,e),o(t,[{key:"registerListeners",value:function(){var e=this.hls;e.on(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(ee.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(ee.ERROR,this.onError,this)}},{key:"doTick",value:function(){this.onTickEnd()}},{key:"onTickEnd",value:function(){}},{key:"startLoad",value:function(e){}},{key:"stopLoad",value:function(){if(this.state!==dn){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);var e=this.fragCurrent;null!=e&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=dn}}},{key:"startPositionValue",get:function(){var e=this.nextLoadPosition,t=this.startPosition;return-1===t&&e?e:t}},{key:"bufferingEnabled",get:function(){return this.buffering}},{key:"pauseBuffering",value:function(){this.buffering=!1}},{key:"resumeBuffering",value:function(){this.buffering=!0}},{key:"inFlightFrag",get:function(){return{frag:this.fragCurrent,state:this.state}}},{key:"_streamEnded",value:function(e,t){if(t.live||!this.media)return!1;var r=e.end||0,i=this.config.timelineOffset||0;if(r<=i)return!1;var n=e.buffered;this.config.maxBufferHole&&n&&n.length>1&&(e=jr.bufferedInfo(n,e.start,0));var a=e.nextStart;if(a&&a>i&&a<t.edge)return!1;if(this.media.currentTime<e.start)return!1;var s=t.partList;if(null!=s&&s.length){var o=s[s.length-1];return jr.isBuffered(this.media,o.start+o.duration/2)}var l=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(l)}},{key:"getLevelDetails",value:function(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}},{key:"timelineOffset",get:function(){var e,t=this.config.timelineOffset;return t?(null==(e=this.getLevelDetails())?void 0:e.appliedTimelineOffset)||t:0}},{key:"onMediaAttached",value:function(e,t){var r=this.media=this.mediaBuffer=t.media;ln(r,"seeking",this.onMediaSeeking),ln(r,"ended",this.onMediaEnded);var i=this.config;this.levels&&i.autoStartLoad&&this.state===dn&&this.startLoad(i.startPosition)}},{key:"onMediaDetaching",value:function(e,t){var r=!!t.transferMedia,i=this.media;if(null!==i){if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),un(i,"seeking",this.onMediaSeeking),un(i,"ended",this.onMediaEnded),this.keyLoader&&!r&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,r)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}},{key:"onManifestLoading",value:function(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}},{key:"onError",value:function(e,t){}},{key:"onManifestLoaded",value:function(e,t){this.startTimeOffset=t.startTimeOffset}},{key:"onHandlerDestroying",value:function(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),T(t,"onHandlerDestroying",this,3)([]),this.hls=this.onMediaSeeking=this.onMediaEnded=null}},{key:"onHandlerDestroyed",value:function(){this.state=dn,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,T(t,"onHandlerDestroyed",this,3)([])}},{key:"loadFragment",value:function(e,t,r){this.startFragRequested=!0,this._loadFragForPlayback(e,t,r)}},{key:"_loadFragForPlayback",value:function(e,t,r){var i=this;this._doFragLoad(e,t,r,function(e){var t=e.frag;if(i.fragContextChanged(t))return i.warn("".concat(t.type," sn: ").concat(t.sn).concat(e.part?" part: "+e.part.index:""," of ").concat(i.fragInfo(t,!1,e.part),") was dropped during download.")),void i.fragmentTracker.removeFragment(t);t.stats.chunkCount++,i._handleFragmentLoadProgress(e)}).then(function(e){if(e){var t=i.state,r=e.frag;i.fragContextChanged(r)?(t===vn||!i.fragCurrent&&t===mn)&&(i.fragmentTracker.removeFragment(r),i.state=hn):("payload"in e&&(i.log("Loaded ".concat(r.type," sn: ").concat(r.sn," of ").concat(i.playlistLabel()," ").concat(r.level)),i.hls.trigger(ee.FRAG_LOADED,e)),i._handleFragmentLoadComplete(e))}}).catch(function(t){i.state!==dn&&i.state!==En&&(i.warn("Frag error: ".concat((null==t?void 0:t.message)||t)),i.resetFragmentLoading(e))})}},{key:"clearTrackerIfNeeded",value:function(e){var t,r=this.fragmentTracker;if(r.getState(e)===br){var i=e.type,n=this.getFwdBufferInfo(this.mediaBuffer,i),a=Math.max(e.duration,n?n.len:this.config.maxBufferLength),s=this.backtrackFragment;(1===(s?e.sn-s.sn:0)||this.reduceMaxBufferLength(a,e.duration))&&r.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?r.removeAllFragments():r.hasParts(e.type)&&(r.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),r.getState(e)===Ar&&r.removeFragment(e))}},{key:"checkLiveUpdate",value:function(e){if(e.updated&&!e.live){var t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}},{key:"waitForLive",value:function(e){var t=e.details;return(null==t?void 0:t.live)&&"EVENT"!==t.type&&(this.levelLastLoaded!==e||t.expired)}},{key:"flushMainBuffer",value:function(e,t){if(e-t){var r={startOffset:e,endOffset:t,type:arguments.length>2&&void 0!==arguments[2]?arguments[2]:null};this.hls.trigger(ee.BUFFER_FLUSHING,r)}}},{key:"_loadInitSegment",value:function(e,t){var r=this;this._doFragLoad(e,t).then(function(e){var t=null==e?void 0:e.frag;if(!t||r.fragContextChanged(t)||!r.levels)throw new Error("init load aborted");return e}).then(function(e){var t=r.hls,i=e.frag,n=e.payload,a=i.decryptdata;if(n&&n.byteLength>0&&null!=a&&a.key&&a.iv&&ai(a.method)){var s=self.performance.now();return r.decrypter.decrypt(new Uint8Array(n),a.key.buffer,a.iv.buffer,si(a.method)).catch(function(e){throw t.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:i}),e}).then(function(n){var a=self.performance.now();return t.trigger(ee.FRAG_DECRYPTED,{frag:i,payload:n,stats:{tstart:s,tdecrypt:a}}),e.payload=n,r.completeInitSegmentLoad(e)})}return r.completeInitSegmentLoad(e)}).catch(function(t){r.state!==dn&&r.state!==En&&(r.warn(t),r.resetFragmentLoading(e))})}},{key:"completeInitSegmentLoad",value:function(e){if(!this.levels)throw new Error("init load aborted, missing levels");var t=e.frag.stats;this.state!==dn&&(this.state=hn),e.frag.data=new Uint8Array(e.payload),t.parsing.start=t.buffering.start=self.performance.now(),t.parsing.end=t.buffering.end=self.performance.now(),this.tick()}},{key:"unhandledEncryptionError",value:function(e,t){var r,i,n=e.tracks;if(n&&!t.encrypted&&(null!=(r=n.audio)&&r.encrypted||null!=(i=n.video)&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){var a=this.media,s=new Error("Encrypted track with no key in ".concat(this.fragInfo(t)," (media ").concat(a?"attached mediaKeys: "+a.mediaKeys:"detached",")"));return this.warn(s.message),!a||a.mediaKeys?!1:(this.hls.trigger(ee.ERROR,{type:J.KEY_SYSTEM_ERROR,details:Z.KEY_SYSTEM_NO_KEYS,fatal:!1,error:s,frag:t}),this.resetTransmuxer(),!0)}return!1}},{key:"fragContextChanged",value:function(e){var t=this.fragCurrent;return!e||!t||e.sn!==t.sn||e.level!==t.level}},{key:"fragBufferedComplete",value:function(e,t){var r=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log("Buffered ".concat(e.type," sn: ").concat(e.sn).concat(t?" part: "+t.index:""," of ").concat(this.fragInfo(e,!1,t)," > buffer:").concat(r?cn(jr.getBuffered(r)):"(detached)",")")),Oe(e)){var i;if(e.type!==oe){var n=e.elementaryStreams;if(!Object.keys(n).some(function(e){return!!n[e]}))return void(this.state=hn)}var a=null==(i=this.levels)?void 0:i[e.level];null!=a&&a.fragmentError&&(this.log("Resetting level fragment error count of ".concat(a.fragmentError," on frag buffered")),a.fragmentError=0)}this.state=hn}},{key:"_handleFragmentLoadComplete",value:function(e){var t=this.transmuxer;if(t){var r=e.frag,i=e.part,n=e.partsLoaded,a=!n||0===n.length||n.some(function(e){return!e}),s=new Hr(r.level,r.sn,r.stats.chunkCount+1,0,i?i.index:-1,!a);t.flush(s)}}},{key:"_handleFragmentLoadProgress",value:function(e){}},{key:"_doFragLoad",value:function(e,t){var r,i=this,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,a=arguments.length>3?arguments[3]:void 0;this.fragCurrent=e;var s=t.details;if(!this.levels||!s)throw new Error("frag load aborted, missing level".concat(s?"":" detail","s"));var o=null;if(!e.encrypted||null!=(r=e.decryptdata)&&r.key)e.encrypted||(o=this.keyLoader.loadClear(e,s.encryptedFragments,this.startFragRequested))&&this.log("[eme] blocking frag load until media-keys acquired");else if(this.log("Loading key for ".concat(e.sn," of [").concat(s.startSN,"-").concat(s.endSN,"], ").concat(this.playlistLabel()," ").concat(e.level)),this.state=fn,this.fragCurrent=e,o=this.keyLoader.load(e).then(function(e){if(!i.fragContextChanged(e.frag))return i.hls.trigger(ee.KEY_LOADED,e),i.state===fn&&(i.state=hn),e}),this.hls.trigger(ee.KEY_LOADING,{frag:e}),null===this.fragCurrent)return this.log("context changed in KEY_LOADING"),Promise.resolve(null);var l,u=this.fragPrevious;if(Oe(e)&&(!u||e.sn!==u.sn)){var c=this.shouldLoadParts(t.details,e.end);c!==this.loadingParts&&(this.log("LL-Part loading ".concat(c?"ON":"OFF"," loading sn ").concat(null==u?void 0:u.sn,"->").concat(e.sn)),this.loadingParts=c)}if(n=Math.max(e.start,n||0),this.loadingParts&&Oe(e)){var d=s.partList;if(d&&a){n>s.fragmentEnd&&s.fragmentHint&&(e=s.fragmentHint);var h=this.getNextPart(d,e,n);if(h>-1){var f,v=d[h];return e=this.fragCurrent=v.fragment,this.log("Loading ".concat(e.type," sn: ").concat(e.sn," part: ").concat(v.index," (").concat(h,"/").concat(d.length-1,") of ").concat(this.fragInfo(e,!1,v),") cc: ").concat(e.cc," [").concat(s.startSN,"-").concat(s.endSN,"], target: ").concat(parseFloat(n.toFixed(3)))),this.nextLoadPosition=v.start+v.duration,this.state=vn,f=o?o.then(function(r){return!r||i.fragContextChanged(r.frag)?null:i.doFragPartsLoad(e,v,t,a)}).catch(function(e){return i.handleFragLoadError(e)}):this.doFragPartsLoad(e,v,t,a).catch(function(e){return i.handleFragLoadError(e)}),this.hls.trigger(ee.FRAG_LOADING,{frag:e,part:v,targetBufferTime:n}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):f}if(!e.url||this.loadedEndOfParts(d,n))return Promise.resolve(null)}}if(Oe(e)&&this.loadingParts)this.log("LL-Part loading OFF after next part miss @".concat(n.toFixed(2)," Check buffer at sn: ").concat(e.sn," loaded parts: ").concat(null==(l=s.partList)?void 0:l.filter(function(e){return e.loaded}).map(function(e){return"[".concat(e.start,"-").concat(e.end,"]")}))),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);this.log("Loading ".concat(e.type," sn: ").concat(e.sn," of ").concat(this.fragInfo(e,!1),") cc: ").concat(e.cc," ").concat("["+s.startSN+"-"+s.endSN+"]",", target: ").concat(parseFloat(n.toFixed(3)))),X(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=vn;var g,p=this.config.progressive;return g=p&&o?o.then(function(t){return!t||i.fragContextChanged(t.frag)?null:i.fragmentLoader.load(e,a)}).catch(function(e){return i.handleFragLoadError(e)}):Promise.all([this.fragmentLoader.load(e,p?a:void 0),o]).then(function(e){var t=m(e,1)[0];return!p&&a&&a(t),t}).catch(function(e){return i.handleFragLoadError(e)}),this.hls.trigger(ee.FRAG_LOADING,{frag:e,targetBufferTime:n}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):g}},{key:"doFragPartsLoad",value:function(e,t,r,i){var n=this;return new Promise(function(a,s){var o,l=[],u=null==(o=r.details)?void 0:o.partList,c=function(t){n.fragmentLoader.loadPart(e,t,i).then(function(i){l[t.index]=i;var s=i.part;n.hls.trigger(ee.FRAG_LOADED,i);var o=$i(r.details,e.sn,t.index+1)||Ji(u,e.sn,t.index+1);if(!o)return a({frag:e,part:s,partsLoaded:l});c(o)}).catch(s)};c(t)})}},{key:"handleFragLoadError",value:function(e){if("data"in e){var t=e.data;t.frag&&t.details===Z.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===J.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(ee.ERROR,t)}else this.hls.trigger(ee.ERROR,{type:J.OTHER_ERROR,details:Z.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}},{key:"_handleTransmuxerFlush",value:function(e){var t=this.getCurrentContext(e);if(t&&this.state===mn){var r=t.frag,i=t.part,n=t.level,a=self.performance.now();r.stats.parsing.end=a,i&&(i.stats.parsing.end=a);var s=this.getLevelDetails(),o=s&&r.sn>s.endSN||this.shouldLoadParts(s,r.end);o!==this.loadingParts&&(this.log("LL-Part loading ".concat(o?"ON":"OFF"," after parsing segment ending @").concat(r.end.toFixed(2))),this.loadingParts=o),this.updateLevelTiming(r,i,n,e.partial)}else this.fragCurrent||this.state===dn||this.state===En||(this.state=hn)}},{key:"shouldLoadParts",value:function(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var r,i,n=e.partList[0];if(n.fragment.type===oe)return!1;if(t>=n.end+((null==(r=e.fragmentHint)?void 0:r.duration)||0))if((this.hls.hasEnoughToStart?(null==(i=this.media)?void 0:i.currentTime)||this.lastCurrentTime:this.getLoadPosition())>n.start-n.fragment.duration)return!0}}return!1}},{key:"getCurrentContext",value:function(e){var t=this.levels,r=this.fragCurrent,i=e.level,n=e.sn,a=e.part;if(null==t||!t[i])return this.warn("Levels object was unset while buffering fragment ".concat(n," of ").concat(this.playlistLabel()," ").concat(i,". The current chunk will not be buffered.")),null;var s=t[i],o=s.details,l=a>-1?$i(o,n,a):null,u=l?l.fragment:Qi(o,n,r);return u?(r&&r!==u&&(u.stats=r.stats),{frag:u,part:l,level:s}):null}},{key:"bufferFragmentData",value:function(e,t,r,i,n){if(this.state===mn){var a=e.data1,s=e.data2,o=a;if(s&&(o=it(a,s)),o.length){var l=this.initPTS[t.cc],u=l?-l.baseTime/l.timescale:void 0,c={type:e.type,frag:t,part:r,chunkMeta:i,offset:u,parent:t.type,data:o};if(this.hls.trigger(ee.BUFFER_APPENDING,c),e.dropped&&e.independent&&!r){if(n)return;this.flushBufferGap(t)}}}}},{key:"flushBufferGap",value:function(e){var t=this.media;if(t)if(jr.isBuffered(t,t.currentTime)){var r=t.currentTime,i=jr.bufferInfo(t,r,0),n=e.duration,a=Math.min(2*this.config.maxFragLookUpTolerance,.25*n),s=Math.max(Math.min(e.start-a,i.end-a),r+a);e.start-s>a&&this.flushMainBuffer(s,e.start)}else this.flushMainBuffer(0,e.start)}},{key:"getFwdBufferInfo",value:function(e,t){var r,i=this.getLoadPosition();if(!X(i))return null;var n=this.lastCurrentTime>i||null!=(r=this.media)&&r.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,i,t,n)}},{key:"getFwdBufferInfoAtPos",value:function(e,t,r,i){var n=jr.bufferInfo(e,t,i);if(0===n.len&&void 0!==n.nextStart){var a=this.fragmentTracker.getBufferedFrag(t,r);if(a&&(n.nextStart<=a.end||a.gap)){var s=Math.max(Math.min(n.nextStart,a.end)-t,i);return jr.bufferInfo(e,t,s)}}return n}},{key:"getMaxBufferLength",value:function(e){var t,r=this.config;return t=e?Math.max(8*r.maxBufferSize/e,r.maxBufferLength):r.maxBufferLength,Math.min(t,r.maxMaxBufferLength)}},{key:"reduceMaxBufferLength",value:function(e,t){var r=this.config,i=Math.max(Math.min(e-t,r.maxBufferLength),t),n=Math.max(e-3*t,r.maxMaxBufferLength/2,i);return n>=i&&(r.maxMaxBufferLength=n,this.warn("Reduce max buffer length to ".concat(n,"s")),!0)}},{key:"getAppendedFrag",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ae,r=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return r&&"fragment"in r?r.fragment:r}},{key:"getNextFragment",value:function(e,t){var r=t.fragments,i=r.length;if(!i)return null;var n=this.config,a=r[0].start,s=n.lowLatencyMode&&!!t.partList,o=null;if(t.live){var l=n.initialLiveManifestSize;if(i<l)return this.warn("Not enough fragments to start playback (have: ".concat(i,", need: ").concat(l,")")),null;if(!t.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||e<a){var u;s&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),o=this.getInitialLiveFragment(t);var c=this.hls.startPosition,d=this.hls.liveSyncPosition,h=o?(-1!==c&&c>=a?c:d)||o.start:e;this.log("Setting startPosition to ".concat(h," to match start frag at live edge. mainStart: ").concat(c," liveSyncPosition: ").concat(d," frag.start: ").concat(null==(u=o)?void 0:u.start)),this.startPosition=this.nextLoadPosition=h}}else e<=a&&(o=r[0]);if(!o){var f=this.loadingParts?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,f,t)}var v=this.filterReplacedPrimary(o,t);if(!v&&o){var g=o.sn-t.startSN;v=this.filterReplacedPrimary(r[g+1]||null,t)}return this.mapToInitFragWhenRequired(v)}},{key:"isLoopLoading",value:function(e,t){var r=this.fragmentTracker.getState(e);return(r===Lr||r===Ar&&!!e.gap)&&this.nextLoadPosition>t}},{key:"getNextFragmentLoopLoading",value:function(e,t,r,i,n){var a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t))&&!a.gap&&r.nextStart){var s=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,r.nextStart,i,0);if(null!==s&&r.len+s.len>=n){var o=a.sn;return this.loopSn!==o&&(this.log('buffer full after gaps in "'.concat(i,'" playlist starting at sn: ').concat(o)),this.loopSn=o),null}}return this.loopSn=void 0,a}},{key:"primaryPrefetch",get:function(){var e;if(An(this.config)&&(null==(e=this.hls.interstitialsManager)||null==(e=e.playingItem)?void 0:e.event))return!0;return!1}},{key:"filterReplacedPrimary",value:function(e,t){if(!e)return e;if(An(this.config)&&e.type!==oe){var r=this.hls.interstitialsManager,i=null==r?void 0:r.bufferingItem;if(i){var n=i.event;if(n){if(n.appendInPlace||Math.abs(e.start-i.start)>1||0===i.start)return null}else{if(e.end<=i.start&&!1===(null==t?void 0:t.live))return null;if(e.start>i.end&&i.nextEvent&&(i.nextEvent.appendInPlace||e.start-i.end>1))return null}}var a=null==r?void 0:r.playerQueue;if(a)for(var s=a.length;s--;){var o=a[s].interstitial;if(o.appendInPlace&&e.start>=o.startTime&&e.end<=o.resumeTime)return null}}return e}},{key:"mapToInitFragWhenRequired",value:function(e){return null==e||!e.initSegment||e.initSegment.data||this.bitrateTest?e:e.initSegment}},{key:"getNextPart",value:function(e,t,r){for(var i=-1,n=!1,a=!0,s=0,o=e.length;s<o;s++){var l=e[s];if(a=a&&!l.independent,i>-1&&r<l.start)break;var u=l.loaded;u?i=-1:(n||(l.independent||a)&&l.fragment===t)&&(l.fragment!==t&&this.warn("Need buffer at ".concat(r," but next unloaded part starts at ").concat(l.start)),i=s),n=u}return i}},{key:"loadedEndOfParts",value:function(e,t){for(var r,i=e.length;i--;){if(!(r=e[i]).loaded)return!1;if(t>r.start)return!0}return!1}},{key:"getInitialLiveFragment",value:function(e){var t=e.fragments,r=this.fragPrevious,i=null;if(r){if(e.hasProgramDateTime&&(this.log("Live playlist, switching playlist, load frag with same PDT: ".concat(r.programDateTime)),i=function(e,t,r){if(null===t||!Array.isArray(e)||!e.length||!X(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;for(var i=0;i<e.length;++i){var n=e[i];if(rr(t,r,n))return n}return null}(t,r.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){var n=r.sn+1;if(n>=e.startSN&&n<=e.endSN){var a=t[n-e.startSN];r.cc===a.cc&&(i=a,this.log("Live playlist, switching playlist, load frag with next SN: ".concat(i.sn)))}i||(i=ir(e,r.cc,r.end))&&this.log("Live playlist, switching playlist, load frag with same CC: ".concat(i.sn))}}else{var s=this.hls.liveSyncPosition;null!==s&&(i=this.getFragmentAtPosition(s,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}},{key:"getFragmentAtPosition",value:function(e,t,r){var i,n,a=this.config,s=this.fragPrevious,o=r.fragments,l=r.endSN,u=r.fragmentHint,c=a.maxFragLookUpTolerance,d=r.partList,h=!!(this.loadingParts&&null!=d&&d.length&&u);(h&&!this.bitrateTest&&d[d.length-1].fragment.sn===u.sn&&(o=o.concat(u),l=u.sn),e<t)?i=er(s,o,e,e<this.lastCurrentTime||e>t-c||null!=(n=this.media)&&n.paused||!this.startFragRequested?0:c):i=o[o.length-1];if(i){var f=i.sn-r.startSN,v=this.fragmentTracker.getState(i);if((v===Lr||v===Ar&&i.gap)&&(s=i),s&&i.sn===s.sn&&(!h||d[0].fragment.sn>i.sn||!r.live))if(i.level===s.level){var g=o[f+1];i=i.sn<l&&this.fragmentTracker.getState(g)!==Lr?g:null}}return i}},{key:"alignPlaylists",value:function(e,t,r){var i=e.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;var n=e.fragmentStart,a=!t,s=e.alignedSliding&&X(n);if(a||!s&&!n){!function(e,t){e&&(sn(t,e),t.alignedSliding||on(t,e),t.alignedSliding||t.skippedSegments||Yi(e,t,!1))}(r,e);var o=e.fragmentStart;return this.log("Live playlist sliding: ".concat(o.toFixed(2)," start-sn: ").concat(t?t.startSN:"na","->").concat(e.startSN," fragments: ").concat(i)),o}return n}},{key:"waitForCdnTuneIn",value:function(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}},{key:"setStartPosition",value:function(e,t){var r=this.startPosition;r<t&&(r=-1);var i=this.timelineOffset;if(-1===r){var n=null!==this.startTimeOffset,a=n?this.startTimeOffset:e.startTimeOffset;null!==a&&X(a)?(r=t+a,a<0&&(r+=e.edge),r=Math.min(Math.max(t,r),t+e.totalduration),this.log("Setting startPosition to ".concat(r," for start time offset ").concat(a," found in ").concat(n?"multivariant":"media"," playlist")),this.startPosition=r):e.live?(r=this.hls.liveSyncPosition||t,this.log("Setting startPosition to -1 to start at live edge ".concat(r)),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=r=0),this.lastCurrentTime=r+i}this.nextLoadPosition=r+i}},{key:"getLoadPosition",value:function(){var e,t=this.media,r=0;return null!=(e=this.hls)&&e.hasEnoughToStart&&t?r=t.currentTime:this.nextLoadPosition>=0&&(r=this.nextLoadPosition),r}},{key:"handleFragLoadAborted",value:function(e,t){this.transmuxer&&e.type===this.playlistType&&Oe(e)&&e.stats.aborted&&(this.log("Fragment ".concat(e.sn).concat(t?" part "+t.index:""," of ").concat(this.playlistLabel()," ").concat(e.level," was aborted")),this.resetFragmentLoading(e))}},{key:"resetFragmentLoading",value:function(e){this.fragCurrent&&(this.fragContextChanged(e)||this.state===gn)||(this.state=hn)}},{key:"onFragmentOrKeyLoadError",value:function(e,t){var r;if(t.chunkMeta&&!t.frag){var i=this.getCurrentContext(t.chunkMeta);i&&(t.frag=i.frag)}var n=t.frag;if(n&&n.type===e&&this.levels)if(this.fragContextChanged(n)){var a;this.warn("Frag load error must match current frag to retry ".concat(n.url," > ").concat(null==(a=this.fragCurrent)?void 0:a.url))}else{var s=t.details===Z.FRAG_GAP;s&&this.fragmentTracker.fragBuffered(n,!0);var o=t.errorAction;if(o){var l=o.action,u=o.flags,c=o.retryCount,d=void 0===c?0:c,h=o.retryConfig,f=!!h,v=f&&l===gr,g=f&&!o.resolved&&u===mr,p=null==(r=this.hls.latestLevelDetails)?void 0:r.live;if(!v&&g&&Oe(n)&&!n.endList&&p&&!sr(t))this.resetFragmentErrors(e),this.treatAsGap(n),o.resolved=!0;else if((v||g)&&d<h.maxNumRetry){var m,y=dr(null==(m=t.response)?void 0:m.code),T=lr(h,d);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+T,this.state=gn,o.resolved=!0,y)return this.log("Waiting for connection (offline)"),this.retryDate=1/0,void(t.reason="offline");this.warn("Fragment ".concat(n.sn," of ").concat(e," ").concat(n.level," errored with ").concat(t.details,", retrying loading ").concat(d+1,"/").concat(h.maxNumRetry," in ").concat(T,"ms"))}else if(h){if(this.resetFragmentErrors(e),!(d<h.maxNumRetry))return void this.warn("".concat(t.details," reached or exceeded max retry (").concat(d,")"));s||l===vr||(o.resolved=!0)}else this.state=l===fr?Sn:En;this.tickImmediate()}else this.state=En}}},{key:"checkRetryDate",value:function(){var e=self.performance.now(),t=this.retryDate,r=t===1/0;(!t||e>=t||r&&!dr(0))&&(r&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=hn)}},{key:"reduceLengthAndFlushBuffer",value:function(e){if(this.state===mn||this.state===yn){var t=e.frag,r=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,r),n=i&&i.len>.5;n&&this.reduceMaxBufferLength(i.len,(null==t?void 0:t.duration)||10);var a=!n;return a&&this.warn("Buffer full error while media.currentTime (".concat(this.getLoadPosition(),") is not buffered, flush ").concat(r," buffer")),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}},{key:"resetFragmentErrors",value:function(e){e===se&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==dn&&(this.state=hn)}},{key:"afterBufferFlushed",value:function(e,t,r){if(e){var i=jr.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,r),this.state===Tn&&this.resetLoadingState()}}},{key:"resetLoadingState",value:function(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==dn&&(this.state=hn)}},{key:"resetStartWhenNotLoaded",value:function(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;var e=this.levelLastLoaded,t=e?e.details:null;null!=t&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}},{key:"resetWhenMissingContext",value:function(e){this.log("Loading context changed while buffering sn ".concat(e.sn," of ").concat(this.playlistLabel()," ").concat(-1===e.level?"<removed>":e.level,". This chunk will not be buffered.")),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}},{key:"removeUnbufferedFrags",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}},{key:"updateLevelTiming",value:function(e,t,r,i){var n=this,a=r.details;if(a){var s;if(!Object.keys(e.elementaryStreams).reduce(function(t,s){var o=e.elementaryStreams[s];if(o){var l=o.endPTS-o.startPTS;if(l<=0)return n.warn("Could not parse fragment ".concat(e.sn," ").concat(s," duration reliably (").concat(l,")")),t||!1;var u=i?0:ji(a,e,o.startPTS,o.endPTS,o.startDTS,o.endDTS,n);return n.hls.trigger(ee.LEVEL_PTS_UPDATED,{details:a,level:r,drift:u,type:s,frag:e,start:o.startPTS,end:o.endPTS}),!0}return t},!1))if(0===r.fragmentError&&this.treatAsGap(e,r),null===(null==(s=this.transmuxer)?void 0:s.error)){var o=new Error("Found no media in fragment ".concat(e.sn," of ").concat(this.playlistLabel()," ").concat(e.level," resetting transmuxer to fallback to playlist timing"));if(this.warn(o.message),this.hls.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.FRAG_PARSING_ERROR,fatal:!1,error:o,frag:e,reason:"Found no media in msn ".concat(e.sn," of ").concat(this.playlistLabel(),' "').concat(r.url,'"')}),!this.hls)return;this.resetTransmuxer()}this.state=yn,this.log("Parsed ".concat(e.type," sn: ").concat(e.sn).concat(t?" part: "+t.index:""," of ").concat(this.fragInfo(e,!1,t),")")),this.hls.trigger(ee.FRAG_PARSED,{frag:e,part:t})}else this.warn("level.details undefined")}},{key:"playlistLabel",value:function(){return this.playlistType===ae?"level":"track"}},{key:"fragInfo",value:function(e){var t,r,i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],n=arguments.length>2?arguments[2]:void 0;return"".concat(this.playlistLabel()," ").concat(e.level," (").concat(n?"part":"frag",":[").concat((null!=(t=i&&!n?e.startPTS:(n||e).start)?t:NaN).toFixed(3),"-").concat((null!=(r=i&&!n?e.endPTS:(n||e).end)?r:NaN).toFixed(3),"]").concat(n&&"main"===e.type?"INDEPENDENT="+(n.independent?"YES":"NO"):"")}},{key:"treatAsGap",value:function(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}},{key:"resetTransmuxer",value:function(){var e;null==(e=this.transmuxer)||e.reset()}},{key:"recoverWorkerError",value:function(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}},{key:"state",get:function(){return this._state},set:function(e){var t=this._state;t!==e&&(this._state=e,this.log("".concat(t,"->").concat(e)))}}])}(Gr);function An(e){return!!e.interstitialsController&&!1!==e.enableInterstitialPlayback}var Ln=function(){return o(function e(){a(this,e),this.chunks=[],this.dataLength=0},[{key:"push",value:function(e){this.chunks.push(e),this.dataLength+=e.length}},{key:"flush",value:function(){var e,t=this.chunks,r=this.dataLength;return t.length?(e=1===t.length?t[0]:function(e,t){for(var r=new Uint8Array(t),i=0,n=0;n<e.length;n++){var a=e[n];r.set(a,i),i+=a.length}return r}(t,r),this.reset(),e):new Uint8Array(0)}},{key:"reset",value:function(){this.chunks.length=0,this.dataLength=0}}])}();var Rn,In={exports:{}};var wn=(Rn||(Rn=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}(In)),In.exports),Pn=Re(wn),Dn="1.6.14",xn={};function Cn(e,t){return t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function _n(e,t){return t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function Mn(e,t){var r=0;return r=(127&e[t])<<21,r|=(127&e[t+1])<<14,r|=(127&e[t+2])<<7,r|=127&e[t+3]}function On(e,t){for(var r=t,i=0;_n(e,t);){i+=10,i+=Mn(e,t+6),Cn(e,t+10)&&(i+=10),t+=i}if(i>0)return e.subarray(r,r+i)}function Fn(e,t){return 255===e[t]&&240==(246&e[t+1])}function Un(e,t){return 1&e[t+1]?7:9}function Nn(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function Bn(e,t){return t+1<e.length&&Fn(e,t)}function Vn(e,t){if(Bn(e,t)){var r=Un(e,t);if(t+r>=e.length)return!1;var i=Nn(e,t);if(i<=r)return!1;var n=t+i;return n===e.length||Bn(e,n)}return!1}function Gn(e,t,r,i,n){if(!e.samplerate){var a=function(e,t,r,i){var n=t[r+2],a=n>>2&15;if(!(a>12)){var s=1+(n>>6&3),o=t[r+3]>>6&3|(1&n)<<2,l="mp4a.40."+s,u=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][a],c=a;5!==s&&29!==s||(c-=3);var d=[s<<3|(14&c)>>1,(1&c)<<7|o<<3];return Ee.log("manifest codec:".concat(i,", parsed codec:").concat(l,", channels:").concat(o,", rate:").concat(u," (ADTS object type:").concat(s," sampling index:").concat(a,")")),{config:d,samplerate:u,channelCount:o,codec:l,parsedCodec:l,manifestCodec:i}}var h=new Error("invalid ADTS sampling index:".concat(a));e.emit(ee.ERROR,ee.ERROR,{type:J.MEDIA_ERROR,details:Z.FRAG_PARSING_ERROR,fatal:!0,error:h,reason:h.message})}(t,r,i,n);if(!a)return;de(e,a)}}function Hn(e){return 9216e4/e}function Kn(e,t,r,i,n){var a,s=i+n*Hn(e.samplerate),o=function(e,t){var r=Un(e,t);if(t+r<=e.length){var i=Nn(e,t)-r;if(i>0)return{headerLength:r,frameLength:i}}}(t,r);if(o){var l=o.frameLength,u=o.headerLength,c=u+l,d=Math.max(0,r+c-t.length);d?(a=new Uint8Array(c-u)).set(t.subarray(r+u,t.length),0):a=t.subarray(r+u,r+c);var h={unit:a,pts:s};return d||e.samples.push(h),{sample:h,length:c,missing:d}}var f=t.length-r;return(a=new Uint8Array(f)).set(t.subarray(r,t.length),0),{sample:{unit:a,pts:s},length:f,missing:-1}}function jn(e,t){return _n(e,t)&&Mn(e,t+6)+10<=e.length-t}function qn(e){return function(e,t,r,i){var n=function(e){return e instanceof ArrayBuffer?e:e.buffer}(e),a=1;"BYTES_PER_ELEMENT"in i&&(a=i.BYTES_PER_ELEMENT);var s=(d=e,d&&d.buffer instanceof ArrayBuffer&&void 0!==d.byteLength&&void 0!==d.byteOffset?e.byteOffset:0),o=(s+e.byteLength)/a,l=(s+t)/a,u=Math.floor(Math.max(0,Math.min(l,o))),c=Math.floor(Math.min(u+Math.max(r,0),o));var d;return new i(n,u,c-u)}(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,arguments.length>2&&void 0!==arguments[2]?arguments[2]:1/0,Uint8Array)}function Wn(e){var t={key:e.type,description:"",data:"",mimeType:null,pictureType:null};if(!(e.size<2))if(3===e.data[0]){var r=e.data.subarray(1).indexOf(0);if(-1!==r){var i=be(qn(e.data,1,r)),n=e.data[2+r],a=e.data.subarray(3+r).indexOf(0);if(-1!==a){var s,o=be(qn(e.data,3+r,a));return s="--\x3e"===i?be(qn(e.data,4+r+a)):function(e){return e instanceof ArrayBuffer?e:0==e.byteOffset&&e.byteLength==e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer}(e.data.subarray(4+r+a)),t.mimeType=i,t.pictureType=n,t.description=o,t.data=s,t}}}else console.log("Ignore frame with unrecognized character encoding")}function Yn(e){return"PRIV"===e.type?function(e){if(!(e.size<2)){var t=be(e.data,!0),r=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:r.buffer}}}(e):"W"===e.type[0]?function(e){if("WXXX"===e.type){if(e.size<2)return;var t=1,r=be(e.data.subarray(t),!0);t+=r.length+1;var i=be(e.data.subarray(t));return{key:e.type,info:r,data:i}}var n=be(e.data);return{key:e.type,info:"",data:n}}(e):"APIC"===e.type?Wn(e):function(e){if(!(e.size<2)){if("TXXX"===e.type){var t=1,r=be(e.data.subarray(t),!0);t+=r.length+1;var i=be(e.data.subarray(t));return{key:e.type,info:r,data:i}}var n=be(e.data.subarray(1));return{key:e.type,info:"",data:n}}}(e)}function zn(e){var t=String.fromCharCode(e[0],e[1],e[2],e[3]),r=Mn(e,4);return{type:t,size:r,data:e.subarray(10,10+r)}}function Xn(e){for(var t=0,r=[];_n(e,t);){var i=Mn(e,t+6);e[t+5]>>6&1&&(t+=10);for(var n=(t+=10)+i;t+10<n;){var a=zn(e.subarray(t)),s=Yn(a);s&&r.push(s),t+=a.size+10}Cn(e,t)&&(t+=10)}return r}function Qn(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info}function $n(e){if(8===e.data.byteLength){var t=new Uint8Array(e.data),r=1&t[3],i=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return i/=45,r&&(i+=47721858.84),Math.round(i)}}function Jn(e){for(var t=Xn(e),r=0;r<t.length;r++){var i=t[r];if(Qn(i))return $n(i)}}var Zn=function(e){return e.audioId3="org.id3",e.dateRange="com.apple.quicktime.HLS",e.emsg="https://aomedia.org/emsg/ID3",e.misbklv="urn:misb:KLV:bin:1910.1",e}({});function ea(){return{type:arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",id:-1,pid:-1,inputTimeScale:arguments.length>1&&void 0!==arguments[1]?arguments[1]:9e4,sequenceNumber:-1,samples:[],dropped:0}}var ta=function(){return o(function e(){a(this,e),this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null},[{key:"resetInitSegment",value:function(e,t,r,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}},{key:"resetTimeStamp",value:function(e){this.initPTS=e,this.resetContiguity()}},{key:"resetContiguity",value:function(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}},{key:"canParse",value:function(e,t){return!1}},{key:"appendFrame",value:function(e,t,r){}},{key:"demux",value:function(e,t){this.cachedData&&(e=it(this.cachedData,e),this.cachedData=null);var r,i=On(e,0),n=i?i.length:0,a=this._audioTrack,s=this._id3Track,o=i?Jn(i):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&X(o))&&(this.basePTS=ra(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),i&&i.length>0&&s.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Zn.audioId3,duration:Number.POSITIVE_INFINITY});n<l;){if(this.canParse(e,n)){var u=this.appendFrame(a,e,n);u?(this.frameIndex++,this.lastPTS=u.sample.pts,r=n+=u.length):n=l}else jn(e,n)?(i=On(e,n),s.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Zn.audioId3,duration:Number.POSITIVE_INFINITY}),r=n+=i.length):n++;if(n===l&&r!==l){var c=e.slice(r);this.cachedData?this.cachedData=it(this.cachedData,c):this.cachedData=c}}return{audioTrack:a,videoTrack:ea(),id3Track:s,textTrack:ea()}}},{key:"demuxSampleAes",value:function(e,t,r){return Promise.reject(new Error("[".concat(this,"] This demuxer does not support Sample-AES decryption")))}},{key:"flush",value:function(e){var t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:ea(),id3Track:this._id3Track,textTrack:ea()}}},{key:"destroy",value:function(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}])}(),ra=function(e,t,r){return X(e)?90*e:9e4*t+(r?9e4*r.baseTime/r.timescale:0)},ia=null,na=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],aa=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],sa=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],oa=[0,1,1,4];function la(e,t,r,i,n){if(!(r+24>t.length)){var a=ua(t,r);if(a&&r+a.frameLength<=t.length){var s=i+n*(9e4*a.samplesPerFrame/a.sampleRate),o={unit:t.subarray(r,r+a.frameLength),pts:s,dts:s};return e.config=[],e.channelCount=a.channelCount,e.samplerate=a.sampleRate,e.samples.push(o),{sample:o,length:a.frameLength,missing:0}}}}function ua(e,t){var r=e[t+1]>>3&3,i=e[t+1]>>1&3,n=e[t+2]>>4&15,a=e[t+2]>>2&3;if(1!==r&&0!==n&&15!==n&&3!==a){var s=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*na[14*(3===r?3-i:3===i?3:4)+n-1],u=aa[3*(3===r?0:2===r?1:2)+a],c=3===o?1:2,d=sa[r][i],h=oa[i],f=8*d*h,v=Math.floor(d*l/u+s)*h;if(null===ia){var g=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);ia=g?parseInt(g[1]):0}return!!ia&&ia<=87&&2===i&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:u,channelCount:c,frameLength:v,samplesPerFrame:f}}}function ca(e,t){return!(255!==e[t]||224&~e[t+1]||!(6&e[t+1]))}function da(e,t){return t+1<e.length&&ca(e,t)}function ha(e,t){if(t+1<e.length&&ca(e,t)){var r=ua(e,t),i=4;null!=r&&r.frameLength&&(i=r.frameLength);var n=t+i;return n===e.length||da(e,n)}return!1}var fa=function(e){function t(e,r){var i;return a(this,t),(i=n(this,t)).observer=void 0,i.config=void 0,i.observer=e,i.config=r,i}return d(t,e),o(t,[{key:"resetInitSegment",value:function(e,r,i,n){T(t,"resetInitSegment",this,3)([e,r,i,n]),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:r,duration:n,inputTimeScale:9e4,dropped:0}}},{key:"canParse",value:function(e,t){return function(e,t){return function(e,t){return t+5<e.length}(e,t)&&Fn(e,t)&&Nn(e,t)<=e.length-t}(e,t)}},{key:"appendFrame",value:function(e,t,r){Gn(e,this.observer,t,r,e.manifestCodec);var i=Kn(e,t,r,this.basePTS,this.frameIndex);if(i&&0===i.missing)return i}}],[{key:"probe",value:function(e,t){if(!e)return!1;var r=On(e,0),i=(null==r?void 0:r.length)||0;if(ha(e,i))return!1;for(var n=e.length;i<n;i++)if(Vn(e,i))return t.log("ADTS sync word found !"),!0;return!1}}])}(ta),va=function(e,t){var r=0,i=5;t+=i;for(var n=new Uint32Array(1),a=new Uint32Array(1),s=new Uint8Array(1);i>0;){s[0]=e[t];var o=Math.min(i,8),l=8-o;a[0]=4278190080>>>24+l<<l,n[0]=(s[0]&a[0])>>l,r=r?r<<o|n[0]:n[0],t+=1,i-=o}return r},ga=function(e){function t(e){var r;return a(this,t),(r=n(this,t)).observer=void 0,r.observer=e,r}return d(t,e),o(t,[{key:"resetInitSegment",value:function(e,r,i,n){T(t,"resetInitSegment",this,3)([e,r,i,n]),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:r,duration:n,inputTimeScale:9e4,dropped:0}}},{key:"canParse",value:function(e,t){return t+64<e.length}},{key:"appendFrame",value:function(e,t,r){var i=pa(e,t,r,this.basePTS,this.frameIndex);if(-1!==i)return{sample:e.samples[e.samples.length-1],length:i,missing:0}}}],[{key:"probe",value:function(e){if(!e)return!1;var t=On(e,0);if(!t)return!1;var r=t.length;return 11===e[r]&&119===e[r+1]&&void 0!==Jn(t)&&va(e,r)<16}}])}(ta);function pa(e,t,r,i,n){if(r+8>t.length)return-1;if(11!==t[r]||119!==t[r+1])return-1;var a=t[r+4]>>6;if(a>=3)return-1;var s=[48e3,44100,32e3][a],o=63&t[r+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+a];if(r+l>t.length)return-1;var u=t[r+6]>>5,c=0;2===u?c+=2:(1&u&&1!==u&&(c+=2),4&u&&(c+=2));var d=(t[r+6]<<8|t[r+7])>>12-c&1,h=[2,1,2,3,3,4,4,5][u]+d,f=t[r+5]>>3,v=7&t[r+5],g=new Uint8Array([a<<6|f<<1|v>>2,(3&v)<<6|u<<3|d<<2|o>>4,o<<4&224]),p=i+n*(1536/s*9e4),m=t.subarray(r,r+l);return e.config=g,e.channelCount=h,e.samplerate=s,e.samples.push({unit:m,pts:p}),l}var ma=function(e){function t(){return a(this,t),n(this,t,arguments)}return d(t,e),o(t,[{key:"resetInitSegment",value:function(e,r,i,n){T(t,"resetInitSegment",this,3)([e,r,i,n]),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:r,duration:n,inputTimeScale:9e4,dropped:0}}},{key:"canParse",value:function(e,t){return function(e,t){return ca(e,t)&&4<=e.length-t}(e,t)}},{key:"appendFrame",value:function(e,t,r){if(null!==this.basePTS)return la(e,t,r,this.basePTS,this.frameIndex)}}],[{key:"probe",value:function(e){if(!e)return!1;var t=On(e,0),r=(null==t?void 0:t.length)||0;if(t&&11===e[r]&&119===e[r+1]&&void 0!==Jn(t)&&va(e,r)<=16)return!1;for(var i=e.length;r<i;r++)if(ha(e,r))return Ee.log("MPEG Audio sync word found !"),!0;return!1}}])}(ta),ya=/\/emsg[-/]ID3/i,Ta=function(){return o(function e(t,r){a(this,e),this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=r},[{key:"resetTimeStamp",value:function(){}},{key:"resetInitSegment",value:function(e,t,r,i){var n=this.videoTrack=ea("video",1),a=this.audioTrack=ea("audio",1),s=this.txtTrack=ea("text",1);if(this.id3Track=ea("id3",1),this.timeOffset=0,null!=e&&e.byteLength){var o=Xe(e);if(o.video){var l=o.video,u=l.id,c=l.timescale,d=l.codec,h=l.supplemental;n.id=u,n.timescale=s.timescale=c,n.codec=d,n.supplemental=h}if(o.audio){var f=o.audio,v=f.id,g=f.timescale,p=f.codec;a.id=v,a.timescale=g,a.codec=p}s.id=Ge.text,n.sampleDuration=0,n.duration=a.duration=i}}},{key:"resetContiguity",value:function(){this.remainderData=null}},{key:"demux",value:function(e,t){this.timeOffset=t;var r=e,i=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(r=it(this.remainderData,e));var a=function(e){var t={valid:null,remainder:null},r=Ye(e,["moof"]);if(r.length<2)return t.remainder=e,t;var i=r[r.length-1];return t.valid=e.slice(0,i.byteOffset-8),t.remainder=e.slice(i.byteOffset-8),t}(r);this.remainderData=a.remainder,i.samples=a.valid||new Uint8Array}else i.samples=r;var s=this.extractID3Track(i,t);return n.samples=nt(t,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:s,textTrack:this.txtTrack}}},{key:"flush",value:function(){var e=this.timeOffset,t=this.videoTrack,r=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;var i=this.extractID3Track(t,this.timeOffset);return r.samples=nt(e,t),{videoTrack:t,audioTrack:ea(),id3Track:i,textTrack:ea()}}},{key:"extractID3Track",value:function(e,t){var r=this,i=this.id3Track;if(e.samples.length){var n=Ye(e.samples,["emsg"]);n&&n.forEach(function(e){var n=function(e){var t=e[0],r="",i="",n=0,a=0,s=0,o=0,l=0,u=0;if(0===t){for(;"\0"!==He(e.subarray(u,u+1));)r+=He(e.subarray(u,u+1)),u+=1;for(r+=He(e.subarray(u,u+1)),u+=1;"\0"!==He(e.subarray(u,u+1));)i+=He(e.subarray(u,u+1)),u+=1;i+=He(e.subarray(u,u+1)),u+=1,n=je(e,12),a=je(e,16),o=je(e,20),l=je(e,24),u=28}else if(1===t){n=je(e,u+=4);var c=je(e,u+=4),d=je(e,u+=4);for(u+=4,s=Math.pow(2,32)*c+d,Q(s)||(s=Number.MAX_SAFE_INTEGER,Ee.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=je(e,u),l=je(e,u+=4),u+=4;"\0"!==He(e.subarray(u,u+1));)r+=He(e.subarray(u,u+1)),u+=1;for(r+=He(e.subarray(u,u+1)),u+=1;"\0"!==He(e.subarray(u,u+1));)i+=He(e.subarray(u,u+1)),u+=1;i+=He(e.subarray(u,u+1)),u+=1}return{schemeIdUri:r,value:i,timeScale:n,presentationTime:s,presentationTimeDelta:a,eventDuration:o,id:l,payload:e.subarray(u,e.byteLength)}}(e);if(ya.test(n.schemeIdUri)){var a=Ea(n,t),s=4294967295===n.eventDuration?Number.POSITIVE_INFINITY:n.eventDuration/n.timeScale;s<=.001&&(s=Number.POSITIVE_INFINITY);var o=n.payload;i.samples.push({data:o,len:o.byteLength,dts:a,pts:a,type:Zn.emsg,duration:s})}else if(r.config.enableEmsgKLVMetadata&&n.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){var l=Ea(n,t);i.samples.push({data:n.payload,len:n.payload.byteLength,dts:l,pts:l,type:Zn.misbklv,duration:Number.POSITIVE_INFINITY})}})}return i}},{key:"demuxSampleAes",value:function(e,t,r){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}},{key:"destroy",value:function(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}}],[{key:"probe",value:function(e){return function(e){for(var t=e.byteLength,r=0;r<t;){var i=je(e,r);if(i>8&&109===e[r+4]&&111===e[r+5]&&111===e[r+6]&&102===e[r+7])return!0;r=i>1?r+i:t}return!1}(e)}}])}();function Ea(e,t){return X(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}var ka=function(){return o(function e(t,r,i){a(this,e),this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Or(r,{removePKCS7Padding:!1})},[{key:"decryptBuffer",value:function(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Dr)}},{key:"decryptAacSample",value:function(e,t,r){var i=this,n=e[t].unit;if(!(n.length<=16)){var a=n.subarray(16,n.length-n.length%16),s=a.buffer.slice(a.byteOffset,a.byteOffset+a.length);this.decryptBuffer(s).then(function(a){var s=new Uint8Array(a);n.set(s,16),i.decrypter.isSync()||i.decryptAacSamples(e,t+1,r)}).catch(r)}}},{key:"decryptAacSamples",value:function(e,t,r){for(;;t++){if(t>=e.length)return void r();if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,r),!this.decrypter.isSync()))return}}},{key:"getAvcEncryptedData",value:function(e){for(var t=16*Math.floor((e.length-48)/160)+16,r=new Int8Array(t),i=0,n=32;n<e.length-16;n+=160,i+=16)r.set(e.subarray(n,n+16),i);return r}},{key:"getAvcDecryptedUnit",value:function(e,t){for(var r=new Uint8Array(t),i=0,n=32;n<e.length-16;n+=160,i+=16)e.set(r.subarray(i,i+16),n);return e}},{key:"decryptAvcSample",value:function(e,t,r,i,n){var a=this,s=lt(n.data),o=this.getAvcEncryptedData(s);this.decryptBuffer(o.buffer).then(function(o){n.data=a.getAvcDecryptedUnit(s,o),a.decrypter.isSync()||a.decryptAvcSamples(e,t,r+1,i)}).catch(i)}},{key:"decryptAvcSamples",value:function(e,t,r,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,r=0){if(t>=e.length)return void i();for(var n=e[t].units;!(r>=n.length);r++){var a=n[r];if(!(a.data.length<=48||1!==a.type&&5!==a.type||(this.decryptAvcSample(e,t,r,i,a),this.decrypter.isSync())))return}}}}])}(),Sa=function(){return o(function e(){a(this,e),this.VideoSample=null},[{key:"createVideoSample",value:function(e,t,r){return{key:e,frame:!1,pts:t,dts:r,units:[],length:0}}},{key:"getLastNalUnit",value:function(e){var t,r,i=this.VideoSample;if(i&&0!==i.units.length||(i=e[e.length-1]),null!=(t=i)&&t.units){var n=i.units;r=n[n.length-1]}return r}},{key:"pushAccessUnit",value:function(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){var r=t.samples,i=r.length;if(!i)return void t.dropped++;var n=r[i-1];e.pts=n.pts,e.dts=n.dts}t.samples.push(e)}}},{key:"parseNALu",value:function(e,t,r){var i,n,a=t.byteLength,s=e.naluState||0,o=s,l=[],u=0,c=-1,d=0;for(-1===s&&(c=0,d=this.getNALuType(t,0),s=0,u=1);u<a;)if(i=t[u++],s)if(1!==s)if(i)if(1===i){if(n=u-s-1,c>=0){var h={data:t.subarray(c,n),type:d};l.push(h)}else{var f=this.getLastNalUnit(e.samples);f&&(o&&u<=4-o&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-o)),n>0&&(f.data=it(f.data,t.subarray(0,n)),f.state=0))}u<a?(c=u,d=this.getNALuType(t,u),s=0):s=-1}else s=0;else s=3;else s=i?0:2;else s=i?0:1;if(c>=0&&s>=0){var v={data:t.subarray(c,a),type:d,state:s};l.push(v)}if(0===l.length){var g=this.getLastNalUnit(e.samples);g&&(g.data=it(g.data,t))}return e.naluState=s,l}}])}(),ba=function(){return o(function e(t){a(this,e),this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0},[{key:"loadWord",value:function(){var e=this.data,t=this.bytesAvailable,r=e.byteLength-t,i=new Uint8Array(4),n=Math.min(4,t);if(0===n)throw new Error("no bytes available");i.set(e.subarray(r,r+n)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*n,this.bytesAvailable-=n}},{key:"skipBits",value:function(e){var t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,e-=(t=e>>3)<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}},{key:"readBits",value:function(e){var t=Math.min(this.bitsAvailable,e),r=this.word>>>32-t;if(e>32&&Ee.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return(t=e-t)>0&&this.bitsAvailable?r<<t|this.readBits(t):r}},{key:"skipLZ",value:function(){var e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}},{key:"skipUEG",value:function(){this.skipBits(1+this.skipLZ())}},{key:"skipEG",value:function(){this.skipBits(1+this.skipLZ())}},{key:"readUEG",value:function(){var e=this.skipLZ();return this.readBits(e+1)-1}},{key:"readEG",value:function(){var e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}},{key:"readBoolean",value:function(){return 1===this.readBits(1)}},{key:"readUByte",value:function(){return this.readBits(8)}},{key:"readUShort",value:function(){return this.readBits(16)}},{key:"readUInt",value:function(){return this.readBits(32)}}])}(),Aa=function(e){function t(){return a(this,t),n(this,t,arguments)}return d(t,e),o(t,[{key:"parsePES",value:function(e,t,r,i){var n,a=this,s=this.parseNALu(e,r.data,i),o=this.VideoSample,l=!1;r.data=null,o&&s.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),s.forEach(function(i){var s,u;switch(i.type){case 1:var c=!1;n=!0;var d,h=i.data;if(l&&h.length>4){var f=a.readSliceType(h);2!==f&&4!==f&&7!==f&&9!==f||(c=!0)}if(c)null!=(d=o)&&d.frame&&!o.key&&(a.pushAccessUnit(o,e),o=a.VideoSample=null);o||(o=a.VideoSample=a.createVideoSample(!0,r.pts,r.dts)),o.frame=!0,o.key=c;break;case 5:n=!0,null!=(s=o)&&s.frame&&!o.key&&(a.pushAccessUnit(o,e),o=a.VideoSample=null),o||(o=a.VideoSample=a.createVideoSample(!0,r.pts,r.dts)),o.key=!0,o.frame=!0;break;case 6:n=!0,ot(i.data,1,r.pts,t.samples);break;case 7:var v,g;n=!0,l=!0;var p=i.data,m=a.readSPS(p);if(!e.sps||e.width!==m.width||e.height!==m.height||(null==(v=e.pixelRatio)?void 0:v[0])!==m.pixelRatio[0]||(null==(g=e.pixelRatio)?void 0:g[1])!==m.pixelRatio[1]){e.width=m.width,e.height=m.height,e.pixelRatio=m.pixelRatio,e.sps=[p];for(var y=p.subarray(1,4),T="avc1.",E=0;E<3;E++){var k=y[E].toString(16);k.length<2&&(k="0"+k),T+=k}e.codec=T}break;case 8:n=!0,e.pps=[i.data];break;case 9:n=!0,e.audFound=!0,null!=(u=o)&&u.frame&&(a.pushAccessUnit(o,e),o=null),o||(o=a.VideoSample=a.createVideoSample(!1,r.pts,r.dts));break;case 12:n=!0;break;default:n=!1}o&&n&&o.units.push(i)}),i&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}},{key:"getNALuType",value:function(e,t){return 31&e[t]}},{key:"readSliceType",value:function(e){var t=new ba(e);return t.readUByte(),t.readUEG(),t.readUEG()}},{key:"skipScalingList",value:function(e,t){for(var r=8,i=8,n=0;n<e;n++)0!==i&&(i=(r+t.readEG()+256)%256),r=0===i?r:i}},{key:"readSPS",value:function(e){var t,r,i,n=new ba(e),a=0,s=0,o=0,l=0,u=n.readUByte.bind(n),c=n.readBits.bind(n),d=n.readUEG.bind(n),h=n.readBoolean.bind(n),f=n.skipBits.bind(n),v=n.skipEG.bind(n),g=n.skipUEG.bind(n),p=this.skipScalingList.bind(this);u();var m=u();if(c(5),f(3),u(),g(),100===m||110===m||122===m||244===m||44===m||83===m||86===m||118===m||128===m){var y=d();if(3===y&&f(1),g(),g(),f(1),h())for(r=3!==y?8:12,i=0;i<r;i++)h()&&p(i<6?16:64,n)}g();var T=d();if(0===T)d();else if(1===T)for(f(1),v(),v(),t=d(),i=0;i<t;i++)v();g(),f(1);var E=d(),k=d(),S=c(1);0===S&&f(1),f(1),h()&&(a=d(),s=d(),o=d(),l=d());var b=[1,1];if(h()&&h())switch(u()){case 1:b=[1,1];break;case 2:b=[12,11];break;case 3:b=[10,11];break;case 4:b=[16,11];break;case 5:b=[40,33];break;case 6:b=[24,11];break;case 7:b=[20,11];break;case 8:b=[32,11];break;case 9:b=[80,33];break;case 10:b=[18,11];break;case 11:b=[15,11];break;case 12:b=[64,33];break;case 13:b=[160,99];break;case 14:b=[4,3];break;case 15:b=[3,2];break;case 16:b=[2,1];break;case 255:b=[u()<<8|u(),u()<<8|u()]}return{width:Math.ceil(16*(E+1)-2*a-2*s),height:(2-S)*(k+1)*16-(S?2:4)*(o+l),pixelRatio:b}}}])}(Sa),La=function(e){function t(){var e;a(this,t);for(var r=arguments.length,i=new Array(r),s=0;s<r;s++)i[s]=arguments[s];return(e=n(this,t,[].concat(i))).initVPS=null,e}return d(t,e),o(t,[{key:"parsePES",value:function(e,t,r,i){var n,a=this,s=this.parseNALu(e,r.data,i),o=this.VideoSample,l=!1;r.data=null,o&&s.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),s.forEach(function(i){var s,u;switch(i.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:o||(o=a.VideoSample=a.createVideoSample(!1,r.pts,r.dts)),o.frame=!0,n=!0;break;case 16:case 17:case 18:case 21:var c;if(n=!0,l)null!=(c=o)&&c.frame&&!o.key&&(a.pushAccessUnit(o,e),o=a.VideoSample=null);o||(o=a.VideoSample=a.createVideoSample(!0,r.pts,r.dts)),o.key=!0,o.frame=!0;break;case 19:case 20:n=!0,null!=(s=o)&&s.frame&&!o.key&&(a.pushAccessUnit(o,e),o=a.VideoSample=null),o||(o=a.VideoSample=a.createVideoSample(!0,r.pts,r.dts)),o.key=!0,o.frame=!0;break;case 39:n=!0,ot(i.data,2,r.pts,t.samples);break;case 32:n=!0,e.vps||("object"!==S(e.params)&&(e.params={}),e.params=de(e.params,a.readVPS(i.data)),a.initVPS=i.data),e.vps=[i.data];break;case 33:if(n=!0,l=!0,void 0===e.vps||e.vps[0]===a.initVPS||void 0===e.sps||a.matchSPS(e.sps[0],i.data)||(a.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){var d=a.readSPS(i.data);for(var h in e.width=d.width,e.height=d.height,e.pixelRatio=d.pixelRatio,e.codec=d.codecString,e.sps=[],"object"!==S(e.params)&&(e.params={}),d.params)e.params[h]=d.params[h]}a.pushParameterSet(e.sps,i.data,e.vps),o||(o=a.VideoSample=a.createVideoSample(!0,r.pts,r.dts)),o.key=!0;break;case 34:if(n=!0,"object"===S(e.params)){if(!e.pps){e.pps=[];var f=a.readPPS(i.data);for(var v in f)e.params[v]=f[v]}a.pushParameterSet(e.pps,i.data,e.vps)}break;case 35:n=!0,e.audFound=!0,null!=(u=o)&&u.frame&&(a.pushAccessUnit(o,e),o=null),o||(o=a.VideoSample=a.createVideoSample(!1,r.pts,r.dts));break;default:n=!1}o&&n&&o.units.push(i)}),i&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}},{key:"pushParameterSet",value:function(e,t,r){(r&&r[0]===this.initVPS||!r&&!e.length)&&e.push(t)}},{key:"getNALuType",value:function(e,t){return(126&e[t])>>>1}},{key:"ebsp2rbsp",value:function(e){for(var t=new Uint8Array(e.byteLength),r=0,i=0;i<e.byteLength;i++)i>=2&&3===e[i]&&0===e[i-1]&&0===e[i-2]||(t[r]=e[i],r++);return new Uint8Array(t.buffer,0,r)}},{key:"pushAccessUnit",value:function(e,r){T(t,"pushAccessUnit",this,3)([e,r]),this.initVPS&&(this.initVPS=null)}},{key:"readVPS",value:function(e){var t=new ba(e);return t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6),{numTemporalLayers:t.readBits(3)+1,temporalIdNested:t.readBoolean()}}},{key:"readSPS",value:function(e){var t=new ba(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);var r=t.readBits(3);t.readBoolean();for(var i=t.readBits(2),n=t.readBoolean(),a=t.readBits(5),s=t.readUByte(),o=t.readUByte(),l=t.readUByte(),u=t.readUByte(),c=t.readUByte(),d=t.readUByte(),h=t.readUByte(),f=t.readUByte(),v=t.readUByte(),g=t.readUByte(),p=t.readUByte(),m=[],y=[],T=0;T<r;T++)m.push(t.readBoolean()),y.push(t.readBoolean());if(r>0)for(var E=r;E<8;E++)t.readBits(2);for(var k=0;k<r;k++)m[k]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),y[k]&&t.readUByte();t.readUEG();var S=t.readUEG();3==S&&t.skipBits(1);var b=t.readUEG(),A=t.readUEG(),L=t.readBoolean(),R=0,I=0,w=0,P=0;L&&(R+=t.readUEG(),I+=t.readUEG(),w+=t.readUEG(),P+=t.readUEG());for(var D=t.readUEG(),x=t.readUEG(),C=t.readUEG(),_=t.readBoolean()?0:r;_<=r;_++)t.skipUEG(),t.skipUEG(),t.skipUEG();if((t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean())&&t.readBoolean())for(var M=0;M<4;M++)for(var O=0;O<(3===M?2:6);O++){if(t.readBoolean()){var F=Math.min(64,1<<4+(M<<1));M>1&&t.readEG();for(var U=0;U<F;U++)t.readEG()}else t.readUEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());for(var N=t.readUEG(),B=0,V=0;V<N;V++){var G=!1;if(0!==V&&(G=t.readBoolean()),G){V===N&&t.readUEG(),t.readBoolean(),t.readUEG();for(var H=0,K=0;K<=B;K++){var j=t.readBoolean(),q=!1;j||(q=t.readBoolean()),(j||q)&&H++}B=H}else{var W=t.readUEG(),Y=t.readUEG();B=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<C+4;J++)t.readBits(1);t.readBits(1)}var Z=0,ee=1,te=1,re=!0,ie=1,ne=0;t.readBoolean(),t.readBoolean();if(t.readBoolean()){if(t.readBoolean()){var ae=t.readUByte();ae>0&&ae<16?(ee=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][ae-1],te=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][ae-1]):255===ae&&(ee=t.readBits(16),te=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean())t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte());if(t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean())if(ie=t.readBits(32),ne=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean()){var se=t.readBoolean(),oe=t.readBoolean(),le=!1;(se||oe)&&((le=t.readBoolean())&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),le&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(var ue=0;ue<=r;ue++){var ce=!1;(re=t.readBoolean())||t.readBoolean()?t.readEG():ce=t.readBoolean();var de=ce?1:t.readUEG()+1;if(se)for(var he=0;he<de;he++)t.readUEG(),t.readUEG(),le&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(oe)for(var fe=0;fe<de;fe++)t.readUEG(),t.readUEG(),le&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),Z=t.readUEG())}var ve=b,ge=A;if(L){var pe=1,me=1;1===S?pe=me=2:2==S&&(pe=2),ve=b-pe*I-pe*R,ge=A-me*P-me*w}for(var ye=i?["A","B","C"][i]:"",Te=s<<24|o<<16|l<<8|u,Ee=0,ke=0;ke<32;ke++)Ee=(Ee|(Te>>ke&1)<<31-ke)>>>0;var Se=Ee.toString(16);1===a&&"2"===Se&&(Se="6");var be=n?"H":"L";return{codecString:"hvc1.".concat(ye).concat(a,".").concat(Se,".").concat(be).concat(p,".B0"),params:{general_tier_flag:n,general_profile_idc:a,general_profile_space:i,general_profile_compatibility_flags:[s,o,l,u],general_constraint_indicator_flags:[c,d,h,f,v,g],general_level_idc:p,bit_depth:D+8,bit_depth_luma_minus8:D,bit_depth_chroma_minus8:x,min_spatial_segmentation_idc:Z,chroma_format_idc:S,frame_rate:{fixed:re,fps:ne/ie}},width:ve,height:ge,pixelRatio:[ee,te]}}},{key:"readPPS",value:function(e){var t=new ba(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);var r=t.readBoolean(),i=t.readBoolean(),n=1;return i&&r?n=0:i?n=3:r&&(n=2),{parallelismType:n}}},{key:"matchSPS",value:function(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}])}(Sa),Ra=188,Ia=function(){function e(t,r,i,n){a(this,e),this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=t,this.config=r,this.typeSupported=i,this.logger=n,this.videoParser=null}return o(e,[{key:"resetInitSegment",value:function(t,r,i,n){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=e.createTrack("video"),this._videoTrack.duration=n,this._audioTrack=e.createTrack("audio",n),this._id3Track=e.createTrack("id3"),this._txtTrack=e.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=r,this.videoCodec=i}},{key:"resetTimeStamp",value:function(){}},{key:"resetContiguity",value:function(){var e=this._audioTrack,t=this._videoTrack,r=this._id3Track;e&&(e.pesData=null),t&&(t.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.remainderData=null}},{key:"demux",value:function(t,r){var i,n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],a=arguments.length>3&&void 0!==arguments[3]&&arguments[3];n||(this.sampleAes=null);var s=this._videoTrack,o=this._audioTrack,l=this._id3Track,u=this._txtTrack,c=s.pid,d=s.pesData,h=o.pid,f=l.pid,v=o.pesData,g=l.pesData,p=null,m=this.pmtParsed,y=this._pmtId,T=t.length;if(this.remainderData&&(T=(t=it(this.remainderData,t)).length,this.remainderData=null),T<Ra&&!a)return this.remainderData=t,{audioTrack:o,videoTrack:s,id3Track:l,textTrack:u};var E=Math.max(0,e.syncOffset(t));(T-=(T-E)%Ra)<t.byteLength&&!a&&(this.remainderData=new Uint8Array(t.buffer,T,t.buffer.byteLength-T));for(var k=0,S=E;S<T;S+=Ra)if(71===t[S]){var b=!!(64&t[S+1]),A=wa(t,S),L=void 0;if((48&t[S+3])>>4>1){if((L=S+5+t[S+4])===S+Ra)continue}else L=S+4;switch(A){case c:b&&(d&&(i=_a(d,this.logger))&&(this.readyVideoParser(s.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(s,u,i,!1)),d={data:[],size:0}),d&&(d.data.push(t.subarray(L,S+Ra)),d.size+=S+Ra-L);break;case h:if(b){if(v&&(i=_a(v,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,i);break;case"mp3":this.parseMPEGPES(o,i);break;case"ac3":this.parseAC3PES(o,i)}v={data:[],size:0}}v&&(v.data.push(t.subarray(L,S+Ra)),v.size+=S+Ra-L);break;case f:b&&(g&&(i=_a(g,this.logger))&&this.parseID3PES(l,i),g={data:[],size:0}),g&&(g.data.push(t.subarray(L,S+Ra)),g.size+=S+Ra-L);break;case 0:b&&(L+=t[L]+1),y=this._pmtId=Pa(t,L);break;case y:b&&(L+=t[L]+1);var R=Da(t,L,this.typeSupported,n,this.observer,this.logger);(c=R.videoPid)>0&&(s.pid=c,s.segmentCodec=R.segmentVideoCodec),(h=R.audioPid)>0&&(o.pid=h,o.segmentCodec=R.segmentAudioCodec),(f=R.id3Pid)>0&&(l.pid=f),null===p||m||(this.logger.warn("MPEG-TS PMT found at ".concat(S," after unknown PID '").concat(p,"'. Backtracking to sync byte @").concat(E," to parse all TS packets.")),p=null,S=E-188),m=this.pmtParsed=!0;break;case 17:case 8191:break;default:p=A}}else k++;k>0&&xa(this.observer,new Error("Found ".concat(k," TS packet/s that do not start with 0x47")),void 0,this.logger),s.pesData=d,o.pesData=v,l.pesData=g;var I={audioTrack:o,videoTrack:s,id3Track:l,textTrack:u};return a&&this.extractRemainingSamples(I),I}},{key:"flush",value:function(){var e,t=this.remainderData;return this.remainderData=null,e=t?this.demux(t,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(e),this.sampleAes?this.decrypt(e,this.sampleAes):e}},{key:"extractRemainingSamples",value:function(e){var t,r=e.audioTrack,i=e.videoTrack,n=e.id3Track,a=e.textTrack,s=i.pesData,o=r.pesData,l=n.pesData;if(s&&(t=_a(s,this.logger))?(this.readyVideoParser(i.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(i,a,t,!0),i.pesData=null)):i.pesData=s,o&&(t=_a(o,this.logger))){switch(r.segmentCodec){case"aac":this.parseAACPES(r,t);break;case"mp3":this.parseMPEGPES(r,t);break;case"ac3":this.parseAC3PES(r,t)}r.pesData=null}else null!=o&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),r.pesData=o;l&&(t=_a(l,this.logger))?(this.parseID3PES(n,t),n.pesData=null):n.pesData=l}},{key:"demuxSampleAes",value:function(e,t,r){var i=this.demux(e,r,!0,!this.config.progressive),n=this.sampleAes=new ka(this.observer,this.config,t);return this.decrypt(i,n)}},{key:"readyVideoParser",value:function(e){null===this.videoParser&&("avc"===e?this.videoParser=new Aa:"hevc"===e&&(this.videoParser=new La))}},{key:"decrypt",value:function(e,t){return new Promise(function(r){var i=e.audioTrack,n=e.videoTrack;i.samples&&"aac"===i.segmentCodec?t.decryptAacSamples(i.samples,0,function(){n.samples?t.decryptAvcSamples(n.samples,0,0,function(){r(e)}):r(e)}):n.samples&&t.decryptAvcSamples(n.samples,0,0,function(){r(e)})})}},{key:"destroy",value:function(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}},{key:"parseAACPES",value:function(e,t){var r,i,n,a=0,s=this.aacOverFlow,o=t.data;if(s){this.aacOverFlow=null;var l=s.missing,u=s.sample.unit.byteLength;if(-1===l)o=it(s.sample.unit,o);else{var c=u-l;s.sample.unit.set(o.subarray(0,l),c),e.samples.push(s.sample),a=s.missing}}for(r=a,i=o.length;r<i-1&&!Bn(o,r);r++);if(r!==a){var d,h=r<i-1;if(d=h?"AAC PES did not start with ADTS header,offset:".concat(r):"No ADTS header found in AAC PES",xa(this.observer,new Error(d),h,this.logger),!h)return}if(Gn(e,this.observer,o,r,this.audioCodec),void 0!==t.pts)n=t.pts;else{if(!s)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");var f=Hn(e.samplerate);n=s.sample.pts+f}for(var v,g=0;r<i;){if(r+=(v=Kn(e,o,r,n,g)).length,v.missing){this.aacOverFlow=v;break}for(g++;r<i-1&&!Bn(o,r);r++);}}},{key:"parseMPEGPES",value:function(e,t){var r=t.data,i=r.length,n=0,a=0,s=t.pts;if(void 0!==s)for(;a<i;)if(da(r,a)){var o=la(e,r,a,s,n);if(!o)break;a+=o.length,n++}else a++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}},{key:"parseAC3PES",value:function(e,t){var r=t.data,i=t.pts;if(void 0!==i)for(var n,a=r.length,s=0,o=0;o<a&&(n=pa(e,r,o,i,s++))>0;)o+=n;else this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS")}},{key:"parseID3PES",value:function(e,t){if(void 0!==t.pts){var r=de({},t,{type:this._videoTrack?Zn.emsg:Zn.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(r)}else this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS")}}],[{key:"probe",value:function(t,r){var i=e.syncOffset(t);return i>0&&r.warn("MPEG2-TS detected but first sync word found @ offset ".concat(i)),-1!==i}},{key:"syncOffset",value:function(e){for(var t=e.length,r=Math.min(940,t-Ra)+1,i=0;i<r;){for(var n=!1,a=-1,s=0,o=i;o<t;o+=Ra){if(71!==e[o]||t-o!==Ra&&71!==e[o+Ra]){if(s)return-1;break}if(s++,-1===a&&0!==(a=o)&&(r=Math.min(a+18612,e.length-Ra)+1),n||(n=0===wa(e,o)),n&&s>1&&(0===a&&s>2||o+Ra>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:Ge[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}}])}();function wa(e,t){return((31&e[t+1])<<8)+e[t+2]}function Pa(e,t){return(31&e[t+10])<<8|e[t+11]}function Da(e,t,r,i,n,a){var s={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t<o;){var l=wa(e,t),u=(15&e[t+3])<<8|e[t+4];switch(e[t]){case 207:if(!i){Ca("ADTS AAC",a);break}case 15:-1===s.audioPid&&(s.audioPid=l);break;case 21:-1===s.id3Pid&&(s.id3Pid=l);break;case 219:if(!i){Ca("H.264",a);break}case 27:-1===s.videoPid&&(s.videoPid=l);break;case 3:case 4:r.mpeg||r.mp3?-1===s.audioPid&&(s.audioPid=l,s.segmentAudioCodec="mp3"):a.log("MPEG audio found, not supported in this browser");break;case 193:if(!i){Ca("AC-3",a);break}case 129:r.ac3?-1===s.audioPid&&(s.audioPid=l,s.segmentAudioCodec="ac3"):a.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===s.audioPid&&u>0)for(var c=t+5,d=u;d>2;){if(106===e[c])!0!==r.ac3?a.log("AC-3 audio found, not supported in this browser for now"):(s.audioPid=l,s.segmentAudioCodec="ac3");var h=e[c+1]+2;c+=h,d-=h}break;case 194:case 135:return xa(n,new Error("Unsupported EC-3 in M2TS found"),void 0,a),s;case 36:-1===s.videoPid&&(s.videoPid=l,s.segmentVideoCodec="hevc",a.log("HEVC in M2TS found"))}t+=u+5}return s}function xa(e,t,r,i){i.warn("parsing error: ".concat(t.message)),e.emit(ee.ERROR,ee.ERROR,{type:J.MEDIA_ERROR,details:Z.FRAG_PARSING_ERROR,fatal:!1,levelRetry:r,error:t,reason:t.message})}function Ca(e,t){t.log("".concat(e," with AES-128-CBC encryption found in unencrypted stream"))}function _a(e,t){var r,i,n,a,s,o=0,l=e.data;if(!e||0===e.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=it(l[0],l[1]),l.splice(1,1);if(1===((r=l[0])[0]<<16)+(r[1]<<8)+r[2]){if((i=(r[4]<<8)+r[5])&&i>e.size-6)return null;var u=r[7];192&u&&(a=536870912*(14&r[9])+4194304*(255&r[10])+16384*(254&r[11])+128*(255&r[12])+(254&r[13])/2,64&u?a-(s=536870912*(14&r[14])+4194304*(255&r[15])+16384*(254&r[16])+128*(255&r[17])+(254&r[18])/2)>54e5&&(t.warn("".concat(Math.round((a-s)/9e4),"s delta between PTS and DTS, align them")),a=s):s=a);var c=(n=r[8])+9;if(e.size<=c)return null;e.size-=c;for(var d=new Uint8Array(e.size),h=0,f=l.length;h<f;h++){var v=(r=l[h]).byteLength;if(c){if(c>v){c-=v;continue}r=r.subarray(c),v-=c,c=0}d.set(r,o),o+=v}return i&&(i-=n+3),{data:d,pts:a,dts:s,len:i}}return null}var Ma=function(){return o(function e(){a(this,e)},null,[{key:"getSilentFrame",value:function(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}}])}(),Oa=Math.pow(2,32)-1,Fa=function(){function e(){a(this,e)}return o(e,null,[{key:"init",value:function(){var t;for(t in e.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},e.types)e.types.hasOwnProperty(t)&&(e.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);var r=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),i=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);e.HDLR_TYPES={video:r,audio:i};var n=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),a=new Uint8Array([0,0,0,0,0,0,0,0]);e.STTS=e.STSC=e.STCO=a,e.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),e.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),e.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),e.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);var s=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);e.FTYP=e.box(e.types.ftyp,s,l,s,o),e.DINF=e.box(e.types.dinf,e.box(e.types.dref,n))}},{key:"box",value:function(e){for(var t=8,r=arguments.length,i=new Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];for(var a=i.length,s=a;a--;)t+=i[a].byteLength;var o=new Uint8Array(t);for(o[0]=t>>24&255,o[1]=t>>16&255,o[2]=t>>8&255,o[3]=255&t,o.set(e,4),a=0,t=8;a<s;a++)o.set(i[a],t),t+=i[a].byteLength;return o}},{key:"hdlr",value:function(t){return e.box(e.types.hdlr,e.HDLR_TYPES[t])}},{key:"mdat",value:function(t){return e.box(e.types.mdat,t)}},{key:"mdhd",value:function(t,r){r*=t;var i=Math.floor(r/(Oa+1)),n=Math.floor(r%(Oa+1));return e.box(e.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n,85,196,0,0]))}},{key:"mdia",value:function(t){return e.box(e.types.mdia,e.mdhd(t.timescale||0,t.duration||0),e.hdlr(t.type),e.minf(t))}},{key:"mfhd",value:function(t){return e.box(e.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}},{key:"minf",value:function(t){return"audio"===t.type?e.box(e.types.minf,e.box(e.types.smhd,e.SMHD),e.DINF,e.stbl(t)):e.box(e.types.minf,e.box(e.types.vmhd,e.VMHD),e.DINF,e.stbl(t))}},{key:"moof",value:function(t,r,i){return e.box(e.types.moof,e.mfhd(t),e.traf(i,r))}},{key:"moov",value:function(t){for(var r=t.length,i=[];r--;)i[r]=e.trak(t[r]);return e.box.apply(null,[e.types.moov,e.mvhd(t[0].timescale||0,t[0].duration||0)].concat(i).concat(e.mvex(t)))}},{key:"mvex",value:function(t){for(var r=t.length,i=[];r--;)i[r]=e.trex(t[r]);return e.box.apply(null,[e.types.mvex].concat(i))}},{key:"mvhd",value:function(t,r){r*=t;var i=Math.floor(r/(Oa+1)),n=Math.floor(r%(Oa+1)),a=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return e.box(e.types.mvhd,a)}},{key:"sdtp",value:function(t){var r,i,n=t.samples||[],a=new Uint8Array(4+n.length);for(r=0;r<n.length;r++)i=n[r].flags,a[r+4]=i.dependsOn<<4|i.isDependedOn<<2|i.hasRedundancy;return e.box(e.types.sdtp,a)}},{key:"stbl",value:function(t){return e.box(e.types.stbl,e.stsd(t),e.box(e.types.stts,e.STTS),e.box(e.types.stsc,e.STSC),e.box(e.types.stsz,e.STSZ),e.box(e.types.stco,e.STCO))}},{key:"avc1",value:function(t){var r,i,n,a=[],s=[];for(r=0;r<t.sps.length;r++)n=(i=t.sps[r]).byteLength,a.push(n>>>8&255),a.push(255&n),a=a.concat(Array.prototype.slice.call(i));for(r=0;r<t.pps.length;r++)n=(i=t.pps[r]).byteLength,s.push(n>>>8&255),s.push(255&n),s=s.concat(Array.prototype.slice.call(i));var o=e.box(e.types.avcC,new Uint8Array([1,a[3],a[4],a[5],255,224|t.sps.length].concat(a).concat([t.pps.length]).concat(s))),l=t.width,u=t.height,c=t.pixelRatio[0],d=t.pixelRatio[1];return e.box(e.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,255&l,u>>8&255,255&u,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,e.box(e.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(e.types.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,255&c,d>>24,d>>16&255,d>>8&255,255&d])))}},{key:"esds",value:function(e){var t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2].concat(E(t),[6,1,2]))}},{key:"audioStsd",value:function(e){var t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,255&t,0,0])}},{key:"mp4a",value:function(t){return e.box(e.types.mp4a,e.audioStsd(t),e.box(e.types.esds,e.esds(t)))}},{key:"mp3",value:function(t){return e.box(e.types[".mp3"],e.audioStsd(t))}},{key:"ac3",value:function(t){return e.box(e.types["ac-3"],e.audioStsd(t),e.box(e.types.dac3,t.config))}},{key:"stsd",value:function(t){var r=t.segmentCodec;if("audio"===t.type){if("aac"===r)return e.box(e.types.stsd,e.STSD,e.mp4a(t));if("ac3"===r&&t.config)return e.box(e.types.stsd,e.STSD,e.ac3(t));if("mp3"===r&&"mp3"===t.codec)return e.box(e.types.stsd,e.STSD,e.mp3(t))}else{if(!t.pps||!t.sps)throw new Error("video track missing pps or sps");if("avc"===r)return e.box(e.types.stsd,e.STSD,e.avc1(t));if("hevc"===r&&t.vps)return e.box(e.types.stsd,e.STSD,e.hvc1(t))}throw new Error("unsupported ".concat(t.type," segment codec (").concat(r,"/").concat(t.codec,")"))}},{key:"tkhd",value:function(t){var r=t.id,i=(t.duration||0)*(t.timescale||0),n=t.width||0,a=t.height||0,s=Math.floor(i/(Oa+1)),o=Math.floor(i%(Oa+1));return e.box(e.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,r>>24&255,r>>16&255,r>>8&255,255&r,0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,o>>24,o>>16&255,o>>8&255,255&o,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,n>>8&255,255&n,0,0,a>>8&255,255&a,0,0]))}},{key:"traf",value:function(t,r){var i=e.sdtp(t),n=t.id,a=Math.floor(r/(Oa+1)),s=Math.floor(r%(Oa+1));return e.box(e.types.traf,e.box(e.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n])),e.box(e.types.tfdt,new Uint8Array([1,0,0,0,a>>24,a>>16&255,a>>8&255,255&a,s>>24,s>>16&255,s>>8&255,255&s])),e.trun(t,i.length+16+20+8+16+8+8),i)}},{key:"trak",value:function(t){return t.duration=t.duration||4294967295,e.box(e.types.trak,e.tkhd(t),e.mdia(t))}},{key:"trex",value:function(t){var r=t.id;return e.box(e.types.trex,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}},{key:"trun",value:function(t,r){var i,n,a,s,o,l,u=t.samples||[],c=u.length,d=12+16*c,h=new Uint8Array(d);for(r+=8+d,h.set(["video"===t.type?1:0,0,15,1,c>>>24&255,c>>>16&255,c>>>8&255,255&c,r>>>24&255,r>>>16&255,r>>>8&255,255&r],0),i=0;i<c;i++)a=(n=u[i]).duration,s=n.size,o=n.flags,l=n.cts,h.set([a>>>24&255,a>>>16&255,a>>>8&255,255&a,s>>>24&255,s>>>16&255,s>>>8&255,255&s,o.isLeading<<2|o.dependsOn,o.isDependedOn<<6|o.hasRedundancy<<4|o.paddingValue<<1|o.isNonSync,61440&o.degradPrio,15&o.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*i);return e.box(e.types.trun,h)}},{key:"initSegment",value:function(t){e.types||e.init();var r=e.moov(t);return it(e.FTYP,r)}},{key:"hvc1",value:function(t){for(var r=t.params,i=[t.vps,t.sps,t.pps],n=new Uint8Array([1,r.general_profile_space<<6|(r.general_tier_flag?32:0)|r.general_profile_idc,r.general_profile_compatibility_flags[0],r.general_profile_compatibility_flags[1],r.general_profile_compatibility_flags[2],r.general_profile_compatibility_flags[3],r.general_constraint_indicator_flags[0],r.general_constraint_indicator_flags[1],r.general_constraint_indicator_flags[2],r.general_constraint_indicator_flags[3],r.general_constraint_indicator_flags[4],r.general_constraint_indicator_flags[5],r.general_level_idc,240|r.min_spatial_segmentation_idc>>8,255&r.min_spatial_segmentation_idc,252|r.parallelismType,252|r.chroma_format_idc,248|r.bit_depth_luma_minus8,248|r.bit_depth_chroma_minus8,0,parseInt(r.frame_rate.fps),3|r.temporal_id_nested<<2|r.num_temporal_layers<<3|(r.frame_rate.fixed?64:0),i.length]),a=n.length,s=0;s<i.length;s+=1){a+=3;for(var o=0;o<i[s].length;o+=1)a+=2+i[s][o].length}var l=new Uint8Array(a);l.set(n,0),a=n.length;for(var u=i.length-1,c=0;c<i.length;c+=1){l.set(new Uint8Array([32+c|(c===u?128:0),0,i[c].length]),a),a+=3;for(var d=0;d<i[c].length;d+=1)l.set(new Uint8Array([i[c][d].length>>8,255&i[c][d].length]),a),a+=2,l.set(i[c][d],a),a+=i[c][d].length}var h=e.box(e.types.hvcC,l),f=t.width,v=t.height,g=t.pixelRatio[0],p=t.pixelRatio[1];return e.box(e.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,f>>8&255,255&f,v>>8&255,255&v,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),h,e.box(e.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(e.types.pasp,new Uint8Array([g>>24,g>>16&255,g>>8&255,255&g,p>>24,p>>16&255,p>>8&255,255&p])))}}])}();Fa.types=void 0,Fa.HDLR_TYPES=void 0,Fa.STTS=void 0,Fa.STSC=void 0,Fa.STCO=void 0,Fa.STSZ=void 0,Fa.VMHD=void 0,Fa.SMHD=void 0,Fa.STSD=void 0,Fa.FTYP=void 0,Fa.DINF=void 0;function Ua(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 Na(e){return Ua(e,1e3,1/9e4,arguments.length>1&&void 0!==arguments[1]&&arguments[1])}function Ba(e){var t=e.baseTime,r=e.timescale,i=e.trackId;return"".concat(t/r," (").concat(t,"/").concat(r,") trackId: ").concat(i)}var Va=null,Ga=null;function Ha(e,t,r,i){return{duration:t,size:r,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}var Ka=function(e){function t(e,r,i,s){var o;if(a(this,t),(o=n(this,t,["mp4-remuxer",s])).observer=void 0,o.config=void 0,o.typeSupported=void 0,o.ISGenerated=!1,o._initPTS=null,o._initDTS=null,o.nextVideoTs=null,o.nextAudioTs=null,o.videoSampleDuration=null,o.isAudioContiguous=!1,o.isVideoContiguous=!1,o.videoTrackConfig=void 0,o.observer=e,o.config=r,o.typeSupported=i,o.ISGenerated=!1,null===Va){var l=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Va=l?parseInt(l[1]):0}if(null===Ga){var u=navigator.userAgent.match(/Safari\/(\d+)/i);Ga=u?parseInt(u[1]):0}return o}return d(t,e),o(t,[{key:"destroy",value:function(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}},{key:"resetTimeStamp",value:function(e){var t=this._initPTS;t&&e&&e.trackId===t.trackId&&e.baseTime===t.baseTime&&e.timescale===t.timescale||this.log("Reset initPTS: ".concat(t?Ba(t):t," > ").concat(e?Ba(e):e)),this._initPTS=this._initDTS=e}},{key:"resetNextTimestamp",value:function(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}},{key:"resetInitSegment",value:function(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}},{key:"getVideoStartPts",value:function(e){var t=!1,r=e[0].pts,i=e.reduce(function(e,i){var n=i.pts,a=n-e;return a<-4294967296&&(t=!0,a=(n=ja(n,r))-e),a>0?e:n},r);return t&&this.debug("PTS rollover detected"),i}},{key:"remux",value:function(e,t,r,i,n,a,s,o){var l,u,c,d,h,f,v=n,g=n,p=e.pid>-1,m=t.pid>-1,y=t.samples.length,T=e.samples.length>0,E=s&&y>0||y>1;if((!p||T)&&(!m||E)||this.ISGenerated||s){if(this.ISGenerated){var k,S,b,A,L=this.videoTrackConfig;(L&&(t.width!==L.width||t.height!==L.height||(null==(k=t.pixelRatio)?void 0:k[0])!==(null==(S=L.pixelRatio)?void 0:S[0])||(null==(b=t.pixelRatio)?void 0:b[1])!==(null==(A=L.pixelRatio)?void 0:A[1]))||!L&&E||null===this.nextAudioTs&&T)&&this.resetInitSegment()}this.ISGenerated||(c=this.generateIS(e,t,n,a));var R,I=this.isVideoContiguous,w=-1;if(E&&(w=function(e){for(var t=0;t<e.length;t++)if(e[t].key)return t;return-1}(t.samples),!I&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,w>0){this.warn("Dropped ".concat(w," out of ").concat(y," video samples due to a missing keyframe"));var P=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(w),t.dropped+=w,R=g+=(t.samples[0].pts-P)/t.inputTimeScale}else-1===w&&(this.warn("No keyframe found out of ".concat(y," video samples")),f=!1);if(this.ISGenerated){if(T&&E){var D=this.getVideoStartPts(t.samples),x=(ja(e.samples[0].pts,D)-D)/t.inputTimeScale;v+=Math.max(0,x),g+=Math.max(0,-x)}if(T){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),c=this.generateIS(e,t,n,a)),u=this.remuxAudio(e,v,this.isAudioContiguous,a,m||E||o===se?g:void 0),E){var C=u?u.endPTS-u.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),c=this.generateIS(e,t,n,a)),l=this.remuxVideo(t,g,I,C)}}else E&&(l=this.remuxVideo(t,g,I,0));l&&(l.firstKeyFrame=w,l.independent=-1!==w,l.firstKeyFramePTS=R)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(h=qa(r,n,this._initPTS,this._initDTS)),i.samples.length&&(d=Wa(i,n,this._initPTS))),{audio:u,video:l,initSegment:c,independent:f,text:d,id3:h}}},{key:"computeInitPts",value:function(e,t,r,i){var n=Math.round(r*t),a=ja(e,n);if(a<n+t)for(this.log("Adjusting PTS for rollover in timeline near ".concat((n-a)/t," ").concat(i));a<n+t;)a+=8589934592;return a-n}},{key:"generateIS",value:function(e,t,r,i){var n,a,s,o=e.samples,l=t.samples,u=this.typeSupported,c={},d=this._initPTS,h=!d||i,f="audio/mp4",v=-1;if(h&&(n=a=1/0),e.config&&o.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":u.mpeg?(f="audio/mpeg",e.codec=""):u.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}c.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&u.mpeg?new Uint8Array(0):Fa.initSegment([e]),metadata:{channelCount:e.channelCount}},h&&(v=e.id,s=e.inputTimeScale,d&&s===d.timescale?h=!1:n=a=this.computeInitPts(o[0].pts,s,r,"audio"))}if(t.sps&&t.pps&&l.length){if(t.timescale=t.inputTimeScale,c.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:Fa.initSegment([t]),metadata:{width:t.width,height:t.height}},h)if(v=t.id,s=t.inputTimeScale,d&&s===d.timescale)h=!1;else{var g=this.getVideoStartPts(l),p=ja(l[0].dts,g),m=this.computeInitPts(p,s,r,"video"),y=this.computeInitPts(g,s,r,"video");a=Math.min(a,m),n=Math.min(n,y)}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(c).length)return this.ISGenerated=!0,h?(d&&this.warn("Timestamps at playlist time: ".concat(i?"":"~").concat(r," ").concat(n/s," != initPTS: ").concat(d.baseTime/d.timescale," (").concat(d.baseTime,"/").concat(d.timescale,") trackId: ").concat(d.trackId)),this.log("Found initPTS at playlist time: ".concat(r," offset: ").concat(n/s," (").concat(n,"/").concat(s,") trackId: ").concat(v)),this._initPTS={baseTime:n,timescale:s,trackId:v},this._initDTS={baseTime:a,timescale:s,trackId:v}):n=s=void 0,{tracks:c,initPTS:n,timescale:s,trackId:v}}},{key:"remuxVideo",value:function(e,t,r,i){var n,a,s=e.inputTimeScale,o=e.samples,l=[],u=o.length,c=this._initPTS,d=c.baseTime*s/c.timescale,h=this.nextVideoTs,f=8,v=this.videoSampleDuration,g=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY,m=!1;if(!r||null===h){var y=d+t*s,T=o[0].pts-ja(o[0].dts,o[0].pts);Va&&null!==h&&Math.abs(y-T-(h+d))<15e3?r=!0:h=y-T-d}for(var E=h+d,k=0;k<u;k++){var S=o[k];S.pts=ja(S.pts,E),S.dts=ja(S.dts,E),S.dts<o[k>0?k-1:k].dts&&(m=!0)}m&&o.sort(function(e,t){var r=e.dts-t.dts,i=e.pts-t.pts;return r||i}),n=o[0].dts;var b=(a=o[o.length-1].dts)-n,A=b?Math.round(b/(u-1)):v||e.inputTimeScale/30;if(r){var L=n-E,R=L>A,I=L<-1;if((R||I)&&(R?this.warn("".concat((e.segmentCodec||"").toUpperCase(),": ").concat(Na(L,!0)," ms (").concat(L,"dts) hole between fragments detected at ").concat(t.toFixed(3))):this.warn("".concat((e.segmentCodec||"").toUpperCase(),": ").concat(Na(-L,!0)," ms (").concat(L,"dts) overlapping between fragments detected at ").concat(t.toFixed(3))),!I||E>=o[0].pts||Va)){n=E;var w=o[0].pts-L;if(R)o[0].dts=n,o[0].pts=w;else for(var P=!0,D=0;D<o.length&&!(o[D].dts>w&&P);D++){var x=o[D].pts;if(o[D].dts-=L,o[D].pts-=L,D<o.length-1){var C=o[D+1].pts;P=C<=o[D].pts==C<=x}}this.log("Video: Initial PTS/DTS adjusted: ".concat(Na(w,!0),"/").concat(Na(n,!0),", delta: ").concat(Na(L,!0)," ms"))}}for(var _=0,M=0,O=n=Math.max(0,n),F=0;F<u;F++){for(var U=o[F],N=U.units,B=N.length,V=0,G=0;G<B;G++)V+=N[G].data.length;M+=V,_+=B,U.length=V,U.dts<O?(U.dts=O,O+=A/4|0||1):O=U.dts,g=Math.min(U.pts,g),p=Math.max(U.pts,p)}a=o[u-1].dts;var H,K=M+4*_+8;try{H=new Uint8Array(K)}catch(e){return void this.observer.emit(ee.ERROR,ee.ERROR,{type:J.MUX_ERROR,details:Z.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:K,reason:"fail allocating video mdat ".concat(K)})}var j=new DataView(H.buffer);j.setUint32(0,K),H.set(Fa.types.mdat,4);for(var q=!1,W=Number.POSITIVE_INFINITY,Y=Number.POSITIVE_INFINITY,z=Number.NEGATIVE_INFINITY,X=Number.NEGATIVE_INFINITY,Q=0;Q<u;Q++){for(var $=o[Q],te=$.units,re=0,ie=0,ne=te.length;ie<ne;ie++){var ae=te[ie],se=ae.data,oe=ae.data.byteLength;j.setUint32(f,oe),f+=4,H.set(se,f),f+=oe,re+=4+oe}var le=void 0;if(Q<u-1)v=o[Q+1].dts-$.dts,le=o[Q+1].pts-$.pts;else{var ue=this.config,ce=Q>0?$.dts-o[Q-1].dts:A;if(le=Q>0?$.pts-o[Q-1].pts:A,ue.stretchShortVideoTrack&&null!==this.nextAudioTs){var he=Math.floor(ue.maxBufferHole*s),fe=(i?g+i*s:this.nextAudioTs+d)-$.pts;fe>he?((v=fe-ce)<0?v=ce:q=!0,this.log("It is approximately ".concat(fe/90," ms to the next segment; using duration ").concat(v/90," ms for the last video frame."))):v=ce}else v=ce}var ve=Math.round($.pts-$.dts);W=Math.min(W,v),z=Math.max(z,v),Y=Math.min(Y,le),X=Math.max(X,le),l.push(Ha($.key,v,re,ve))}if(l.length)if(Va){if(Va<70){var ge=l[0].flags;ge.dependsOn=2,ge.isNonSync=0}}else if(Ga&&X-Y<z-W&&A/z<.025&&0===l[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");for(var pe=n,me=0,ye=l.length;me<ye;me++){var Te=pe+l[me].duration,Ee=pe+l[me].cts;if(me<ye-1){var ke=Te+l[me+1].cts;l[me].duration=ke-Ee}else l[me].duration=me?l[me-1].duration:A;l[me].cts=0,pe=Te}}var Se=a+(v=q||!v?A:v);this.nextVideoTs=h=Se-d,this.videoSampleDuration=v,this.isVideoContiguous=!0;var be={data1:Fa.moof(e.sequenceNumber++,n,de(e,{samples:l})),data2:H,startPTS:(g-d)/s,endPTS:(p+v-d)/s,startDTS:(n-d)/s,endDTS:h/s,type:"video",hasAudio:!1,hasVideo:!0,nb:l.length,dropped:e.dropped};return e.samples=[],e.dropped=0,be}},{key:"getSamplesPerFrame",value:function(e){switch(e.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}},{key:"remuxAudio",value:function(e,t,r,i,n){var a=e.inputTimeScale,s=a/(e.samplerate?e.samplerate:a),o=this.getSamplesPerFrame(e),l=o*s,u=this._initPTS,c="mp3"===e.segmentCodec&&this.typeSupported.mpeg,d=[],h=void 0!==n,f=e.samples,v=c?0:8,g=this.nextAudioTs||-1,p=u.baseTime*a/u.timescale,m=p+t*a;if(this.isAudioContiguous=r=r||f.length&&g>0&&(i&&Math.abs(m-(g+p))<9e3||Math.abs(ja(f[0].pts,m)-(g+p))<20*l),f.forEach(function(e){e.pts=ja(e.pts,m)}),!r||g<0){var y=f.length;if(f=f.filter(function(e){return e.pts>=0}),y!==f.length&&this.warn("Removed ".concat(f.length-y," of ").concat(y," samples (initPTS ").concat(p," / ").concat(a,")")),!f.length)return;g=0===n?0:i&&!h?Math.max(0,m-p):f[0].pts-p}if("aac"===e.segmentCodec)for(var T=this.config.maxAudioFramesDrift,E=0,k=g+p;E<f.length;E++){var S=f[E],b=S.pts,A=b-k,L=Math.abs(1e3*A/a);if(A<=-T*l&&h)0===E&&(this.warn("Audio frame @ ".concat((b/a).toFixed(3),"s overlaps marker by ").concat(Math.round(1e3*A/a)," ms.")),this.nextAudioTs=g=b-p,k=b);else if(A>=T*l&&L<1e4&&h){var R=Math.round(A/l);for(k=b-R*l;k<0&&R&&l;)R--,k+=l;0===E&&(this.nextAudioTs=g=k-p),this.warn("Injecting ".concat(R," audio frames @ ").concat(((k-p)/a).toFixed(3),"s due to ").concat(Math.round(1e3*A/a)," ms gap."));for(var I=0;I<R;I++){var w=Ma.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);w||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),w=S.unit.subarray()),f.splice(E,0,{unit:w,pts:k}),k+=l,E++}}S.pts=k,k+=l}for(var P,D=null,x=null,C=0,_=f.length;_--;)C+=f[_].unit.byteLength;for(var M=0,O=f.length;M<O;M++){var F=f[M],U=F.unit,N=F.pts;if(null!==x){d[M-1].duration=Math.round((N-x)/s)}else{if(r&&"aac"===e.segmentCodec&&(N=g+p),D=N,!(C>0))return;C+=v;try{P=new Uint8Array(C)}catch(e){return void this.observer.emit(ee.ERROR,ee.ERROR,{type:J.MUX_ERROR,details:Z.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:C,reason:"fail allocating audio mdat ".concat(C)})}c||(new DataView(P.buffer).setUint32(0,C),P.set(Fa.types.mdat,4))}P.set(U,v);var B=U.byteLength;v+=B,d.push(Ha(!0,o,B,0)),x=N}var V=d.length;if(V){var G=d[d.length-1];g=x-p,this.nextAudioTs=g+s*G.duration;var H=c?new Uint8Array(0):Fa.moof(e.sequenceNumber++,D/s,de({},e,{samples:d}));e.samples=[];var K=(D-p)/a,j=g/a,q={data1:H,data2:P,startPTS:K,endPTS:j,startDTS:K,endDTS:j,type:"audio",hasAudio:!0,hasVideo:!1,nb:V};return this.isAudioContiguous=!0,q}}}])}(ve);function ja(e,t){var r;if(null===t)return e;for(r=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=r;return e}function qa(e,t,r,i){var n=e.samples.length;if(n){for(var a=e.inputTimeScale,s=0;s<n;s++){var o=e.samples[s];o.pts=ja(o.pts-r.baseTime*a/r.timescale,t*a)/a,o.dts=ja(o.dts-i.baseTime*a/i.timescale,t*a)/a}var l=e.samples;return e.samples=[],{samples:l}}}function Wa(e,t,r){var i=e.samples.length;if(i){for(var n=e.inputTimeScale,a=0;a<i;a++){var s=e.samples[a];s.pts=ja(s.pts-r.baseTime*n/r.timescale,t*n)/n}e.samples.sort(function(e,t){return e.pts-t.pts});var o=e.samples;return e.samples=[],{samples:o}}}var Ya,za=function(e){function t(e,r,i,s){var o;return a(this,t),(o=n(this,t,["passthrough-remuxer",s])).emitInitSegment=!1,o.audioCodec=void 0,o.videoCodec=void 0,o.initData=void 0,o.initPTS=null,o.initTracks=void 0,o.lastEndTime=null,o.isVideoContiguous=!1,o}return d(t,e),o(t,[{key:"destroy",value:function(){}},{key:"resetTimeStamp",value:function(e){this.lastEndTime=null;var t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}},{key:"resetNextTimestamp",value:function(){this.isVideoContiguous=!1,this.lastEndTime=null}},{key:"resetInitSegment",value:function(e,t,r,i){this.audioCodec=t,this.videoCodec=r,this.generateInitSegment(e,i),this.emitInitSegment=!0}},{key:"generateInitSegment",value:function(e,t){var r=this.audioCodec,i=this.videoCodec;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);var n=this.initData=Xe(e),a=n.audio,s=n.video;if(t)!function(e,t){if(e&&t){var r=t.keyId;r&&t.isCommonEncryption&&tt(e,function(e,t){var i=e.subarray(8,24);i.some(function(e){return 0!==e})||(Ee.log("[eme] Patching keyId in 'enc".concat(t?"a":"v",">sinf>>tenc' box: ").concat(Ae(i)," -> ").concat(Ae(r))),e.set(r,8))})}}(e,t);else{var o=a||s;null!=o&&o.encrypted&&this.warn('Init segment with encrypted track with has no key ("'.concat(o.codec,'")!'))}a&&(r=Qa(a,xe,this)),s&&(i=Qa(s,Ce,this));var l={};a&&s?l.audiovideo={container:"video/mp4",codec:r+","+i,supplemental:s.supplemental,encrypted:s.encrypted,initSegment:e,id:"main"}:a?l.audio={container:"audio/mp4",codec:r,encrypted:a.encrypted,initSegment:e,id:"audio"}:s?l.video={container:"video/mp4",codec:i,supplemental:s.supplemental,encrypted:s.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=l}},{key:"remux",value:function(e,t,r,i,n,a){var s,o,l=this.initPTS,u=this.lastEndTime,c={audio:void 0,video:void 0,text:i,id3:r,initSegment:void 0};X(u)||(u=this.lastEndTime=n||0);var d=t.samples;if(!d.length)return c;var h={initPTS:void 0,timescale:void 0,trackId:void 0},f=this.initData;if(null!=(s=f)&&s.length||(this.generateInitSegment(d),f=this.initData),null==(o=f)||!o.length)return this.warn("Failed to generate initSegment."),c;this.emitInitSegment&&(h.tracks=this.initTracks,this.emitInitSegment=!1);var v=function(e,t,r){for(var i={},n=Ye(e,["moof","traf"]),a=0;a<n.length;a++){var s=n[a],o=Ye(s,["tfhd"])[0],l=je(o,4),u=t[l];if(u){i[l]||(i[l]={start:NaN,duration:0,sampleCount:0,timescale:u.timescale,type:u.type});var c=i[l],d=Ye(s,["tfdt"])[0];if(d){var h=d[0],f=je(d,4);1===h&&(f===Be?r.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(f*=Be+1,f+=je(d,8))),X(f)&&(!X(c.start)||f<c.start)&&(c.start=f)}var v=u.default,g=je(o,0)|(null==v?void 0:v.flags),p=(null==v?void 0:v.duration)||0;8&g&&(p=je(o,2&g?12:8));for(var m=Ye(s,["trun"]),y=c.start||0,T=0,E=p,k=0;k<m.length;k++){var S=m[k],b=je(S,4),A=c.sampleCount;c.sampleCount+=b;var L=1&S[3],R=4&S[3],I=1&S[2],w=2&S[2],P=4&S[2],D=8&S[2],x=8,C=b;for(L&&(x+=4),R&&b&&(1&S[x+1]||void 0!==c.keyFrameIndex||(c.keyFrameIndex=A),x+=4,I?(E=je(S,x),x+=4):E=p,w&&(x+=4),D&&(x+=4),y+=E,T+=E,C--);C--;)I?(E=je(S,x),x+=4):E=p,w&&(x+=4),P&&(1&S[x+1]||void 0===c.keyFrameIndex&&(c.keyFrameIndex=c.sampleCount-(C+1),c.keyFrameStart=y),x+=4),D&&(x+=4),y+=E,T+=E;!T&&p&&(T+=p*b)}c.duration+=T}}if(!Object.keys(i).some(function(e){return i[e].duration})){for(var _=1/0,M=0,O=Ye(e,["sidx"]),F=0;F<O.length;F++){var U=ze(O[F]);if(null!=U&&U.references){_=Math.min(_,U.earliestPresentationTime/U.timescale);var N=U.references.reduce(function(e,t){return e+t.info.duration||0},0);M=Math.max(M,N+U.earliestPresentationTime/U.timescale)}}M&&X(M)&&Object.keys(i).forEach(function(e){i[e].duration||(i[e].duration=M*i[e].timescale-i[e].start)})}return i}(d,f,this),g=f.audio?v[f.audio.id]:null,p=f.video?v[f.video.id]:null,m=Xa(p,1/0),y=Xa(g,1/0),T=Xa(p,0,!0),E=Xa(g,0,!0),k=n,S=0,b=g&&(!p||!l&&y<m||l&&l.trackId===f.audio.id),A=b?g:p;if(A){var L=A.timescale,R=A.start-n*L,I=b?f.audio.id:f.video.id;k=A.start/L,S=b?E-y:T-m,!a&&l||!function(e,t,r,i){if(null===e)return!0;var n=Math.max(i,1),a=t-e.baseTime/e.timescale;return Math.abs(a-r)>n}(l,k,n,S)&&L===l.timescale||(l&&this.warn("Timestamps at playlist time: ".concat(a?"":"~").concat(n," ").concat(R/L," != initPTS: ").concat(l.baseTime/l.timescale," (").concat(l.baseTime,"/").concat(l.timescale,") trackId: ").concat(l.trackId)),this.log("Found initPTS at playlist time: ".concat(n," offset: ").concat(k-n," (").concat(R,"/").concat(L,") trackId: ").concat(I)),l=null,h.initPTS=R,h.timescale=L,h.trackId=I)}else this.warn("No audio or video samples found for initPTS at playlist time: ".concat(n));l?(h.initPTS=l.baseTime,h.timescale=l.timescale,h.trackId=l.trackId):(h.timescale&&void 0!==h.trackId&&void 0!==h.initPTS||(this.warn("Could not set initPTS"),h.initPTS=k,h.timescale=1,h.trackId=-1),this.initPTS=l={baseTime:h.initPTS,timescale:h.timescale,trackId:h.trackId});var w=k-l.baseTime/l.timescale,P=w+S;S>0?this.lastEndTime=P:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());var D=!!f.audio,x=!!f.video,C="";D&&(C+="audio"),x&&(C+="video");var _={data1:d,startPTS:w,startDTS:w,endPTS:P,endDTS:P,type:C,hasAudio:D,hasVideo:x,nb:1,dropped:0,encrypted:!!f.audio&&f.audio.encrypted||!!f.video&&f.video.encrypted};c.audio=D&&!x?_:void 0,c.video=x?_:void 0;var M=null==p?void 0:p.sampleCount;if(M){var O=p.keyFrameIndex,F=-1!==O;_.nb=M,_.dropped=0===O||this.isVideoContiguous?0:F?O:M,_.independent=F,_.firstKeyFrame=O,F&&p.keyFrameStart&&(_.firstKeyFramePTS=(p.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(c.independent=F),this.isVideoContiguous||(this.isVideoContiguous=F),_.dropped&&this.warn("fmp4 does not start with IDR: firstIDR ".concat(O,"/").concat(M," dropped: ").concat(_.dropped," start: ").concat(_.firstKeyFramePTS||"NA"))}return c.initSegment=h,c.id3=qa(r,n,l,l),i.samples.length&&(c.text=Wa(i,n,l)),c}}])}(ve);function Xa(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return void 0!==(null==e?void 0:e.start)?(e.start+(r?e.duration:0))/e.timescale:t}function Qa(e,t,r){var i=e.codec;if(i&&i.length>4)return i;if(t===xe){if("ec-3"===i||"ac-3"===i||"alac"===i)return i;if("fLaC"===i||"Opus"===i){return kt(i,!1)}return r.warn('Unhandled audio codec "'.concat(i,'" in mp4 MAP')),i||"mp4a"}return r.warn('Unhandled video codec "'.concat(i,'" in mp4 MAP')),i||"avc1"}try{Ya=self.performance.now.bind(self.performance)}catch(e){Ya=Date.now}var $a=[{demux:Ta,remux:za},{demux:Ia,remux:Ka},{demux:fa,remux:Ka},{demux:ma,remux:Ka}];$a.splice(2,0,{demux:ga,remux:Ka});var Ja=function(){return o(function e(t,r,i,n,s,o){a(this,e),this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=t,this.typeSupported=r,this.config=i,this.id=s,this.logger=o},[{key:"configure",value:function(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}},{key:"push",value:function(e,t,r,i){var n=this,a=r.transmuxing;a.executeStart=Ya();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,T=l.duration,E=l.initSegmentData,k=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(k&&ai(k.method)){var S=this.getDecrypter(),b=si(k.method);if(!S.isSync())return this.asyncResult=!0,this.decryptionPromise=S.webCryptoDecrypt(s,k.key.buffer,k.iv.buffer,b).then(function(e){var t=n.push(e,null,r);return n.decryptionPromise=null,t}),this.decryptionPromise;var A=S.softwareDecrypt(s,k.key.buffer,k.iv.buffer,b);if(r.part>-1){var L=S.flush();A=L?L.buffer:L}if(!A)return a.executeEnd=Ya(),Za(r);s=new Uint8Array(A)}var R=this.needsProbing(d,h);if(R){var I=this.configureTransmuxer(s);if(I)return this.logger.warn("[transmuxer] ".concat(I.message)),this.observer.emit(ee.ERROR,ee.ERROR,{type:J.MEDIA_ERROR,details:Z.FRAG_PARSING_ERROR,fatal:!1,error:I,reason:I.message}),a.executeEnd=Ya(),Za(r)}(d||h||g||R)&&this.resetInitSegment(E,p,m,T,t),(d||g||R)&&this.resetInitialTimestamp(y),c||this.resetContiguity();var w=this.transmux(s,k,v,f,r);this.asyncResult=es(w);var P=this.currentTransmuxState;return P.contiguous=!0,P.discontinuity=!1,P.trackSwitch=!1,a.executeEnd=Ya(),w}},{key:"flush",value:function(e){var t=this,r=e.transmuxing;r.executeStart=Ya();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=Ya();var d=[Za(e)];return this.asyncResult?Promise.resolve(d):d}var h=u.flush(o);return es(h)?(this.asyncResult=!0,h.then(function(r){return t.flushRemux(s,r,e),s})):(this.flushRemux(s,h,e),this.asyncResult?Promise.resolve(s):s)}},{key:"flushRemux",value:function(e,t,r){var i=t.audioTrack,n=t.videoTrack,a=t.id3Track,s=t.textTrack,o=this.currentTransmuxState,l=o.accurateTimeOffset,u=o.timeOffset;this.logger.log("[transmuxer.ts]: Flushed ".concat(this.id," sn: ").concat(r.sn).concat(r.part>-1?" part: "+r.part:""," of ").concat(this.id===ae?"level":"track"," ").concat(r.level));var c=this.remuxer.remux(i,n,a,s,u,l,!0,this.id);e.push({remuxResult:c,chunkMeta:r}),r.transmuxing.executeEnd=Ya()}},{key:"resetInitialTimestamp",value:function(e){var t=this.demuxer,r=this.remuxer;t&&r&&(t.resetTimeStamp(e),r.resetTimeStamp(e))}},{key:"resetContiguity",value:function(){var e=this.demuxer,t=this.remuxer;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())}},{key:"resetInitSegment",value:function(e,t,r,i,n){var a=this.demuxer,s=this.remuxer;a&&s&&(a.resetInitSegment(e,t,r,i),s.resetInitSegment(e,t,r,n))}},{key:"destroy",value:function(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}},{key:"transmux",value:function(e,t,r,i,n){return t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,r,i,n):this.transmuxUnencrypted(e,r,i,n)}},{key:"transmuxUnencrypted",value:function(e,t,r,i){var n=this.demuxer.demux(e,t,!1,!this.config.progressive),a=n.audioTrack,s=n.videoTrack,o=n.id3Track,l=n.textTrack;return{remuxResult:this.remuxer.remux(a,s,o,l,t,r,!1,this.id),chunkMeta:i}}},{key:"transmuxSampleAes",value:function(e,t,r,i,n){var a=this;return this.demuxer.demuxSampleAes(e,t,r).then(function(e){return{remuxResult:a.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,r,i,!1,a.id),chunkMeta:n}})}},{key:"configureTransmuxer",value:function(e){for(var t,r=this.config,i=this.observer,n=this.typeSupported,a=0,s=$a.length;a<s;a++){var o;if(null!=(o=$a[a].demux)&&o.probe(e,this.logger)){t=$a[a];break}}if(!t)return new Error("Failed to find demuxer by probing fragment data");var l=this.demuxer,u=this.remuxer,c=t.remux,d=t.demux;u&&u instanceof c||(this.remuxer=new c(i,r,n,this.logger)),l&&l instanceof d||(this.demuxer=new d(i,r,n,this.logger),this.probe=d.probe)}},{key:"needsProbing",value:function(e,t){return!this.demuxer||!this.remuxer||e||t}},{key:"getDecrypter",value:function(){var e=this.decrypter;return e||(e=this.decrypter=new Or(this.config)),e}}])}();var Za=function(e){return{remuxResult:{},chunkMeta:e}};function es(e){return"then"in e&&e.then instanceof Function}var ts=o(function e(t,r,i,n,s){a(this,e),this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=t,this.videoCodec=r,this.initSegmentData=i,this.duration=n,this.defaultInitPts=s||null}),rs=o(function e(t,r,i,n,s,o){a(this,e),this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=t,this.contiguous=r,this.accurateTimeOffset=i,this.trackSwitch=n,this.timeOffset=s,this.initSegmentChange=o}),is=0,ns=function(){return o(function e(t,r,i,n){var s=this;a(this,e),this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=is++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=function(e){var t=e.data,r=s.hls;if(r&&null!=t&&t.event&&t.instanceNo===s.instanceNo)switch(t.event){case"init":var i,n=null==(i=s.workerContext)?void 0:i.objectURL;n&&self.URL.revokeObjectURL(n);break;case"transmuxComplete":s.handleTransmuxComplete(t.data);break;case"flush":s.onFlush(t.data);break;case"workerLog":r.logger[t.data.logType]&&r.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=s.frag,t.data.part=s.part,t.data.id=s.id,r.trigger(t.event,t.data)}},this.onWorkerError=function(e){if(s.hls){var t=new Error("".concat(e.message," (").concat(e.filename,":").concat(e.lineno,")"));s.hls.config.enableWorker=!1,s.hls.logger.warn('Error in "'.concat(s.id,'" Web Worker, fallback to inline')),s.hls.trigger(ee.ERROR,{type:J.OTHER_ERROR,details:Z.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:t})}};var o=t.config;this.hls=t,this.id=r,this.useWorker=!!o.enableWorker,this.onTransmuxComplete=i,this.onFlush=n;var l=function(e,t){(t=t||{}).frag=s.frag||void 0,e===ee.ERROR&&(t.parent=s.id,t.part=s.part,s.error=t.error),s.hls.trigger(e,t)};this.observer=new Pn,this.observer.on(ee.FRAG_DECRYPTED,l),this.observer.on(ee.ERROR,l);var u=Lt(o.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){var c=this.hls.logger;if(o.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{o.workerPath?(c.log("loading Web Worker ".concat(o.workerPath,' for "').concat(r,'"')),this.workerContext=function(e){var t=xn[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 xn[e]=i,i}(o.workerPath)):(c.log('injecting Web Worker for "'.concat(r,'"')),this.workerContext=function(){var e=xn[Dn];if(e)return e.clientCount++,e;var t=new self.Blob(["var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(".concat(__HLS_WORKER_BUNDLE__.toString(),")(true);")],{type:"text/javascript"}),r=self.URL.createObjectURL(t),i={worker:new self.Worker(r),objectURL:r,clientCount:1};return xn[Dn]=i,i}());var d=this.workerContext.worker;d.addEventListener("message",this.onWorkerMessage),d.addEventListener("error",this.onWorkerError),d.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:u,id:r,config:Kt(o)})}catch(e){c.warn('Error setting up "'.concat(r,'" Web Worker, fallback to inline'),e),this.terminateWorker(),this.error=null,this.transmuxer=new Ja(this.observer,u,o,"",r,t.logger)}return}}this.transmuxer=new Ja(this.observer,u,o,"",r,t.logger)},[{key:"reset",value:function(){if(this.frag=null,this.part=null,this.workerContext){var e=this.instanceNo;this.instanceNo=is++;var t=this.hls.config,r=Lt(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:r,id:this.id,config:Kt(t)})}}},{key:"terminateWorker",value:function(){if(this.workerContext){var e=this.workerContext.worker;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),function(e){var t=xn[e||Dn];if(t&&1===t.clientCount--){var r=t.worker,i=t.objectURL;delete xn[e||Dn],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),T=!(m&&l.level===m.level),E=m?l.sn-m.sn:-1,k=this.part?l.part-this.part.index:-1,S=0===E&&l.id>1&&l.id===(null==m?void 0:m.stats.chunkCount),b=!T&&(1===E||0===E&&(1===k||S&&k<=0)),A=self.performance.now();(T||E||0===n.stats.parsing.start)&&(n.stats.parsing.start=A),!a||!k&&b||(a.stats.parsing.start=A);var L=!(m&&(null==(c=n.initSegment)?void 0:c.url)===(null==(d=m.initSegment)?void 0:d.url)),R=new rs(y,b,o,T,g,L);if(!b||y||L){this.hls.logger.log("[transmuxer-interface]: Starting new transmux session for ".concat(n.type," sn: ").concat(l.sn).concat(l.part>-1?" part: "+l.part:""," ").concat(this.id===ae?"level":"track",": ").concat(l.level," id: ").concat(l.id,"\n discontinuity: ").concat(y,"\n trackSwitch: ").concat(T,"\n contiguous: ").concat(b,"\n accurateTimeOffset: ").concat(o,"\n timeOffset: ").concat(g,"\n initSegmentChange: ").concat(L));var I=new ts(r,i,t,s,u);this.configureTransmuxer(I)}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 w=v.push(e,p,l,R);es(w)?w.then(function(e){h.handleTransmuxComplete(e)}).catch(function(e){h.transmuxerError(e,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(w)}}},{key:"flush",value:function(e){var t=this;e.transmuxing.start=self.performance.now();var r=this.instanceNo,i=this.transmuxer;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:r,cmd:"flush",chunkMeta:e});else if(i){var n=i.flush(e);es(n)?n.then(function(r){t.handleFlushResult(r,e)}).catch(function(r){t.transmuxerError(r,e,"transmuxer-interface flush error")}):this.handleFlushResult(n,e)}}},{key:"transmuxerError",value:function(e,t,r){this.hls&&(this.error=e,this.hls.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:r}))}},{key:"handleFlushResult",value:function(e,t){var r=this;e.forEach(function(e){r.handleTransmuxComplete(e)}),this.onFlush(t)}},{key:"configureTransmuxer",value:function(e){var t=this.instanceNo,r=this.transmuxer;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):r&&r.configure(e)}},{key:"handleTransmuxComplete",value:function(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}])}(),as=function(e){function t(e,r,i){var s;return a(this,t),(s=n(this,t,[e,r,i,"audio-stream-controller",se])).mainAnchor=null,s.mainFragLoading=null,s.audioOnly=!1,s.bufferedTrack=null,s.switchingTrack=null,s.trackId=-1,s.waitingData=null,s.mainDetails=null,s.flushing=!1,s.bufferFlushed=!1,s.cachedTrackLoadedData=null,s.registerListeners(),s}return d(t,e),o(t,[{key:"onHandlerDestroying",value:function(){this.unregisterListeners(),T(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(){T(t,"registerListeners",this,3)([]);var e=this.hls;e.on(ee.LEVEL_LOADED,this.onLevelLoaded,this),e.on(ee.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(ee.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(ee.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(ee.BUFFER_RESET,this.onBufferReset,this),e.on(ee.BUFFER_CREATED,this.onBufferCreated,this),e.on(ee.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(ee.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(ee.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(ee.FRAG_LOADING,this.onFragLoading,this),e.on(ee.FRAG_BUFFERED,this.onFragBuffered,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(T(t,"unregisterListeners",this,3)([]),e.off(ee.LEVEL_LOADED,this.onLevelLoaded,this),e.off(ee.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(ee.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(ee.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(ee.BUFFER_RESET,this.onBufferReset,this),e.off(ee.BUFFER_CREATED,this.onBufferCreated,this),e.off(ee.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(ee.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(ee.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(ee.FRAG_LOADING,this.onFragLoading,this),e.off(ee.FRAG_BUFFERED,this.onFragBuffered,this))}},{key:"onInitPtsFound",value:function(e,t){var r=t.frag,i=t.id,n=t.initPTS,a=t.timescale,s=t.trackId;if(i===ae){var o=r.cc,l=this.fragCurrent;if(this.initPTS[o]={baseTime:n,timescale:a,trackId:s},this.log("InitPTS for cc: ".concat(o," found from main: ").concat(n/a," (").concat(n,"/").concat(a,") trackId: ").concat(s)),this.mainAnchor=r,this.state===kn){var u=this.waitingData;(!u&&!this.loadingParts||u&&u.frag.cc!==o)&&this.syncWithAnchor(r,null==u?void 0:u.frag)}else!this.hls.hasEnoughToStart&&l&&l.cc!==o?(l.abortRequests(),this.syncWithAnchor(r,l)):this.state===hn&&this.tick()}}},{key:"getLoadPosition",value:function(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:T(t,"getLoadPosition",this,3)([])}},{key:"syncWithAnchor",value:function(e,t){var r,i=(null==(r=this.mainFragLoading)?void 0:r.frag)||null;if(!t||(null==i?void 0:i.cc)!==t.cc){var n=(i||e).cc,a=ir(this.getLevelDetails(),n,this.getLoadPosition());a&&(this.log("Syncing with main frag at ".concat(a.start," cc ").concat(a.cc)),this.startFragRequested=!1,this.nextLoadPosition=a.start,this.resetLoadingState(),this.state===hn&&this.doTickIdle())}}},{key:"startLoad",value:function(e,t){if(!this.levels)return this.startPosition=e,void(this.state=dn);var r=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),r>0&&-1===e?(this.log("Override startPosition with lastCurrentTime @".concat(r.toFixed(3))),e=r,this.state=hn):this.state=pn,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}},{key:"doTick",value:function(){switch(this.state){case hn:this.doTickIdle();break;case pn:var e=this.levels,r=this.trackId,i=null==e?void 0:e[r],n=null==i?void 0:i.details;if(n&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(n))break;this.state=kn}break;case gn:this.checkRetryDate();break;case kn:var a=this.waitingData;if(a){var s=a.frag,o=a.part,l=a.cache,u=a.complete,c=this.mainAnchor;if(void 0!==this.initPTS[s.cc]){this.waitingData=null,this.state=vn;var d={frag:s,part:o,payload:l.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(d),u&&T(t,"_handleFragmentLoadComplete",this,3)([d])}else c&&c.cc!==a.frag.cc&&this.syncWithAnchor(c,a.frag)}else this.state=hn}this.onTickEnd()}},{key:"resetLoadingState",value:function(){var e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),T(t,"resetLoadingState",this,3)([])}},{key:"onTickEnd",value:function(){var e=this.media;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime)}},{key:"doTickIdle",value:function(){var e,t=this.hls,r=this.levels,i=this.media,n=this.trackId,a=t.config;if(this.buffering&&(i||this.primaryPrefetch||!this.startFragRequested&&a.startFragPrefetch)&&null!=r&&r[n]){var s=r[n],o=s.details;if(!o||this.waitForLive(s)||this.waitForCdnTuneIn(o))return this.state=pn,void(this.startFragRequested=!1);var l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,xe,se));var u=this.getFwdBufferInfo(l,se);if(null!==u){if(!this.switchingTrack&&this._streamEnded(u,o))return t.trigger(ee.BUFFER_EOS,{type:"audio"}),void(this.state=Tn);var c=u.len,d=t.maxBufferLength,h=o.fragments,f=h[0].start,v=this.getLoadPosition(),g=this.flushing?v:u.end;if(this.switchingTrack&&i){var p=v;o.PTSKnown&&p<f&&(u.end>f||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=f+.05)}if(!(c>=d&&!this.switchingTrack&&g<h[h.length-1].start)){var m=this.getNextFragment(g,o);if(m&&this.isLoopLoading(m,g)&&(m=this.getNextFragmentLoopLoading(m,o,u,ae,d)),m){var y=(null==(e=this.mainFragLoading)?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&y&&Oe(m)&&!m.endList&&(!o.live||!this.loadingParts&&g<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(y)===Lr&&(this.mainFragLoading=y=null),y&&Oe(y))){if(m.start>y.end){var T=this.fragmentTracker.getFragAtPos(g,ae);T&&T.end>y.end&&(y=T,this.mainFragLoading={frag:T,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,T(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 Vt(e)})}},{key:"onAudioTrackSwitching",value:function(e,t){var r=!!t.url;this.trackId=t.id;var i=this.fragCurrent;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),r?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==dn&&(this.setInterval(100),this.state=hn,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}},{key:"onManifestLoading",value:function(){T(t,"onManifestLoading",this,3)([]),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}},{key:"onLevelLoaded",value:function(e,t){this.mainDetails=t.details;var r=this.cachedTrackLoadedData;r&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(ee.AUDIO_TRACK_LOADED,r))}},{key:"onAudioTrackLoaded",value:function(e,t){var r,i=this.levels,n=t.details,a=t.id,s=t.groupId,o=t.track;if(i){var l=this.mainDetails;if(!l||n.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=t,void(this.state!==dn&&(this.state=pn));this.cachedTrackLoadedData=null,this.log("Audio track ".concat(a,' "').concat(o.name,'" of "').concat(s,'" loaded [').concat(n.startSN,",").concat(n.endSN,"]").concat(n.lastPartSn?"[part-".concat(n.lastPartSn,"-").concat(n.lastPartIndex,"]"):"",",duration:").concat(n.totalduration));var u=i[a],c=0;if(n.live||null!=(r=u.details)&&r.live){if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;var d;if(u.details)c=this.alignPlaylists(n,u.details,null==(d=this.levelLastLoaded)?void 0:d.details);n.alignedSliding||(sn(n,l),n.alignedSliding||on(n,l),c=n.fragmentStart)}u.details=n,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(l,c),this.hls.trigger(ee.AUDIO_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.state!==pn||this.waitForCdnTuneIn(n)||(this.state=hn),this.tick()}else this.warn("Audio tracks reset while loading track ".concat(a,' "').concat(o.name,'" of "').concat(s,'"'))}},{key:"_handleFragmentLoadProgress",value:function(e){var t,r=e.frag,i=e.part,n=e.payload,a=this.config,s=this.trackId,o=this.levels;if(o){var l=o[s];if(l){var u=l.details;if(!u)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(r.start);var c=a.defaultAudioCodec||l.audioCodec||"mp4a.40.2",d=this.transmuxer;d||(d=this.transmuxer=new ns(this.hls,se,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));var h=this.initPTS[r.cc],f=null==(t=r.initSegment)?void 0:t.data;if(void 0!==h){var v=i?i.index:-1,g=-1!==v,p=new Hr(r.level,r.sn,r.stats.chunkCount,n.byteLength,v,g);d.push(n,f,c,"",r,i,u.totalduration,!1,p,h)}else{this.log("Unknown video PTS for cc ".concat(r.cc,", waiting for video PTS before demuxing audio frag ").concat(r.sn," of [").concat(u.startSN," ,").concat(u.endSN,"],track ").concat(s)),(this.waitingData=this.waitingData||{frag:r,part:i,cache:new Ln,complete:!1}).cache.push(new Uint8Array(n)),this.state!==dn&&(this.state=kn)}}else this.warn("Audio track is undefined on fragment load progress")}else this.warn("Audio tracks were reset while fragment load was in progress. Fragment ".concat(r.sn," of level ").concat(r.level," will not be buffered"))}},{key:"_handleFragmentLoadComplete",value:function(e){this.waitingData?this.waitingData.complete=!0:T(t,"_handleFragmentLoadComplete",this,3)([e])}},{key:"onBufferReset",value:function(){this.mediaBuffer=null}},{key:"onBufferCreated",value:function(e,t){this.bufferFlushed=this.flushing=!1;var r=t.tracks.audio;r&&(this.mediaBuffer=r.buffer||null)}},{key:"onFragLoading",value:function(e,t){!this.audioOnly&&t.frag.type===ae&&Oe(t.frag)&&(this.mainFragLoading=t,this.state===hn&&this.tick())}},{key:"onFragBuffered",value:function(e,t){var r=t.frag,i=t.part;if(r.type===se)if(this.fragContextChanged(r))this.warn("Fragment ".concat(r.sn).concat(i?" p: "+i.index:""," of level ").concat(r.level," finished buffering, but was aborted. state: ").concat(this.state,", audioSwitch: ").concat(this.switchingTrack?this.switchingTrack.name:"false"));else{if(Oe(r)){this.fragPrevious=r;var n=this.switchingTrack;n&&(this.bufferedTrack=n,this.switchingTrack=null,this.hls.trigger(ee.AUDIO_TRACK_SWITCHED,fe({},n)))}this.fragBufferedComplete(r,i),this.media&&this.tick()}else this.audioOnly||r.type!==ae||r.elementaryStreams.video||r.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}},{key:"onError",value:function(e,r){var i;if(r.fatal)this.state=En;else switch(r.details){case Z.FRAG_GAP:case Z.FRAG_PARSING_ERROR:case Z.FRAG_DECRYPT_ERROR:case Z.FRAG_LOAD_ERROR:case Z.FRAG_LOAD_TIMEOUT:case Z.KEY_LOAD_ERROR:case Z.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(se,r);break;case Z.AUDIO_TRACK_LOAD_ERROR:case Z.AUDIO_TRACK_LOAD_TIMEOUT:case Z.LEVEL_PARSING_ERROR:r.levelRetry||this.state!==pn||(null==(i=r.context)?void 0:i.type)!==ie||(this.state=hn);break;case Z.BUFFER_ADD_CODEC_ERROR:case Z.BUFFER_APPEND_ERROR:if("audio"!==r.parent)return;this.reduceLengthAndFlushBuffer(r)||this.resetLoadingState();break;case Z.BUFFER_FULL_ERROR:if("audio"!==r.parent)return;this.reduceLengthAndFlushBuffer(r)&&(this.bufferedTrack=null,T(t,"flushMainBuffer",this,3)([0,Number.POSITIVE_INFINITY,"audio"]));break;case Z.INTERNAL_EXCEPTION:this.recoverWorkerError(r)}}},{key:"onBufferFlushing",value:function(e,t){t.type!==Ce&&(this.flushing=!0)}},{key:"onBufferFlushed",value:function(e,t){var r=t.type;if(r!==Ce){this.flushing=!1,this.bufferFlushed=!0,this.state===Tn&&(this.state=hn);var i=this.mediaBuffer||this.media;i&&(this.afterBufferFlushed(i,r,se),this.tick())}}},{key:"_handleTransmuxComplete",value:function(e){var t,r="audio",i=this.hls,n=e.remuxResult,a=e.chunkMeta,s=this.getCurrentContext(a);if(s){var o=s.frag,l=s.part,u=s.level,c=u.details,d=n.audio,h=n.text,f=n.id3,v=n.initSegment;if(!this.fragContextChanged(o)&&c){if(this.state=mn,this.switchingTrack&&d&&this.completeAudioSwitch(this.switchingTrack),null!=v&&v.tracks){var g=o.initSegment||o;if(this.unhandledEncryptionError(v,o))return;this._bufferInitSegment(u,v.tracks,g,a),i.trigger(ee.FRAG_PARSING_INIT_SEGMENT,{frag:g,id:r,tracks:v.tracks})}if(d){var p=d.startPTS,m=d.endPTS,y=d.startDTS,T=d.endDTS;l&&(l.elementaryStreams[xe]={startPTS:p,endPTS:m,startDTS:y,endDTS:T}),o.setElementaryStreamInfo(xe,p,m,y,T),this.bufferFragmentData(d,o,l,a)}if(null!=f&&null!=(t=f.samples)&&t.length){var E=de({id:r,frag:o,details:c},f);i.trigger(ee.FRAG_PARSING_METADATA,E)}if(h){var k=de({id:r,frag:o,details:c},h);i.trigger(ee.FRAG_PARSING_USERDATA,k)}}else this.fragmentTracker.removeFragment(o)}else this.resetWhenMissingContext(a)}},{key:"_bufferInitSegment",value:function(e,t,r,i){if(this.state===mn&&(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,t.audio)){var n=t.audio;n.id=se;var a=e.audioCodec;this.log("Init audio buffer, container:".concat(n.container,", codecs[level/parsed]=[").concat(a,"/").concat(n.codec,"]")),a&&1===a.split(",").length&&(n.levelCodec=a),this.hls.trigger(ee.BUFFER_CODECS,t);var s=n.initSegment;if(null!=s&&s.byteLength){var o={type:"audio",frag:r,part:null,chunkMeta:i,parent:r.type,data:s};this.hls.trigger(ee.BUFFER_APPENDING,o)}this.tickImmediate()}}},{key:"loadFragment",value:function(e,r,i){var n,a=this.fragmentTracker.getState(e);if(this.switchingTrack||a===Sr||a===Ar)if(Oe(e))if(null!=(n=r.details)&&n.live&&!this.initPTS[e.cc]){this.log("Waiting for video PTS in continuity counter ".concat(e.cc," of live stream before loading audio fragment ").concat(e.sn," of level ").concat(this.trackId)),this.state=kn;var s=this.mainDetails;s&&s.fragmentStart!==r.details.fragmentStart&&on(r.details,s)}else T(t,"loadFragment",this,3)([e,r,i]);else this._loadInitSegment(e,r);else this.clearTrackerIfNeeded(e)}},{key:"flushAudioIfNeeded",value:function(e){if(this.media&&this.bufferedTrack){var r=this.bufferedTrack;zt({name:r.name,lang:r.lang,assocLang:r.assocLang,characteristics:r.characteristics,audioCodec:r.audioCodec,channels:r.channels},e,Xt)||($t(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),T(t,"flushMainBuffer",this,3)([0,Number.POSITIVE_INFINITY,"audio"]),this.bufferedTrack=null):this.bufferedTrack=e)}}},{key:"completeAudioSwitch",value:function(e){var t=this.hls;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(ee.AUDIO_TRACK_SWITCHED,fe({},e))}}])}(bn),ss=function(e){function t(e,r){var i;return a(this,t),(i=n(this,t,[r,e.logger])).hls=void 0,i.canLoad=!1,i.timer=-1,i.hls=e,i}return d(t,e),o(t,[{key:"destroy",value:function(){this.clearTimer(),this.hls=this.log=this.warn=null}},{key:"clearTimer",value:function(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}},{key:"startLoad",value:function(){this.canLoad=!0,this.loadPlaylist()}},{key:"stopLoad",value:function(){this.canLoad=!1,this.clearTimer()}},{key:"switchParams",value:function(e,t,r){var i=null==t?void 0:t.renditionReports;if(i){for(var n=-1,a=0;a<i.length;a++){var s=i[a],o=void 0;try{o=new self.URL(s.URI,t.url).href}catch(e){this.warn("Could not construct new URL for Rendition Report: ".concat(e)),o=s.URI||""}if(o===e){n=a;break}o===e.substring(0,o.length)&&(n=a)}if(-1!==n){var l=i[n],u=parseInt(l["LAST-MSN"])||t.lastPartSn,c=parseInt(l["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){var d=Math.min(t.age-t.partTarget,t.targetduration);c>=0&&d>t.partTarget&&(c+=1)}var h=r&&Nt(r);return new Bt(u,c>=0?c:void 0,h)}}}},{key:"loadPlaylist",value:function(e){this.clearTimer()}},{key:"loadingPlaylist",value:function(e,t){this.clearTimer()}},{key:"shouldLoadPlaylist",value:function(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}},{key:"getUrlWithDirectives",value:function(e,t){if(t)try{return t.addDirectives(e)}catch(e){this.warn("Could not construct new URL with HLS Delivery Directives: ".concat(e))}return e}},{key:"playlistLoaded",value:function(e,t,r){var i=t.details,n=t.stats,a=self.performance.now(),s=n.loading.first?Math.max(0,a-n.loading.first):0;i.advancedDateTime=Date.now()-s;var o=this.hls.config.timelineOffset;if(o!==i.appliedTimelineOffset){var l=Math.max(o||0,0);i.appliedTimelineOffset=l,i.fragments.forEach(function(e){e.setStart(e.playlistOffset+l)})}if(i.live||null!=r&&r.live){var u="levelInfo"in t?t.levelInfo:t.track;if(i.reloaded(r),r&&i.fragments.length>0){qi(r,i,this);var c=i.playlistParsingError;if(c){this.warn(c);var d=this.hls;if(!d.config.ignorePlaylistParsingErrors){var h,f=t.networkDetails;return void d.trigger(ee.ERROR,{type:J.NETWORK_ERROR,details:Z.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:c,reason:c.message,level:t.level||void 0,parent:null==(h=i.fragments[0])?void 0:h.type,networkDetails:f,stats:n})}i.playlistParsingError=null}}-1===i.requestScheduled&&(i.requestScheduled=n.loading.start);var v,g=this.hls.mainForwardBufferInfo,p=g?g.end-g.len:0,m=Xi(i,1e3*(i.edge-p));if(i.requestScheduled+m<a?i.requestScheduled=a:i.requestScheduled+=m,this.log("live playlist ".concat(e," ").concat(i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED")),!this.canLoad||!i.live)return;var y=void 0,T=void 0;if(i.canBlockReload&&i.endSN&&i.advanced){var E=this.hls.config.lowLatencyMode,k=i.lastPartSn,S=i.endSN,b=i.lastPartIndex,A=k===S;-1!==b?A?(y=S+1,T=E?0:b):(y=k,T=E?b+1:i.maxPartIndex):y=S+1;var L=i.age,R=L+i.ageHeader,I=Math.min(R-i.partTarget,1.5*i.targetduration);if(I>0){if(R>3*i.targetduration)this.log("Playlist last advanced ".concat(L.toFixed(2),"s ago. Omitting segment and part directives.")),y=void 0,T=void 0;else if(null!=r&&r.tuneInGoal&&R-i.partTarget>r.tuneInGoal)this.warn("CDN Tune-in goal increased from: ".concat(r.tuneInGoal," to: ").concat(I," with playlist age: ").concat(i.age)),I=0;else{var w=Math.floor(I/i.targetduration);if(y+=w,void 0!==T)T+=Math.round(I%i.targetduration/i.partTarget);this.log("CDN Tune-in age: ".concat(i.ageHeader,"s last advanced ").concat(L.toFixed(2),"s goal: ").concat(I," skip sn ").concat(w," to part ").concat(T))}i.tuneInGoal=I}if(v=this.getDeliveryDirectives(i,t.deliveryDirectives,y,T),E||!A)return i.requestScheduled=a,void this.loadingPlaylist(u,v)}else(i.canBlockReload||i.canSkipUntil)&&(v=this.getDeliveryDirectives(i,t.deliveryDirectives,y,T));v&&void 0!==y&&i.canBlockReload&&(i.requestScheduled=n.loading.first+Math.max(m-2*s,m/2)),this.scheduleLoading(u,v,i)}else this.clearTimer()}},{key:"scheduleLoading",value:function(e,t,r){var i=this,n=r||e.details;if(n){var a=self.performance.now(),s=n.requestScheduled;if(a>=s)this.loadingPlaylist(e,t);else{var o=s-a;this.log("reload live playlist ".concat(e.name||e.bitrate+"bps"," in ").concat(Math.round(o)," ms")),this.clearTimer(),this.timer=self.setTimeout(function(){return i.loadingPlaylist(e,t)},o)}}else this.loadingPlaylist(e,t)}},{key:"getDeliveryDirectives",value:function(e,t,r,i){var n=Nt(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(r=t.msn,i=t.part,n=Ot),new Bt(r,i,n)}},{key:"checkRetry",value:function(e){var t=this,r=e.details,i=nr(e),n=e.errorAction,a=n||{},s=a.action,o=a.retryCount,l=void 0===o?0:o,u=a.retryConfig,c=!!n&&!!u&&(s===gr||!n.resolved&&s===fr);if(c){var d;if(l>=u.maxNumRetry)return!1;if(i&&null!=(d=e.context)&&d.deliveryDirectives)this.warn("Retrying playlist loading ".concat(l+1,"/").concat(u.maxNumRetry,' after "').concat(r,'" without delivery-directives')),this.loadPlaylist();else{var h=lr(u,l);this.clearTimer(),this.timer=self.setTimeout(function(){return t.loadPlaylist()},h),this.warn("Retrying playlist loading ".concat(l+1,"/").concat(u.maxNumRetry,' after "').concat(r,'" in ').concat(h,"ms"))}e.levelRetry=!0,n.resolved=!0}return c}}])}(ve);function os(e,t){if(e.length!==t.length)return!1;for(var r=0;r<e.length;r++)if(!ls(e[r].attrs,t[r].attrs))return!1;return!0}function ls(e,t,r){var i=e["STABLE-RENDITION-ID"];return i&&!r?i===t["STABLE-RENDITION-ID"]:!(r||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(function(r){return e[r]!==t[r]})}function us(e,t){return t.label.toLowerCase()===e.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(e.lang||"").toLowerCase())}var cs=function(e){function t(e){var r;return a(this,t),(r=n(this,t,[e,"audio-track-controller"])).tracks=[],r.groupIds=null,r.tracksInGroup=[],r.trackId=-1,r.currentTrack=null,r.selectDefaultTrack=!0,r.registerListeners(),r}return d(t,e),o(t,[{key:"registerListeners",value:function(){var e=this.hls;e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.MANIFEST_PARSED,this.onManifestParsed,this),e.on(ee.LEVEL_LOADING,this.onLevelLoading,this),e.on(ee.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(ee.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(ee.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.MANIFEST_PARSED,this.onManifestParsed,this),e.off(ee.LEVEL_LOADING,this.onLevelLoading,this),e.off(ee.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(ee.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(ee.ERROR,this.onError,this)}},{key:"destroy",value:function(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,T(t,"destroy",this,3)([])}},{key:"onManifestLoading",value:function(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}},{key:"onManifestParsed",value:function(e,t){this.tracks=t.audioTracks||[]}},{key:"onAudioTrackLoaded",value:function(e,t){var r=t.id,i=t.groupId,n=t.details,a=this.tracksInGroup[r];if(a&&a.groupId===i){var s=a.details;a.details=t.details,this.log("Audio track ".concat(r,' "').concat(a.name,'" lang:').concat(a.lang," group:").concat(i," loaded [").concat(n.startSN,"-").concat(n.endSN,"]")),r===this.trackId&&this.playlistLoaded(r,t,s)}else this.warn("Audio track with id:".concat(r," and group:").concat(i," not found in active group ").concat(null==a?void 0:a.groupId))}},{key:"onLevelLoading",value:function(e,t){this.switchLevel(t.level)}},{key:"onLevelSwitching",value:function(e,t){this.switchLevel(t.level)}},{key:"switchLevel",value:function(e){var t=this.hls.levels[e];if(t){var r=t.audioGroups||null,i=this.groupIds,n=this.currentTrack;if(!r||(null==i?void 0:i.length)!==(null==r?void 0:r.length)||null!=r&&r.some(function(e){return-1===(null==i?void 0:i.indexOf(e))})){this.groupIds=r,this.trackId=-1,this.currentTrack=null;var a=this.tracks.filter(function(e){return!r||-1!==r.indexOf(e.groupId)});if(a.length)this.selectDefaultTrack&&!a.some(function(e){return e.default})&&(this.selectDefaultTrack=!1),a.forEach(function(e,t){e.id=t});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=a;var s=this.hls.config.audioPreference;if(!n&&s){var o=Yt(s,a,Xt);if(o>-1)n=a[o];else{var l=Yt(s,this.tracks);n=this.tracks[l]}}var u=this.findTrackId(n);-1===u&&n&&(u=this.findTrackId(null));var c={audioTracks:a};this.log("Updating audio tracks, ".concat(a.length," track(s) found in group(s): ").concat(null==r?void 0:r.join(","))),this.hls.trigger(ee.AUDIO_TRACKS_UPDATED,c);var d=this.trackId;if(-1!==u&&-1===d)this.setAudioTrack(u);else if(a.length&&-1===d){var h,f=new Error("No audio track selected for current audio group-ID(s): ".concat(null==(h=this.groupIds)?void 0:h.join(",")," track count: ").concat(a.length));this.warn(f.message),this.hls.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:f})}}}}},{key:"onError",value:function(e,t){!t.fatal&&t.context&&(t.context.type!==ie||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))}},{key:"allAudioTracks",get:function(){return this.tracks}},{key:"audioTracks",get:function(){return this.tracksInGroup}},{key:"audioTrack",get:function(){return this.trackId},set:function(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}},{key:"setAudioOption",value:function(e){var t=this.hls;if(t.config.audioPreference=e,e){var r=this.allAudioTracks;if(this.selectDefaultTrack=!1,r.length){var i=this.currentTrack;if(i&&zt(e,i,Xt))return i;var n=Yt(e,this.tracksInGroup,Xt);if(n>-1){var a=this.tracksInGroup[n];return this.setAudioTrack(n),a}if(i){var s=t.loadLevel;-1===s&&(s=t.firstAutoLevel);var o=function(e,t,r,i,n){var a=t[i],s=t.reduce(function(e,t,r){var i=t.uri;return(e[i]||(e[i]=[])).push(r),e},{})[a.uri];s.length>1&&(i=Math.max.apply(Math,s));var o=a.videoRange,l=a.frameRate,u=a.codecSet.substring(0,4),c=Qt(t,i,function(t){if(t.videoRange!==o||t.frameRate!==l||t.codecSet.substring(0,4)!==u)return!1;var i=t.audioGroups,a=r.filter(function(e){return!i||-1!==i.indexOf(e.groupId)});return Yt(e,a,n)>-1});return c>-1?c:Qt(t,i,function(t){var i=t.audioGroups,a=r.filter(function(e){return!i||-1!==i.indexOf(e.groupId)});return Yt(e,a,n)>-1})}(e,t.levels,r,s,Xt);if(-1===o)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){var l=Yt(e,r);if(l>-1)return r[l]}}}return null}},{key:"setAudioTrack",value:function(e){var t=this.tracksInGroup;if(e<0||e>=t.length)this.warn("Invalid audio track id: ".concat(e));else{this.selectDefaultTrack=!1;var r=this.currentTrack,i=t[e],n=i.details&&!i.details.live;if(!(e===this.trackId&&i===r&&n||(this.log("Switching to audio-track ".concat(e,' "').concat(i.name,'" lang:').concat(i.lang," group:").concat(i.groupId," channels:").concat(i.channels)),this.trackId=e,this.currentTrack=i,this.hls.trigger(ee.AUDIO_TRACK_SWITCHING,fe({},i)),n))){var a=this.switchParams(i.url,null==r?void 0:r.details,i.details);this.loadPlaylist(a)}}}},{key:"findTrackId",value:function(e){for(var t=this.tracksInGroup,r=0;r<t.length;r++){var i=t[r];if((!this.selectDefaultTrack||i.default)&&(!e||zt(e,i,Xt)))return r}if(e){for(var n=e.name,a=e.lang,s=e.assocLang,o=e.characteristics,l=e.audioCodec,u=e.channels,c=0;c<t.length;c++){if(zt({name:n,lang:a,assocLang:s,characteristics:o,audioCodec:l,channels:u},t[c],Xt))return c}for(var d=0;d<t.length;d++){var h=t[d];if(ls(e.attrs,h.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return d}for(var f=0;f<t.length;f++){var v=t[f];if(ls(e.attrs,v.attrs,["LANGUAGE"]))return f}}return-1}},{key:"loadPlaylist",value:function(e){T(t,"loadPlaylist",this,3)([]);var r=this.currentTrack;this.shouldLoadPlaylist(r)&&$t(r.url,this.hls)&&this.scheduleLoading(r,e)}},{key:"loadingPlaylist",value:function(e,r){T(t,"loadingPlaylist",this,3)([e,r]);var i=e.id,n=e.groupId,a=this.getUrlWithDirectives(e.url,r),s=e.details,o=null==s?void 0:s.age;this.log("Loading audio-track ".concat(i,' "').concat(e.name,'" lang:').concat(e.lang," group:").concat(n).concat(void 0!==(null==r?void 0:r.msn)?" at sn "+r.msn+" part "+r.part:"").concat(o&&s.live?" age "+o.toFixed(1)+(s.type&&" "+s.type||""):""," ").concat(a)),this.hls.trigger(ee.AUDIO_TRACK_LOADING,{url:a,id:i,groupId:n,deliveryDirectives:r||null,track:e})}}])}(ss),ds=function(){return o(function e(t){a(this,e),this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=t},[{key:"destroy",value:function(){this.tracks=this.queues=null}},{key:"append",value:function(e,t,r){if(null!==this.queues&&null!==this.tracks){var i=this.queues[t];i.push(e),1!==i.length||r||this.executeNext(t)}}},{key:"appendBlocker",value:function(e){var t=this;return new Promise(function(r){var i={label:"async-blocker",execute:r,onStart:function(){},onComplete:function(){},onError:function(){}};t.append(i,e)})}},{key:"prependBlocker",value:function(e){var t=this;return new Promise(function(r){if(t.queues){var i={label:"async-blocker-prepend",execute:r,onStart:function(){},onComplete:function(){},onError:function(){}};t.queues[e].unshift(i)}})}},{key:"removeBlockers",value:function(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(function(e){var t,r=null==(t=e[0])?void 0:t.label;"async-blocker"!==r&&"async-blocker-prepend"!==r||(e[0].execute(),e.splice(0,1))})}},{key:"unblockAudio",value:function(e){null!==this.queues&&(this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio"))}},{key:"executeNext",value:function(e){if(null!==this.queues&&null!==this.tracks){var t=this.queues[e];if(t.length){var r=t[0];try{r.execute()}catch(t){var i;if(r.onError(t),null===this.queues||null===this.tracks)return;var n=null==(i=this.tracks[e])?void 0:i.buffer;null!=n&&n.updating||this.shiftAndExecuteNext(e)}}}}},{key:"shiftAndExecuteNext",value:function(e){null!==this.queues&&(this.queues[e].shift(),this.executeNext(e))}},{key:"current",value:function(e){var t;return(null==(t=this.queues)?void 0:t[e][0])||null}},{key:"toString",value:function(){var e=this.queues,t=this.tracks;return null===e||null===t?"<destroyed>":"\n".concat(this.list("video"),"\n").concat(this.list("audio"),"\n").concat(this.list("audiovideo"),"}")}},{key:"list",value:function(e){var t,r;return null!=(t=this.queues)&&t[e]||null!=(r=this.tracks)&&r[e]?"".concat(e,": (").concat(this.listSbInfo(e),") ").concat(this.listOps(e)):""}},{key:"listSbInfo",value:function(e){var t,r=null==(t=this.tracks)?void 0:t[e],i=null==r?void 0:r.buffer;return i?"SourceBuffer".concat(i.updating?" updating":"").concat(r.ended?" ended":"").concat(r.ending?" ending":""):"none"}},{key:"listOps",value:function(e){var t;return(null==(t=this.queues)?void 0:t[e].map(function(e){return e.label}).join(", "))||""}}])}(),hs=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,fs="HlsJsTrackRemovedError",vs=function(e){function t(e){var r;return a(this,t),(r=n(this,t,[e])).name=fs,r}return d(t,e),o(t)}(L(Error)),gs=function(e){function t(e,r){var i,s;return a(this,t),(i=n(this,t,["buffer-controller",e.logger])).hls=void 0,i.fragmentTracker=void 0,i.details=null,i._objectUrl=null,i.operationQueue=null,i.bufferCodecEventsTotal=0,i.media=null,i.mediaSource=null,i.lastMpegAudioChunk=null,i.blockedAudioAppend=null,i.lastVideoAppendEnd=0,i.appendSource=void 0,i.transferData=void 0,i.overrides=void 0,i.appendErrors={audio:0,video:0,audiovideo:0},i.tracks={},i.sourceBuffers=[[null,null],[null,null]],i._onEndStreaming=function(e){var t;i.hls&&"open"===(null==(t=i.mediaSource)?void 0:t.readyState)&&i.hls.pauseBuffering()},i._onStartStreaming=function(e){i.hls&&i.hls.resumeBuffering()},i._onMediaSourceOpen=function(e){var t=i,r=t.media,n=t.mediaSource;e&&i.log("Media source opened"),r&&n&&(n.removeEventListener("sourceopen",i._onMediaSourceOpen),r.removeEventListener("emptied",i._onMediaEmptied),i.updateDuration(),i.hls.trigger(ee.MEDIA_ATTACHED,{media:r,mediaSource:n}),null!==i.mediaSource&&i.checkPendingTracks())},i._onMediaSourceClose=function(){i.log("Media source closed")},i._onMediaSourceEnded=function(){i.log("Media source ended")},i._onMediaEmptied=function(){var e=i,t=e.mediaSrc,r=e._objectUrl;t!==r&&i.error("Media element src was set while attaching MediaSource (".concat(r," > ").concat(t,")"))},i.hls=e,i.fragmentTracker=r,i.appendSource=(s=ke(e.config.preferManagedMediaSource),"undefined"!=typeof self&&s===self.ManagedMediaSource),i.initTracks(),i.registerListeners(),i}return d(t,e),o(t,[{key:"hasSourceTypes",value:function(){return Object.keys(this.tracks).length>0}},{key:"destroy",value:function(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}},{key:"registerListeners",value:function(){var e=this.hls;e.on(ee.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.MANIFEST_PARSED,this.onManifestParsed,this),e.on(ee.BUFFER_RESET,this.onBufferReset,this),e.on(ee.BUFFER_APPENDING,this.onBufferAppending,this),e.on(ee.BUFFER_CODECS,this.onBufferCodecs,this),e.on(ee.BUFFER_EOS,this.onBufferEos,this),e.on(ee.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(ee.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(ee.FRAG_PARSED,this.onFragParsed,this),e.on(ee.FRAG_CHANGED,this.onFragChanged,this),e.on(ee.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(ee.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.MANIFEST_PARSED,this.onManifestParsed,this),e.off(ee.BUFFER_RESET,this.onBufferReset,this),e.off(ee.BUFFER_APPENDING,this.onBufferAppending,this),e.off(ee.BUFFER_CODECS,this.onBufferCodecs,this),e.off(ee.BUFFER_EOS,this.onBufferEos,this),e.off(ee.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(ee.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(ee.FRAG_PARSED,this.onFragParsed,this),e.off(ee.FRAG_CHANGED,this.onFragChanged,this),e.off(ee.ERROR,this.onError,this)}},{key:"transferMedia",value:function(){var e=this,t=this.media,r=this.mediaSource;if(!t)return null;var i={};if(this.operationQueue){var n=this.isUpdating();n||this.operationQueue.removeBlockers();var a=this.isQueued();(n||a)&&this.warn("Transfering MediaSource with".concat(a?" operations in queue":"").concat(n?" updating SourceBuffer(s)":""," ").concat(this.operationQueue)),this.operationQueue.destroy()}var s=this.transferData;return!this.sourceBufferCount&&s&&s.mediaSource===r?de(i,s.tracks):this.sourceBuffers.forEach(function(t){var r=m(t,1)[0];r&&(i[r]=de({},e.tracks[r]),e.removeBuffer(r)),t[0]=t[1]=null}),{media:t,mediaSource:r,tracks:i}}},{key:"initTracks",value:function(){this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}},{key:"onManifestLoading",value:function(){this.bufferCodecEventsTotal=0,this.details=null}},{key:"onManifestParsed",value:function(e,t){var r,i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log("".concat(i," bufferCodec event(s) expected.")),null!=(r=this.transferData)&&r.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}},{key:"onMediaAttaching",value:function(e,t){var r=this.media=t.media;this.transferData=this.overrides=void 0;var i=ke(this.appendSource);if(i){var n=!!t.mediaSource;(n||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);var a=this.mediaSource=t.mediaSource||new i;if(this.assignMediaSource(a),n)this._objectUrl=r.src,this.attachTransferred();else{var s=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{r.removeAttribute("src");var o=self.ManagedMediaSource;r.disableRemotePlayback=r.disableRemotePlayback||o&&a instanceof o,ps(r),function(e,t){var r=self.document.createElement("source");r.type="video/mp4",r.src=t,e.appendChild(r)}(r,s),r.load()}catch(e){r.src=s}else r.src=s}r.addEventListener("emptied",this._onMediaEmptied)}}},{key:"assignMediaSource",value:function(e){var t,r;this.log("".concat((null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created"," media source: ").concat(null==(r=e.constructor)?void 0:r.name)),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}},{key:"attachTransferred",value:function(){var e=this,t=this.media,r=this.transferData;if(r&&t){var i=this.tracks,n=r.tracks,a=n?Object.keys(n):null,s=a?a.length:0,o=function(){Promise.resolve().then(function(){e.media&&e.mediaSourceOpenOrEnded&&e._onMediaSourceOpen()})};if(n&&a&&s){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log("attachTransferred: (bufferCodecEventsTotal ".concat(this.bufferCodecEventsTotal,")\nrequired tracks: ").concat(Kt(i,function(e,t){return"initSegment"===e?void 0:t}),";\ntransfer tracks: ").concat(Kt(n,function(e,t){return"initSegment"===e?void 0:t}),"}")),!Se(n,i)){r.mediaSource=null,r.tracks=void 0;var l=t.currentTime,u=this.details,c=Math.max(l,(null==u?void 0:u.fragments[0].start)||0);return c-l>1?void this.log("attachTransferred: waiting for playback to reach new tracks start time ".concat(l," -> ").concat(c)):(this.warn('attachTransferred: resetting MediaSource for incompatible tracks ("'.concat(Object.keys(n),'"->"').concat(Object.keys(i),'") start time: ').concat(c," currentTime: ").concat(l)),this.onMediaDetaching(ee.MEDIA_DETACHING,{}),this.onMediaAttaching(ee.MEDIA_ATTACHING,r),void(t.currentTime=c))}this.transferData=void 0,a.forEach(function(t){var r=t,i=n[r];if(i){var a=i.buffer;if(a){var s=e.fragmentTracker,o=i.id;if(s.hasFragments(o)||s.hasParts(o)){var l=jr.getBuffered(a);s.detectEvictedFragments(r,l,o,null,!0)}var u=ms(r),c=[r,a];e.sourceBuffers[u]=c,a.updating&&e.operationQueue&&e.operationQueue.prependBlocker(r),e.trackSourceBuffer(r,i)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}}},{key:"mediaSourceOpenOrEnded",get:function(){var e,t=null==(e=this.mediaSource)?void 0:e.readyState;return"open"===t||"ended"===t}},{key:"onMediaDetaching",value:function(e,t){var r=this,i=!!t.transferMedia;this.transferData=this.overrides=void 0;var n=this.media,a=this.mediaSource,s=this._objectUrl;if(a){if(this.log("media source ".concat(i?"transferring":"detaching")),i)this.sourceBuffers.forEach(function(e){var t=m(e,1)[0];t&&r.removeBuffer(t)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){var o="open"===a.readyState;try{for(var l=a.sourceBuffers,u=l.length;u--;)o&&l[u].abort(),a.removeSourceBuffer(l[u]);o&&a.endOfStream()}catch(e){this.warn("onMediaDetaching: ".concat(e.message," while calling endOfStream"))}}this.sourceBufferCount&&this.onBufferReset()}a.removeEventListener("sourceopen",this._onMediaSourceOpen),a.removeEventListener("sourceended",this._onMediaSourceEnded),a.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(a.removeEventListener("startstreaming",this._onStartStreaming),a.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}n&&(n.removeEventListener("emptied",this._onMediaEmptied),i||(s&&self.URL.revokeObjectURL(s),this.mediaSrc===s?(n.removeAttribute("src"),this.appendSource&&ps(n),n.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(ee.MEDIA_DETACHED,t)}},{key:"onBufferReset",value:function(){var e=this;this.sourceBuffers.forEach(function(t){var r=m(t,1)[0];r&&e.resetBuffer(r)}),this.initTracks()}},{key:"resetBuffer",value:function(e){var t,r=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),r)try{var i;null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(r)}catch(t){this.warn("onBufferReset ".concat(e),t)}delete this.tracks[e]}},{key:"removeBuffer",value:function(e){this.removeBufferListeners(e),this.sourceBuffers[ms(e)]=[null,null];var t=this.tracks[e];t&&(t.buffer=void 0)}},{key:"resetQueue",value:function(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new ds(this.tracks)}},{key:"onBufferCodecs",value:function(e,t){var r,i=this,n=this.tracks,a=Object.keys(t);this.log('BUFFER_CODECS: "'.concat(a,'" (current SB count ').concat(this.sourceBufferCount,")"));var s="audiovideo"in t&&(n.audio||n.video)||n.audiovideo&&("audio"in t||"video"in t),o=!s&&this.sourceBufferCount&&this.media&&a.some(function(e){return!n[e]});s||o?this.warn('Unsupported transition between "'.concat(Object.keys(n),'" and "').concat(a,'" SourceBuffers')):(a.forEach(function(e){var r,a,s=t[e],o=s.id,l=s.codec,u=s.levelCodec,c=s.container,d=s.metadata,h=s.supplemental,f=n[e],v=null==(r=i.transferData)||null==(r=r.tracks)?void 0:r[e],g=null!=v&&v.buffer?v:f,p=(null==g?void 0:g.pendingCodec)||(null==g?void 0:g.codec),m=null==g?void 0:g.levelCodec;f||(f=n[e]={buffer:void 0,listeners:[],codec:l,supplemental:h,container:c,levelCodec:u,metadata:d,id:o});var y=St(p,m),T=null==y?void 0:y.replace(hs,"$1"),E=St(l,u),k=null==(a=E)?void 0:a.replace(hs,"$1");E&&y&&T!==k&&("audio"===e.slice(0,5)&&(E=kt(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,ae))?void 0:t.gap))){var a={label:"block-audio",execute:function(){var e,t=r.tracks.video;(r.lastVideoAppendEnd>n||null!=t&&t.buffer&&jr.isBuffered(t.buffer,n)||!0===(null==(e=r.fragmentTracker.getAppendedFrag(n,ae))?void 0:e.gap))&&(r.blockedAudioAppend=null,r.shiftAndExecuteNext("audio"))},onStart:function(){},onComplete:function(){},onError:function(e){r.warn("Error executing block-audio operation",e)}};this.blockedAudioAppend={op:a,frag:e},this.append(a,"audio",!0)}}},{key:"unblockAudio",value:function(){var e=this.blockedAudioAppend,t=this.operationQueue;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}},{key:"onBufferAppending",value:function(e,t){var r=this,i=this.tracks,n=t.data,a=t.type,s=t.parent,o=t.frag,l=t.part,u=t.chunkMeta,c=t.offset,d=u.buffering[a],h=o.sn,f=o.cc,v=self.performance.now();d.start=v;var g=o.stats.buffering,p=l?l.stats.buffering:null;0===g.start&&(g.start=v),p&&0===p.start&&(p.start=v);var y=i.audio,T=!1;"audio"===a&&"audio/mpeg"===(null==y?void 0:y.container)&&(T=!this.lastMpegAudioChunk||1===u.id||this.lastMpegAudioChunk.sn!==u.sn,this.lastMpegAudioChunk=u);var E=i.video,k=null==E?void 0:E.buffer;if(k&&"initSegment"!==h){var S=l||o,b=this.blockedAudioAppend;if("audio"!==a||"main"===s||this.blockedAudioAppend||E.ending||E.ended){if("video"===a){var A=S.end;if(b){var L=b.frag.start;(A>L||A<this.lastVideoAppendEnd||jr.isBuffered(k,L))&&this.unblockAudio()}this.lastVideoAppendEnd=A}}else{var R=S.start+.05*S.duration,I=k.buffered,w=this.currentOp("video");I.length||w?!w&&!jr.isBuffered(k,R)&&this.lastVideoAppendEnd<R&&this.blockAudio(S):this.blockAudio(S)}}var P=(l||o).start,D={label:"append-".concat(a),execute:function(){var e;d.executeStart=self.performance.now();var t=null==(e=r.tracks[a])?void 0:e.buffer;t&&(T?r.updateTimestampOffset(t,P,.1,a,h,f):void 0!==c&&X(c)&&r.updateTimestampOffset(t,c,1e-6,a,h,f)),r.appendExecutor(n,a)},onStart:function(){},onComplete:function(){var e=self.performance.now();d.executeEnd=d.end=e,0===g.first&&(g.first=e),p&&0===p.first&&(p.first=e);var t={};r.sourceBuffers.forEach(function(e){var r=m(e,2),i=r[0],n=r[1];i&&(t[i]=jr.getBuffered(n))}),r.appendErrors[a]=0,"audio"===a||"video"===a?r.appendErrors.audiovideo=0:(r.appendErrors.audio=0,r.appendErrors.video=0),r.hls.trigger(ee.BUFFER_APPENDED,{type:a,frag:o,part:l,chunkMeta:u,parent:o.type,timeRanges:t})},onError:function(e){var t,i={type:J.MEDIA_ERROR,parent:o.type,details:Z.BUFFER_APPEND_ERROR,sourceBufferName:a,frag:o,part:l,chunkMeta:u,error:e,err:e,fatal:!1},n=null==(t=r.media)?void 0:t.error;if(e.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==e.name||"quota"in e)i.details=Z.BUFFER_FULL_ERROR;else if(e.code===DOMException.INVALID_STATE_ERR&&r.mediaSourceOpenOrEnded&&!n)i.errorAction=kr(!0);else if(e.name===fs&&0===r.sourceBufferCount)i.errorAction=kr(!0);else{var s=++r.appendErrors[a];r.warn("Failed ".concat(s,"/").concat(r.hls.config.appendErrorMaxRetry,' times to append segment in "').concat(a,'" sourceBuffer (').concat(n||"no media error",")")),(s>=r.hls.config.appendErrorMaxRetry||n)&&(i.fatal=!0)}r.hls.trigger(ee.ERROR,i)}};this.log('queuing "'.concat(a,'" append sn: ').concat(h).concat(l?" p: "+l.index:""," of ").concat(o.type===ae?"level":"track"," ").concat(o.level," cc: ").concat(f)),this.append(D,a,this.isPending(this.tracks[a]))}},{key:"getFlushOp",value:function(e,t,r){var i=this;return this.log('queuing "'.concat(e,'" remove ').concat(t,"-").concat(r)),{label:"remove",execute:function(){i.removeExecutor(e,t,r)},onStart:function(){},onComplete:function(){i.hls.trigger(ee.BUFFER_FLUSHED,{type:e})},onError:function(n){i.warn("Failed to remove ".concat(t,"-").concat(r,' from "').concat(e,'" SourceBuffer'),n)}}}},{key:"onBufferFlushing",value:function(e,t){var r=this,i=t.type,n=t.startOffset,a=t.endOffset;i?this.append(this.getFlushOp(i,n,a),i):this.sourceBuffers.forEach(function(e){var t=m(e,1)[0];t&&r.append(r.getFlushOp(t,n,a),t)})}},{key:"onFragParsed",value:function(e,t){var r=this,i=t.frag,n=t.part,a=[],s=n?n.elementaryStreams:i.elementaryStreams;s[_e]?a.push("audiovideo"):(s[xe]&&a.push("audio"),s[Ce]&&a.push("video"));0===a.length&&this.warn("Fragments must have at least one ElementaryStreamType set. type: ".concat(i.type," level: ").concat(i.level," sn: ").concat(i.sn)),this.blockBuffers(function(){var e=self.performance.now();i.stats.buffering.end=e,n&&(n.stats.buffering.end=e);var t=n?n.stats:i.stats;r.hls.trigger(ee.FRAG_BUFFERED,{frag:i,part:n,stats:t,id:i.type})},a).catch(function(e){r.warn("Fragment buffered callback ".concat(e)),r.stepOperationQueue(r.sourceBufferTypes)})}},{key:"onFragChanged",value:function(e,t){this.trimBuffers()}},{key:"bufferedToEnd",get:function(){var e=this;return this.sourceBufferCount>0&&!this.sourceBuffers.some(function(t){var r=m(t,1)[0];if(r){var i=e.tracks[r];if(i)return!i.ended||i.ending}return!1})}},{key:"onBufferEos",value:function(e,t){var r,i=this;this.sourceBuffers.forEach(function(e){var r=m(e,1)[0];if(r){var n=i.tracks[r];t.type&&t.type!==r||(n.ending=!0,n.ended||(n.ended=!0,i.log("".concat(r," buffer reached EOS"))))}});var n=!1!==(null==(r=this.overrides)?void 0:r.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some(function(e){var t,r=m(e,1)[0];return r&&!(null!=(t=i.tracks[r])&&t.ended)})?n?(this.log("Queueing EOS"),this.blockUntilOpen(function(){i.tracksEnded();var e=i.mediaSource;e&&"open"===e.readyState?(i.log("Calling mediaSource.endOfStream()"),e.endOfStream(),i.hls.trigger(ee.BUFFERED_TO_END,void 0)):e&&i.log("Could not call mediaSource.endOfStream(). mediaSource.readyState: ".concat(e.readyState))})):(this.tracksEnded(),this.hls.trigger(ee.BUFFERED_TO_END,void 0)):"video"===t.type&&this.unblockAudio()}},{key:"tracksEnded",value:function(){var e=this;this.sourceBuffers.forEach(function(t){var r=m(t,1)[0];if(null!==r){var i=e.tracks[r];i&&(i.ending=!1)}})}},{key:"onLevelUpdated",value:function(e,t){var r=t.details;r.fragments.length&&(this.details=r,this.updateDuration())}},{key:"updateDuration",value:function(){var e=this;this.blockUntilOpen(function(){var t=e.getDurationAndRange();t&&e.updateMediaSource(t)})}},{key:"onError",value:function(e,t){if(t.details===Z.BUFFER_APPEND_ERROR&&t.frag){var r,i=null==(r=t.errorAction)?void 0:r.nextAutoLevel;X(i)&&i!==t.frag.level&&this.resetAppendErrors()}}},{key:"resetAppendErrors",value:function(){this.appendErrors={audio:0,video:0,audiovideo:0}}},{key:"trimBuffers",value:function(){var e=this.hls,t=this.details,r=this.media;if(r&&null!==t&&this.sourceBufferCount){var i=e.config,n=r.currentTime,a=t.levelTargetDuration,s=t.live&&null!==i.liveBackBufferLength?i.liveBackBufferLength:i.backBufferLength;if(X(s)&&s>=0){var o=Math.max(s,a),l=Math.floor(n/a)*a-o;this.flushBackBuffer(n,a,l)}var u=i.frontBufferFlushThreshold;if(X(u)&&u>0){var c=Math.max(i.maxBufferLength,u),d=Math.max(c,a),h=Math.floor(n/a)*a+d;this.flushFrontBuffer(n,a,h)}}}},{key:"flushBackBuffer",value:function(e,t,r){var i=this;this.sourceBuffers.forEach(function(e){var t=m(e,2),n=t[0],a=t[1];if(a){var s=jr.getBuffered(a);if(s.length>0&&r>s.start(0)){var o;i.hls.trigger(ee.BACK_BUFFER_REACHED,{bufferEnd:r});var l=i.tracks[n];if(null!=(o=i.details)&&o.live)i.hls.trigger(ee.LIVE_BACK_BUFFER_REACHED,{bufferEnd:r});else if(null!=l&&l.ended)return void i.log("Cannot flush ".concat(n," back buffer while SourceBuffer is in ended state"));i.hls.trigger(ee.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:n})}}})}},{key:"flushFrontBuffer",value:function(e,t,r){var i=this;this.sourceBuffers.forEach(function(t){var n=m(t,2),a=n[0],s=n[1];if(s){var o=jr.getBuffered(s),l=o.length;if(l<2)return;var u=o.start(l-1),c=o.end(l-1);if(r>u||e>=u&&e<=c)return;i.hls.trigger(ee.BUFFER_FLUSHING,{startOffset:u,endOffset:1/0,type:a})}})}},{key:"getDurationAndRange",value:function(){var e,t=this.details,r=this.mediaSource;if(!t||!this.media||"open"!==(null==r?void 0:r.readyState))return null;var i=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&r.setLiveSeekableRange){var n=Math.max(0,t.fragmentStart);return{duration:1/0,start:n,end:Math.max(n,i)}}return{duration:1/0}}var a=null==(e=this.overrides)?void 0:e.duration;if(a)return X(a)?{duration:a}:null;var s=this.media.duration;return i>(X(r.duration)?r.duration:0)&&i>s||!X(s)?{duration:i}:null}},{key:"updateMediaSource",value:function(e){var t=e.duration,r=e.start,i=e.end,n=this.mediaSource;this.media&&n&&"open"===n.readyState&&(n.duration!==t&&(X(t)&&this.log("Updating MediaSource duration to ".concat(t.toFixed(3))),n.duration=t),void 0!==r&&void 0!==i&&(this.log("MediaSource duration is set to ".concat(n.duration,". Setting seekable range to ").concat(r,"-").concat(i,".")),n.setLiveSeekableRange(r,i)))}},{key:"tracksReady",get:function(){var e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}},{key:"checkPendingTracks",value:function(){var e=this.bufferCodecEventsTotal,t=this.pendingTrackCount,r=this.tracks;if(this.log("checkPendingTracks (pending: ".concat(t," codec events expected: ").concat(e,") ").concat(Kt(r))),this.tracksReady){var i,n=null==(i=this.transferData)?void 0:i.tracks;n&&Object.keys(n).length?this.attachTransferred():this.createSourceBuffers()}}},{key:"bufferCreated",value:function(){var e=this;if(this.sourceBufferCount){var t={};this.sourceBuffers.forEach(function(r){var i=m(r,2),n=i[0],a=i[1];if(n){var s=e.tracks[n];t[n]={buffer:a,container:s.container,codec:s.codec,supplemental:s.supplemental,levelCodec:s.levelCodec,id:s.id,metadata:s.metadata}}}),this.hls.trigger(ee.BUFFER_CREATED,{tracks:t}),this.log("SourceBuffers created. Running queue: ".concat(this.operationQueue)),this.sourceBuffers.forEach(function(t){var r=m(t,1)[0];e.executeNext(r)})}else{var r=new Error("could not create source buffer for media codec(s)");this.hls.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:r,reason:r.message})}}},{key:"createSourceBuffers",value:function(){var e=this.tracks,t=this.sourceBuffers,r=this.mediaSource;if(!r)throw new Error("createSourceBuffers called when mediaSource was null");for(var i in e){var n=i,a=e[n];if(this.isPending(a)){var s=this.getTrackCodec(a,n),o="".concat(a.container,";codecs=").concat(s);a.codec=s,this.log("creating sourceBuffer(".concat(o,")").concat(this.currentOp(n)?" Queued":""," ").concat(Kt(a)));try{var l=r.addSourceBuffer(o),u=ms(n),c=[n,l];t[u]=c,a.buffer=l}catch(e){var d;return this.error("error while trying to add sourceBuffer: ".concat(e.message)),this.shiftAndExecuteNext(n),null==(d=this.operationQueue)||d.removeBlockers(),delete this.tracks[n],void this.hls.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:n,mimeType:o,parent:a.id})}this.trackSourceBuffer(n,a)}}this.bufferCreated()}},{key:"getTrackCodec",value:function(e,t){var r=e.supplemental,i=e.codec;r&&("video"===t||"audiovideo"===t)&&vt(r,"video")&&(i=function(e,t){var r=[];if(e)for(var i=e.split(","),n=0;n<i.length;n++)ft(i[n],"video")||r.push(i[n]);return t&&r.push(t),r.join(",")}(i,r));var n=St(i,e.levelCodec);return n?"audio"===t.slice(0,5)?kt(n,this.appendSource):n:""}},{key:"trackSourceBuffer",value:function(e,t){var r=this,i=t.buffer;if(i){var n=this.getTrackCodec(t,e);this.tracks[e]={buffer:i,codec:n,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",function(e,t){var i=t.removedRanges;null!=i&&i.length&&r.hls.trigger(ee.BUFFER_FLUSHED,{type:e})})}}},{key:"mediaSrc",get:function(){var e,t,r=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==r?void 0:r.src}},{key:"onSBUpdateStart",value:function(e){var t=this.currentOp(e);t&&t.onStart()}},{key:"onSBUpdateEnd",value:function(e){var t;if("closed"!==(null==(t=this.mediaSource)?void 0:t.readyState)){var r=this.currentOp(e);r&&(r.onComplete(),this.shiftAndExecuteNext(e))}else this.resetBuffer(e)}},{key:"onSBUpdateError",value:function(e,t){var r,i=new Error("".concat(e," SourceBuffer error. MediaSource readyState: ").concat(null==(r=this.mediaSource)?void 0:r.readyState));this.error("".concat(i),t),this.hls.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});var n=this.currentOp(e);n&&n.onError(i)}},{key:"updateTimestampOffset",value:function(e,t,r,i,n,a){var s=t-e.timestampOffset;Math.abs(s)>=r&&(this.log("Updating ".concat(i," SourceBuffer timestampOffset to ").concat(t," (sn: ").concat(n," cc: ").concat(a,")")),e.timestampOffset=t)}},{key:"removeExecutor",value:function(e,t,r){var i=this.media,n=this.mediaSource,a=this.tracks[e],s=null==a?void 0:a.buffer;if(!i||!n||!s)return this.warn("Attempting to remove from the ".concat(e," SourceBuffer, but it does not exist")),void this.shiftAndExecuteNext(e);var o=X(i.duration)?i.duration:1/0,l=X(n.duration)?n.duration:1/0,u=Math.max(0,t),c=Math.min(r,o,l);c>u&&(!a.ending||a.ended)?(a.ended=!1,this.log("Removing [".concat(u,",").concat(c,"] from the ").concat(e," SourceBuffer")),s.remove(u,c)):this.shiftAndExecuteNext(e)}},{key:"appendExecutor",value:function(e,t){var r=this.tracks[t],i=null==r?void 0:r.buffer;if(!i)throw new vs("Attempting to append to the ".concat(t," SourceBuffer, but it does not exist"));r.ending=!1,r.ended=!1,i.appendBuffer(e)}},{key:"blockUntilOpen",value:function(e){var t=this;if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(function(e){t.warn("SourceBuffer blocked callback ".concat(e)),t.stepOperationQueue(t.sourceBufferTypes)});else try{e()}catch(e){this.warn("Callback run without blocking ".concat(this.operationQueue," ").concat(e))}}},{key:"isUpdating",value:function(){return this.sourceBuffers.some(function(e){var t=m(e,2),r=t[0],i=t[1];return r&&i.updating})}},{key:"isQueued",value:function(){var e=this;return this.sourceBuffers.some(function(t){var r=m(t,1)[0];return r&&!!e.currentOp(r)})}},{key:"isPending",value:function(e){return!!e&&!e.buffer}},{key:"blockBuffers",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.sourceBufferTypes;if(!r.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);var i=this.operationQueue,n=r.map(function(e){return t.appendBlocker(e)});return r.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(n).then(function(r){i===t.operationQueue&&(e(),t.stepOperationQueue(t.sourceBufferTypes))})}},{key:"stepOperationQueue",value:function(e){var t=this;e.forEach(function(e){var r,i=null==(r=t.tracks[e])?void 0:r.buffer;i&&!i.updating&&t.shiftAndExecuteNext(e)})}},{key:"append",value:function(e,t,r){this.operationQueue&&this.operationQueue.append(e,t,r)}},{key:"appendBlocker",value:function(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}},{key:"currentOp",value:function(e){return this.operationQueue?this.operationQueue.current(e):null}},{key:"executeNext",value:function(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}},{key:"shiftAndExecuteNext",value:function(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}},{key:"pendingTrackCount",get:function(){var e=this;return Object.keys(this.tracks).reduce(function(t,r){return t+(e.isPending(e.tracks[r])?1:0)},0)}},{key:"sourceBufferCount",get:function(){return this.sourceBuffers.reduce(function(e,t){return e+(m(t,1)[0]?1:0)},0)}},{key:"sourceBufferTypes",get:function(){return this.sourceBuffers.map(function(e){return m(e,1)[0]}).filter(function(e){return!!e})}},{key:"addBufferListener",value:function(e,t,r){var i=this.tracks[e];if(i){var n=i.buffer;if(n){var a=r.bind(this,e);i.listeners.push({event:t,listener:a}),n.addEventListener(t,a)}}}},{key:"removeBufferListeners",value:function(e){var t=this.tracks[e];if(t){var r=t.buffer;r&&(t.listeners.forEach(function(e){r.removeEventListener(e.event,e.listener)}),t.listeners.length=0)}}}])}(ve);function ps(e){var t=e.querySelectorAll("source");[].slice.call(t).forEach(function(t){e.removeChild(t)})}function ms(e){return"audio"===e?1:0}var ys=function(){function e(t){a(this,e),this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}return o(e,[{key:"setStreamController",value:function(e){this.streamController=e}},{key:"destroy",value:function(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}},{key:"registerListeners",value:function(){var e=this.hls;e.on(ee.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(ee.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(ee.MANIFEST_PARSED,this.onManifestParsed,this),e.on(ee.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(ee.BUFFER_CODECS,this.onBufferCodecs,this),e.on(ee.MEDIA_DETACHING,this.onMediaDetaching,this)}},{key:"unregisterListener",value:function(){var e=this.hls;e.off(ee.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(ee.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(ee.MANIFEST_PARSED,this.onManifestParsed,this),e.off(ee.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(ee.BUFFER_CODECS,this.onBufferCodecs,this),e.off(ee.MEDIA_DETACHING,this.onMediaDetaching,this)}},{key:"onFpsDropLevelCapping",value:function(e,t){var r=this.hls.levels[t.droppedLevel];this.isLevelAllowed(r)&&this.restrictedLevels.push({bitrate:r.bitrate,height:r.height,width:r.width})}},{key:"onMediaAttaching",value:function(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}},{key:"onManifestParsed",value:function(e,t){var r=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,r.config.capLevelToPlayerSize&&t.video&&this.startCapping()}},{key:"onLevelsUpdated",value:function(e,t){this.timer&&X(this.autoLevelCapping)&&this.detectPlayerSize()}},{key:"onBufferCodecs",value:function(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}},{key:"onMediaDetaching",value:function(){this.stopCapping(),this.media=null}},{key:"detectPlayerSize",value:function(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);var e=this.hls.levels;if(e.length){var t=this.hls,r=this.getMaxLevel(e.length-1);r!==this.autoLevelCapping&&t.logger.log("Setting autoLevelCapping to ".concat(r,": ").concat(e[r].height,"p@").concat(e[r].bitrate," for media ").concat(this.mediaWidth,"x").concat(this.mediaHeight)),t.autoLevelCapping=r,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}},{key:"getMaxLevel",value:function(t){var r=this,i=this.hls.levels;if(!i.length)return-1;var n=i.filter(function(e,i){return r.isLevelAllowed(e)&&i<=t});return this.clientRect=null,e.getMaxLevelByMediaSize(n,this.mediaWidth,this.mediaHeight)}},{key:"startCapping",value:function(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}},{key:"stopCapping",value:function(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}},{key:"getDimensions",value:function(){if(this.clientRect)return this.clientRect;var e=this.media,t={width:0,height:0};if(e){var r=e.getBoundingClientRect();t.width=r.width,t.height=r.height,t.width||t.height||(t.width=r.right-r.left||e.width||0,t.height=r.bottom-r.top||e.height||0)}return this.clientRect=t,t}},{key:"mediaWidth",get:function(){return this.getDimensions().width*this.contentScaleFactor}},{key:"mediaHeight",get:function(){return this.getDimensions().height*this.contentScaleFactor}},{key:"contentScaleFactor",get:function(){var e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch(e){}return Math.min(e,this.hls.config.maxDevicePixelRatio)}},{key:"isLevelAllowed",value:function(e){return!this.restrictedLevels.some(function(t){return e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height})}}],[{key:"getMaxLevelByMediaSize",value:function(e,t,r){if(null==e||!e.length)return-1;for(var i=function(e,t){return!t||(e.width!==t.width||e.height!==t.height)},n=e.length-1,a=Math.max(t,r),s=0;s<e.length;s+=1){var o=e[s];if((o.width>=a||o.height>=a)&&i(o,e[s+1])){n=s;break}}return n}}])}(),Ts={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Es={HLS:"h"},ks=o(function e(t,r){a(this,e),Array.isArray(t)&&(t=t.map(function(t){return t instanceof e?t:new e(t)})),this.value=t,this.params=r});function Ss(e,t,r,i){return new Error("failed to ".concat(e,' "').concat((n=t,Array.isArray(n)?JSON.stringify(n):n instanceof Map?"Map{}":n instanceof Set?"Set{}":"object"===S(n)?JSON.stringify(n):String(n)),'" as ').concat(r),{cause:i});var n}function bs(e,t,r){return Ss("serialize",e,t,r)}var As=o(function e(t){a(this,e),this.description=t}),Ls="Bare Item";function Rs(e){if(!1===ArrayBuffer.isView(e))throw bs(e,"Byte Sequence");return":".concat((t=e,btoa(String.fromCharCode.apply(String,E(t)))),":");var t}function Is(e){if(function(e){return e<-999999999999999||999999999999999<e}(e))throw bs(e,"Integer");return e.toString()}function ws(e,t){if(e<0)return-ws(-e,t);var r=Math.pow(10,t);if(Math.abs(e*r%1-.5)<Number.EPSILON){var i=Math.floor(e*r);return(i%2==0?i:i+1)/r}return Math.round(e*r)/r}function Ps(e){var t=ws(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw bs(e,"Decimal");var r=t.toString();return r.includes(".")?r:"".concat(r,".0")}var Ds=/[\x00-\x1f\x7f]+/;function xs(e){var t,r=(t=e).description||t.toString().slice(7,-1);if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(r))throw bs(r,"Token");return r}function Cs(e){switch(S(e)){case"number":if(!X(e))throw bs(e,Ls);return Number.isInteger(e)?Is(e):Ps(e);case"string":return function(e){if(Ds.test(e))throw bs(e,"String");return'"'.concat(e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),'"')}(e);case"symbol":return xs(e);case"boolean":return function(e){if("boolean"!=typeof e)throw bs(e,"Boolean");return e?"?1":"?0"}(e);case"object":if(e instanceof Date)return function(e){return"@".concat(Is(e.getTime()/1e3))}(e);if(e instanceof Uint8Array)return Rs(e);if(e instanceof As)return xs(e);default:throw bs(e,Ls)}}function _s(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw bs(e,"Key");return e}function Ms(e){return null==e?"":Object.entries(e).map(function(e){var t=m(e,2),r=t[0],i=t[1];return!0===i?";".concat(_s(r)):";".concat(_s(r),"=").concat(Cs(i))}).join("")}function Os(e){return e instanceof ks?"".concat(Cs(e.value)).concat(Ms(e.params)):Cs(e)}function Fs(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{whitespace:!0};if("object"!==S(e)||null==e)throw bs(e,"Dict");var r=e instanceof Map?e.entries():Object.entries(e),i=(null==t?void 0:t.whitespace)?" ":"";return Array.from(r).map(function(e){var t=m(e,2),r=t[0],i=t[1];i instanceof ks==!1&&(i=new ks(i));var n,a=_s(r);return!0===i.value?a+=Ms(i.params):(a+="=",Array.isArray(i.value)?a+="(".concat((n=i).value.map(Os).join(" "),")").concat(Ms(n.params)):a+=Os(i)),a}).join(",".concat(i))}function Us(e,t){return Fs(e,t)}var Ns="CMCD-Object",Bs="CMCD-Request",Vs="CMCD-Session",Gs="CMCD-Status",Hs={br:Ns,ab:Ns,d:Ns,ot:Ns,tb:Ns,tpb:Ns,lb:Ns,tab:Ns,lab:Ns,url:Ns,pb:Bs,bl:Bs,tbl:Bs,dl:Bs,ltc:Bs,mtp:Bs,nor:Bs,nrr:Bs,rc:Bs,sn:Bs,sta:Bs,su:Bs,ttfb:Bs,ttfbb:Bs,ttlb:Bs,cmsdd:Bs,cmsds:Bs,smrt:Bs,df:Bs,cs:Bs,ts:Bs,cid:Vs,pr:Vs,sf:Vs,sid:Vs,st:Vs,v:Vs,msd:Vs,bs:Gs,bsd:Gs,cdn:Gs,rtp:Gs,bg:Gs,pt:Gs,ec:Gs,e:Gs},Ks=Bs;function js(e,t){var r={};if(!e)return r;var i,n=Object.keys(e),a=t?(i=t,Object.keys(i).reduce(function(e,t){var r;return null===(r=i[t])||void 0===r||r.forEach(function(r){return e[r]=t}),e},{})):{};return n.reduce(function(t,r){var i,n=Hs[r]||a[r]||Ks;return(null!==(i=t[n])&&void 0!==i?i:t[n]={})[r]=e[r],t},r)}var qs="event";var Ws=function(e){return Math.round(e)},Ys=function(e,t){return Array.isArray(e)?e.map(function(e){return Ys(e,t)}):e instanceof ks&&"string"==typeof e.value?new ks(Ys(e.value,t),e.params):(t.baseUrl&&(e=function(e,t){var r=new URL(e),i=new URL(t);if(r.origin!==i.origin)return e;for(var n=r.pathname.split("/").slice(1),a=i.pathname.split("/").slice(1,-1);n[0]===a[0];)n.shift(),a.shift();for(;a.length;)a.shift(),n.unshift("..");return n.join("/")+r.search+r.hash}(e,t.baseUrl)),1===t.version?encodeURIComponent(e):e)},zs=function(e){return 100*Ws(e/100)},Xs={br:Ws,d:Ws,bl:zs,dl:zs,mtp:zs,nor:function(e,t){var r=e;return t.version>=2&&(e instanceof ks&&"string"==typeof e.value?r=new ks([e]):"string"==typeof e&&(r=[e])),Ys(r,t)},rtp:zs,tb:Ws},Qs="request",$s="response",Js=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],Zs=["e"],eo=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function to(e){return eo.test(e)}var ro=["d","dl","nor","ot","rtp","su"];var io=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];var no=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function ao(e){return no.includes(e)||to(e)}var so=l(l(l({},$s,function(e){return Js.includes(e)||ro.includes(e)||io.includes(e)||to(e)}),qs,function(e){return Js.includes(e)||Zs.includes(e)||to(e)}),Qs,function(e){return Js.includes(e)||ro.includes(e)||to(e)});function oo(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r={};if(null==e||"object"!==S(e))return r;var i=t.version||e.v||1,n=t.reportingMode||Qs,a=1===i?ao:so[n],s=Object.keys(e).filter(a),o=t.filter;"function"==typeof o&&(s=s.filter(o));var l=n===$s||n===qs;l&&!s.includes("ts")&&s.push("ts"),i>1&&!s.includes("v")&&s.push("v");var u=de({},Xs,t.formatters),c={version:i,reportingMode:n,baseUrl:t.baseUrl};return s.sort().forEach(function(t){var n=e[t],a=u[t];if("function"==typeof a&&(n=a(n,c)),"v"===t){if(1===i)return;n=i}"pr"==t&&1===n||(l&&"ts"===t&&!X(n)&&(n=Date.now()),function(e){return"number"==typeof e?X(e):null!=e&&""!==e&&!1!==e}(n)&&(function(e){return["ot","sf","st","e","sta"].includes(e)}(t)&&"string"==typeof n&&(n=new As(n)),r[t]=n))}),r}function lo(e,t,r){return de(e,function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r={};if(!e)return r;var i=js(oo(e,t),null==t?void 0:t.customHeaderMap);return Object.entries(i).reduce(function(e,t){var r=m(t,2),i=r[0],n=Us(r[1],{whitespace:!1});return n&&(e[i]=n),e},r)}(t,r))}function uo(e){if(!e)return"";var t=function(e){return e?Us(oo(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}),{whitespace:!1}):""}(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{});return encodeURIComponent(t)}var co=/CMCD=[^&#]+/;function ho(e,t,r){var i=function(e){if(!e)return"";var t=uo(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{});return"".concat("CMCD","=").concat(t)}(t,r);if(!i)return e;if(co.test(e))return e.replace(co,i);var n=e.includes("?")?"&":"?";return"".concat(e).concat(n).concat(i)}var fo=function(){return o(function e(t){var r=this;a(this,e),this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=function(){r.initialized&&(r.starved=!0),r.buffering=!0},this.onPlaying=function(){r.initialized||(r.initialized=!0),r.buffering=!1},this.applyPlaylistData=function(e){try{r.apply(e,{ot:Ts.MANIFEST,su:!r.initialized})}catch(e){r.hls.logger.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=function(e){try{var t=e.frag,i=e.part,n=r.hls.levels[t.level],a=r.getObjectType(t),s={d:1e3*(i||t).duration,ot:a};a!==Ts.VIDEO&&a!==Ts.AUDIO&&a!=Ts.MUXED||(s.br=n.bitrate/1e3,s.tb=r.getTopBandwidth(a)/1e3,s.bl=r.getBufferLength(a));var o=i?r.getNextPart(i):r.getNextFrag(t);null!=o&&o.url&&o.url!==t.url&&(s.nor=o.url),r.apply(e,s)}catch(e){r.hls.logger.warn("Could not generate segment CMCD data.",e)}},this.hls=t;var i=this.config=t.config,n=i.cmcd;null!=n&&(i.pLoader=this.createPlaylistLoader(),i.fLoader=this.createFragmentLoader(),this.sid=n.sessionId||t.sessionId,this.cid=n.contentId,this.useHeaders=!0===n.useHeaders,this.includeKeys=n.includeKeys,this.registerListeners())},[{key:"registerListeners",value:function(){var e=this.hls;e.on(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ee.MEDIA_DETACHED,this.onMediaDetached,this),e.on(ee.BUFFER_CREATED,this.onBufferCreated,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ee.MEDIA_DETACHED,this.onMediaDetached,this),e.off(ee.BUFFER_CREATED,this.onBufferCreated,this)}},{key:"destroy",value:function(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}},{key:"onMediaAttached",value:function(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}},{key:"onMediaDetached",value:function(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}},{key:"onBufferCreated",value:function(e,t){var r,i;this.audioBuffer=null==(r=t.tracks.audio)?void 0:r.buffer,this.videoBuffer=null==(i=t.tracks.video)?void 0:i.buffer}},{key:"createData",value:function(){var e;return{v:1,sf:Es.HLS,sid:this.sid,cid:this.cid,pr:null==(e=this.media)?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}},{key:"apply",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};de(t,this.createData());var r=t.ot===Ts.INIT||t.ot===Ts.VIDEO||t.ot===Ts.MUXED;this.starved&&r&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering);var i=this.includeKeys;i&&(t=Object.keys(t).reduce(function(e,r){return i.includes(r)&&(e[r]=t[r]),e},{}));var n={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),lo(e.headers,t,n)):e.url=ho(e.url,t,n)}},{key:"getNextFrag",value:function(e){var t,r=null==(t=this.hls.levels[e.level])?void 0:t.details;if(r){var i=e.sn-r.startSN;return r.fragments[i+1]}}},{key:"getNextPart",value:function(e){var t,r=e.index,i=e.fragment,n=null==(t=this.hls.levels[i.level])||null==(t=t.details)?void 0:t.partList;if(n)for(var a=i.sn,s=n.length-1;s>=0;s--){var o=n[s];if(o.index===r&&o.fragment.sn===a)return n[s+1]}}},{key:"getObjectType",value:function(e){var t=e.type;return"subtitle"===t?Ts.TIMED_TEXT:"initSegment"===e.sn?Ts.INIT:"audio"===t?Ts.AUDIO:"main"===t?this.hls.audioTracks.length?Ts.VIDEO:Ts.MUXED:void 0}},{key:"getTopBandwidth",value:function(e){var t,r=0,i=this.hls;if(e===Ts.AUDIO)t=i.audioTracks;else{var n=i.maxAutoLevel,a=n>-1?n+1:i.levels.length;t=i.levels.slice(0,a)}return t.forEach(function(e){e.bitrate>r&&(r=e.bitrate)}),r>0?r:NaN}},{key:"getBufferLength",value:function(e){var t=this.media,r=e===Ts.AUDIO?this.audioBuffer:this.videoBuffer;return r&&t?1e3*jr.bufferInfo(r,t.currentTime,this.config.maxBufferHole).len:NaN}},{key:"createPlaylistLoader",value:function(){var e=this.config.pLoader,t=this.applyPlaylistData,r=e||this.config.loader;return function(){return o(function e(t){a(this,e),this.loader=void 0,this.loader=new r(t)},[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}},{key:"destroy",value:function(){this.loader.destroy()}},{key:"abort",value:function(){this.loader.abort()}},{key:"load",value:function(e,r,i){t(e),this.loader.load(e,r,i)}}])}()}},{key:"createFragmentLoader",value:function(){var e=this.config.fLoader,t=this.applyFragmentData,r=e||this.config.loader;return function(){return o(function e(t){a(this,e),this.loader=void 0,this.loader=new r(t)},[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}},{key:"destroy",value:function(){this.loader.destroy()}},{key:"abort",value:function(){this.loader.abort()}},{key:"load",value:function(e,r,i){t(e),this.loader.load(e,r,i)}}])}()}}])}(),vo=function(e){function t(e){var r;return a(this,t),(r=n(this,t,["content-steering",e.logger])).hls=void 0,r.loader=null,r.uri=null,r.pathwayId=".",r._pathwayPriority=null,r.timeToLoad=300,r.reloadTimer=-1,r.updated=0,r.started=!1,r.enabled=!0,r.levels=null,r.audioTracks=null,r.subtitleTracks=null,r.penalizedPathways={},r.hls=e,r.registerListeners(),r}return d(t,e),o(t,[{key:"registerListeners",value:function(){var e=this.hls;e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(ee.MANIFEST_PARSED,this.onManifestParsed,this),e.on(ee.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(ee.MANIFEST_PARSED,this.onManifestParsed,this),e.off(ee.ERROR,this.onError,this))}},{key:"pathways",value:function(){return(this.levels||[]).reduce(function(e,t){return-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e},[])}},{key:"pathwayPriority",get:function(){return this._pathwayPriority},set:function(e){this.updatePathwayPriority(e)}},{key:"startLoad",value:function(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){var e=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}}},{key:"stopLoad",value:function(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}},{key:"clearTimeout",value:function(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}},{key:"destroy",value:function(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}},{key:"removeLevel",value:function(e){var t=this.levels;t&&(this.levels=t.filter(function(t){return t!==e}))}},{key:"onManifestLoading",value:function(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}},{key:"onManifestLoaded",value:function(e,t){var r=t.contentSteering;null!==r&&(this.pathwayId=r.pathwayId,this.uri=r.uri,this.started&&this.startLoad())}},{key:"onManifestParsed",value:function(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}},{key:"onError",value:function(e,t){var r=t.errorAction;if((null==r?void 0:r.action)===fr&&r.flags===mr){var i=this.levels,n=this._pathwayPriority,a=this.pathwayId;if(t.context){var s=t.context,o=s.groupId,l=s.pathwayId,u=s.type;o&&i?a=this.getPathwayForGroupId(o,u,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!n&&i&&(n=this.pathways()),n&&n.length>1&&(this.updatePathwayPriority(n),r.resolved=this.pathwayId!==a),t.details!==Z.BUFFER_APPEND_ERROR||t.fatal?r.resolved||this.warn("Could not resolve ".concat(t.details,' ("').concat(t.error.message,'") with content-steering for Pathway: ').concat(a," levels: ").concat(i?i.length:i," priorities: ").concat(Kt(n)," penalized: ").concat(Kt(this.penalizedPathways))):r.resolved=!0}}},{key:"filterParsedLevels",value:function(e){this.levels=e;var t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){var r=e[0].pathwayId;this.log("No levels found in Pathway ".concat(this.pathwayId,'. Setting initial Pathway to "').concat(r,'"')),t=this.getLevelsForPathway(r),this.pathwayId=r}return t.length!==e.length&&this.log("Found ".concat(t.length,"/").concat(e.length,' levels in Pathway "').concat(this.pathwayId,'"')),t}},{key:"getLevelsForPathway",value:function(e){return null===this.levels?[]:this.levels.filter(function(t){return e===t.pathwayId})}},{key:"updatePathwayPriority",value:function(e){var t;this._pathwayPriority=e;var r=this.penalizedPathways,i=performance.now();Object.keys(r).forEach(function(e){i-r[e]>3e5&&delete r[e]});for(var n=0;n<e.length;n++){var a=e[n];if(!(a in r)){if(a===this.pathwayId)return;var s=this.hls.nextLoadLevel,o=this.hls.levels[s];if((t=this.getLevelsForPathway(a)).length>0){this.log('Setting Pathway to "'.concat(a,'"')),this.pathwayId=a,Zi(t),this.hls.trigger(ee.LEVELS_UPDATED,{levels:t});var l=this.hls.levels[s];o&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==o.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==o.bitrate&&this.log("Unstable Pathways change from bitrate ".concat(o.bitrate," to ").concat(l.bitrate)),this.hls.nextLoadLevel=s);break}}}}},{key:"getPathwayForGroupId",value:function(e,t,r){for(var i=this.getLevelsForPathway(r).concat(this.levels||[]),n=0;n<i.length;n++)if(t===ie&&i[n].hasAudioGroup(e)||t===ne&&i[n].hasSubtitleGroup(e))return i[n].pathwayId;return r}},{key:"clonePathways",value:function(e){var t=this,r=this.levels;if(r){var i={},n={};e.forEach(function(e){var a=e.ID,s=e["BASE-ID"],o=e["URI-REPLACEMENT"];if(!r.some(function(e){return e.pathwayId===a})){var l=t.getLevelsForPathway(s).map(function(e){var t=new Jr(e.attrs);t["PATHWAY-ID"]=a;var r=t.AUDIO&&"".concat(t.AUDIO,"_clone_").concat(a),s=t.SUBTITLES&&"".concat(t.SUBTITLES,"_clone_").concat(a);r&&(i[t.AUDIO]=r,t.AUDIO=r),s&&(n[t.SUBTITLES]=s,t.SUBTITLES=s);var l=po(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",o),u=new Vt({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,E(l)),go(t.audioTracks,i,o,a),go(t.subtitleTracks,n,o,a)}})}}},{key:"loadSteeringManifest",value:function(e){var t,r=this,i=this.hls.config,n=i.loader;this.loader&&this.loader.destroy(),this.loader=new n(i);try{t=new self.URL(e)}catch(t){return this.enabled=!1,void this.log("Failed to parse Steering Manifest URI: ".concat(e))}if("data:"!==t.protocol){var a=0|(this.hls.bandwidthEstimate||i.abrEwmaDefaultEstimate);t.searchParams.set("_HLS_pathway",this.pathwayId),t.searchParams.set("_HLS_throughput",""+a)}var s={responseType:"json",url:t.href},o=i.steeringManifestLoadPolicy.default,l=o.errorRetry||o.timeoutRetry||{},u={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:l.maxNumRetry||0,retryDelay:l.retryDelayMs||0,maxRetryDelay:l.maxRetryDelayMs||0},c={onSuccess:function(e,i,n,a){r.log('Loaded steering manifest: "'.concat(t,'"'));var s=e.data;if(1===(null==s?void 0:s.VERSION)){r.updated=performance.now(),r.timeToLoad=s.TTL;var o=s["RELOAD-URI"],l=s["PATHWAY-CLONES"],u=s["PATHWAY-PRIORITY"];if(o)try{r.uri=new self.URL(o,t).href}catch(e){return r.enabled=!1,void r.log("Failed to parse Steering Manifest RELOAD-URI: ".concat(o))}r.scheduleRefresh(r.uri||n.url),l&&r.clonePathways(l);var c={steeringManifest:s,url:t.toString()};r.hls.trigger(ee.STEERING_MANIFEST_LOADED,c),u&&r.updatePathwayPriority(u)}else r.log("Steering VERSION ".concat(s.VERSION," not supported!"))},onError:function(e,t,i,n){if(r.log("Error loading steering manifest: ".concat(e.code," ").concat(e.text," (").concat(t.url,")")),r.stopLoad(),410===e.code)return r.enabled=!1,void r.log("Steering manifest ".concat(t.url," no longer available"));var a=1e3*r.timeToLoad;if(429!==e.code)r.scheduleRefresh(r.uri||t.url,a);else{var s=r.loader;if("function"==typeof(null==s?void 0:s.getResponseHeader)){var o=s.getResponseHeader("Retry-After");o&&(a=1e3*parseFloat(o))}r.log("Steering manifest ".concat(t.url," rate limited"))}},onTimeout:function(e,t,i){r.log("Timeout loading steering manifest (".concat(t.url,")")),r.scheduleRefresh(r.uri||t.url)}};this.log("Requesting steering manifest: ".concat(t)),this.loader.load(s,u,c)}},{key:"scheduleRefresh",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1e3*this.timeToLoad;this.clearTimeout(),this.reloadTimer=self.setTimeout(function(){var r,i=null==(r=t.hls)?void 0:r.media;!i||i.ended?t.scheduleRefresh(e,1e3*t.timeToLoad):t.loadSteeringManifest(e)},r)}}])}(ve);function go(e,t,r,i){e&&Object.keys(t).forEach(function(n){var a=e.filter(function(e){return e.groupId===n}).map(function(e){var a=de({},e);return a.details=void 0,a.attrs=new Jr(a.attrs),a.url=a.attrs.URI=po(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",r),a.groupId=a.attrs["GROUP-ID"]=t[n],a.attrs["PATHWAY-ID"]=i,a});e.push.apply(e,E(a))})}function po(e,t,r,i){var n,a=i.HOST,s=i.PARAMS,o=i[r];t&&(n=null==o?void 0:o[t])&&(e=n);var l=new self.URL(e);return a&&!n&&(l.host=a),s&&Object.keys(s).sort().forEach(function(e){e&&l.searchParams.set(e,s[e])}),l.href}var mo=function(e){function t(e){var r;return a(this,t),(r=n(this,t,["eme",e.logger])).hls=void 0,r.config=void 0,r.media=null,r.mediaResolved=void 0,r.keyFormatPromise=null,r.keySystemAccessPromises={},r._requestLicenseFailureCount=0,r.mediaKeySessions=[],r.keyIdToKeySessionPromise={},r.mediaKeys=null,r.setMediaKeysQueue=t.CDMCleanupPromise?[t.CDMCleanupPromise]:[],r.bannedKeyIds={},r.onMediaEncrypted=function(e){var t=e.initDataType,i=e.initData,n='"'.concat(e.type,'" event: init data type: "').concat(t,'"');if(r.debug(n),null!==i){if(!r.keyFormatPromise){var a=Object.keys(r.keySystemAccessPromises);a.length||(a=Ti(r.config));var s=a.map(yi).filter(function(e){return!!e});r.keyFormatPromise=r.getKeyFormatPromise(s)}r.keyFormatPromise.then(function(a){var s=mi(a);if("sinf"===t&&s===hi.FAIRPLAY){var o;try{var l=He(new Uint8Array(i)),u=rt(oi(JSON.parse(l).sinf));if(!u)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");o=new Uint8Array(u.subarray(8,24))}catch(e){return void r.warn("".concat(n," Failed to parse sinf: ").concat(e))}for(var c,d=Ae(o),h=r,f=h.keyIdToKeySessionPromise,v=h.mediaKeySessions,g=f[d],p=function(){var e=v[m],n=e.decryptdata;if(!n.keyId)return 0;var a=Ae(n.keyId);return ii(o,n.keyId)||-1!==n.uri.replace(/-/g,"").indexOf(d)?(g=f[a])?(n.pssh||(delete f[a],n.pssh=new Uint8Array(i),n.keyId=o,(g=f[d]=g.then(function(){return r.generateRequestWithPreferredKeySession(e,t,i,"encrypted-event-key-match")})).catch(function(e){return r.handleError(e)})),1):0:void 0},m=0;m<v.length&&(0===(c=p())||1!==c);m++);g||r.handleError(new Error("Key ID ".concat(d," not encountered in playlist. Key-system sessions ").concat(v.length,".")))}else r.log('Ignoring "'.concat(e.type,'" event with init data type: "').concat(t,'" for selected key-system ').concat(s))}).catch(function(e){return r.handleError(e)})}},r.onWaitingForKey=function(e){r.log('"'.concat(e.type,'" event'))},r.hls=e,r.config=e.config,r.registerListeners(),r}return d(t,e),o(t,[{key:"destroy",value:function(){this.onDestroying(),this.onMediaDetached();var e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}},{key:"registerListeners",value:function(){this.hls.on(ee.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(ee.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(ee.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(ee.DESTROYING,this.onDestroying,this)}},{key:"unregisterListeners",value:function(){this.hls.off(ee.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(ee.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(ee.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(ee.DESTROYING,this.onDestroying,this)}},{key:"getLicenseServerUrl",value:function(e){var t=this.config,r=t.drmSystems,i=t.widevineLicenseUrl,n=null==r?void 0:r[e];return n?n.licenseUrl:e===hi.WIDEVINE&&i?i:void 0}},{key:"getLicenseServerUrlOrThrow",value:function(e){var t=this.getLicenseServerUrl(e);if(void 0===t)throw new Error('no license server URL configured for key-system "'.concat(e,'"'));return t}},{key:"getServerCertificateUrl",value:function(e){var t=this.config.drmSystems,r=null==t?void 0:t[e];if(r)return r.serverCertificateUrl;this.log('No Server Certificate in config.drmSystems["'.concat(e,'"]'))}},{key:"attemptKeySystemAccess",value:function(e){var t=this,r=this.hls.levels,i=function(e,t,r){return!!e&&r.indexOf(e)===t},n=r.map(function(e){return e.audioCodec}).filter(i),a=r.map(function(e){return e.videoCodec}).filter(i);return n.length+a.length===0&&a.push("avc1.42e01e"),new Promise(function(r,i){var s=function(e){var o=e.shift();t.getMediaKeysPromise(o,n,a).then(function(e){return r({keySystem:o,mediaKeys:e})}).catch(function(t){e.length?s(e):i(t instanceof Eo?t:new Eo({type:J.KEY_SYSTEM_ERROR,details:Z.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))})};s(e)})}},{key:"requestMediaKeySystemAccess",value:function(e,t){var r=this.config.requestMediaKeySystemAccessFunc;if("function"!=typeof r){var i="Configured requestMediaKeySystemAccess is not a function ".concat(r);return null===ki&&"http:"===self.location.protocol&&(i="navigator.requestMediaKeySystemAccess is not available over insecure protocol ".concat(location.protocol)),Promise.reject(new Error(i))}return r(e,t)}},{key:"getMediaKeysPromise",value:function(e,t,r){var i,n=this,a=function(e,t,r,i){var n;switch(e){case hi.FAIRPLAY:n=["cenc","sinf"];break;case hi.WIDEVINE:case hi.PLAYREADY:n=["cenc"];break;case hi.CLEARKEY:n=["cenc","keyids"];break;default:throw new Error("Unknown key-system: ".concat(e))}return function(e,t,r,i){return[{initDataTypes:e,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:t.map(function(e){return{contentType:"audio/mp4; codecs=".concat(e),robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null}}),videoCapabilities:r.map(function(e){return{contentType:"video/mp4; codecs=".concat(e),robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}})}]}(n,t,r,i)}(e,t,r,this.config.drmSystemOptions||{}),s=this.keySystemAccessPromises[e],o=null==(i=s)?void 0:i.keySystemAccess;if(!o){this.log('Requesting encrypted media "'.concat(e,'" key-system access with config: ').concat(Kt(a))),o=this.requestMediaKeySystemAccess(e,a);var l=s=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(function(t){n.log('Failed to obtain access to key-system "'.concat(e,'": ').concat(t))}),o.then(function(t){n.log('Access for key-system "'.concat(t.keySystem,'" obtained'));var r=n.fetchServerCertificate(e);n.log('Create media-keys for "'.concat(e,'"'));var i=l.mediaKeys=t.createMediaKeys().then(function(t){return n.log('Media-keys created for "'.concat(e,'"')),l.hasMediaKeys=!0,r.then(function(r){return r?n.setMediaKeysServerCertificate(t,e,r):t})});return i.catch(function(t){n.error('Failed to create media-keys for "'.concat(e,'"}: ').concat(t))}),i})}return o.then(function(){return s.mediaKeys})}},{key:"createMediaKeySessionContext",value:function(e){var t=e.decryptdata,r=e.keySystem,i=e.mediaKeys;this.log('Creating key-system session "'.concat(r,'" keyId: ').concat(Ae(t.keyId||[])," keyUri: ").concat(t.uri));var n=i.createSession(),a={decryptdata:t,keySystem:r,mediaKeys:i,mediaKeysSession:n,keyStatus:"status-pending"};return this.mediaKeySessions.push(a),a}},{key:"renewKeySession",value:function(e){var t=e.decryptdata;if(t.pssh){var r=this.createMediaKeySessionContext(e),i=yo(t);this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(r,"cenc",t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}},{key:"updateKeySession",value:function(e,t){var r=e.mediaKeysSession;return this.log('Updating key-session "'.concat(r.sessionId,'" for keyId ').concat(Ae(e.decryptdata.keyId||[]),"\n } (data length: ").concat(t.byteLength,")")),r.update(t)}},{key:"getSelectedKeySystemFormats",value:function(){var e=this;return Object.keys(this.keySystemAccessPromises).map(function(t){return{keySystem:t,hasMediaKeys:e.keySystemAccessPromises[t].hasMediaKeys}}).filter(function(e){return!!e.hasMediaKeys}).map(function(e){return yi(e.keySystem)}).filter(function(e){return!!e})}},{key:"getKeySystemAccess",value:function(e){var t=this;return this.getKeySystemSelectionPromise(e).then(function(e){var r=e.keySystem,i=e.mediaKeys;return t.attemptSetMediaKeys(r,i)})}},{key:"selectKeySystem",value:function(e){var t=this;return new Promise(function(r,i){t.getKeySystemSelectionPromise(e).then(function(e){var t=e.keySystem,n=yi(t);n?r(n):i(new Error('Unable to find format for key-system "'.concat(t,'"')))}).catch(i)})}},{key:"selectKeySystemFormat",value:function(e){var t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log("Selecting key-system from fragment (sn: ".concat(e.sn," ").concat(e.type,": ").concat(e.level,") key formats ").concat(t.join(", "))),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}},{key:"getKeyFormatPromise",value:function(e){var t=Ti(this.config),r=e.map(mi).filter(function(e){return!!e&&-1!==t.indexOf(e)});return this.selectKeySystem(r)}},{key:"getKeyStatus",value:function(e){for(var t=this.mediaKeySessions,r=0;r<t.length;r++){var i=To(e,t[r]);if(i)return i}}},{key:"loadKey",value:function(e){var t=this,r=e.keyInfo.decryptdata,i=yo(r),n=this.bannedKeyIds[i];if(n||"internal-error"===this.getKeyStatus(r)){var a=ko(n||"internal-error",r);return this.handleError(a,e.frag),Promise.reject(a)}var s="(keyId: ".concat(i,' format: "').concat(r.keyFormat,'" method: ').concat(r.method," uri: ").concat(r.uri,")");this.log("Starting session for key ".concat(s));var o=this.keyIdToKeySessionPromise[i];if(!o){var l=this.getKeySystemForKeyPromise(r).then(function(i){var n=i.keySystem,a=i.mediaKeys;return t.throwIfDestroyed(),t.log("Handle encrypted media sn: ".concat(e.frag.sn," ").concat(e.frag.type,": ").concat(e.frag.level," using key ").concat(s)),t.attemptSetMediaKeys(n,a).then(function(){return t.throwIfDestroyed(),t.createMediaKeySessionContext({keySystem:n,mediaKeys:a,decryptdata:r})})}).then(function(e){var i=r.pssh?r.pssh.buffer:null;return t.generateRequestWithPreferredKeySession(e,"cenc",i,"playlist-key")});return l.catch(function(r){return t.handleError(r,e.frag)}),this.keyIdToKeySessionPromise[i]=l,l}return o.catch(function(i){if(i instanceof Eo){var n=fe({},i.data);"internal-error"===t.getKeyStatus(r)&&(n.decryptdata=r);var a=new Eo(n,i.message);t.handleError(a,e.frag)}}),o}},{key:"throwIfDestroyed",value:function(){if(!this.hls)throw new Error("invalid state")}},{key:"handleError",value:function(e,t){if(this.hls)if(e instanceof Eo){t&&(e.data.frag=t);var r=e.data.decryptdata;this.error("".concat(e.message).concat(r?" (".concat(Ae(r.keyId||[]),")"):"")),this.hls.trigger(ee.ERROR,e.data)}else this.error(e.message),this.hls.trigger(ee.ERROR,{type:J.KEY_SYSTEM_ERROR,details:Z.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}},{key:"getKeySystemForKeyPromise",value:function(e){var t=yo(e),r=this.keyIdToKeySessionPromise[t];if(!r){var i=mi(e.keyFormat),n=i?[i]:Ti(this.config);return this.attemptKeySystemAccess(n)}return r}},{key:"getKeySystemSelectionPromise",value:function(e){if(e.length||(e=Ti(this.config)),0===e.length)throw new Eo({type:J.KEY_SYSTEM_ERROR,details:Z.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},"Missing key-system license configuration options ".concat(Kt({drmSystems:this.config.drmSystems})));return this.attemptKeySystemAccess(e)}},{key:"attemptSetMediaKeys",value:function(e,t){var r=this;if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();var i=this.setMediaKeysQueue.slice();this.log('Setting media-keys for "'.concat(e,'"'));var n=Promise.all(i).then(function(){return r.media?r.media.setMediaKeys(t):new Promise(function(e,i){r.mediaResolved=function(){if(r.mediaResolved=void 0,!r.media)return i(new Error("Attempted to set mediaKeys without media element attached"));r.mediaKeys=t,r.media.setMediaKeys(t).then(e).catch(i)}})});return this.mediaKeys=t,this.setMediaKeysQueue.push(n),n.then(function(){r.log('Media-keys set for "'.concat(e,'"')),i.push(n),r.setMediaKeysQueue=r.setMediaKeysQueue.filter(function(e){return-1===i.indexOf(e)})})}},{key:"generateRequestWithPreferredKeySession",value:function(e,t,r,i){var n,a=this,s=null==(n=this.config.drmSystems)||null==(n=n[e.keySystem])?void 0:n.generateRequest;if(s)try{var o=s.call(this.hls,t,r,e);if(!o)throw new Error("Invalid response from configured generateRequest filter");t=o.initDataType,r=o.initData?o.initData:null,e.decryptdata.pssh=r?new Uint8Array(r):null}catch(e){if(this.warn(e.message),this.hls&&this.hls.config.debug)throw e}if(null===r)return this.log('Skipping key-session request for "'.concat(i,'" (no initData)')),Promise.resolve(e);var l=yo(e.decryptdata),u=e.decryptdata.uri;this.log('Generating key-session request for "'.concat(i,'" keyId: ').concat(l," URI: ").concat(u," (init data type: ").concat(t," length: ").concat(r.byteLength,")"));var c=new Pn,d=e._onmessage=function(t){var r=e.mediaKeysSession;if(r){var i=t.messageType,n=t.message;a.log('"'.concat(i,'" message event for session "').concat(r.sessionId,'" message size: ').concat(n.byteLength)),"license-request"===i||"license-renewal"===i?a.renewLicense(e,n).catch(function(e){c.eventNames().length?c.emit("error",e):a.handleError(e)}):"license-release"===i?e.keySystem===hi.FAIRPLAY&&a.updateKeySession(e,li("acknowledged")).then(function(){return a.removeSession(e)}).catch(function(e){return a.handleError(e)}):a.warn('unhandled media key message type "'.concat(i,'"'))}else c.emit("error",new Error("invalid state"))},h=function(e,t){var r;t.keyStatus=e,e.startsWith("usable")?c.emit("resolved"):"internal-error"===e||"output-restricted"===e||"output-downscaled"===e?r=ko(e,t.decryptdata):"expired"===e?r=new Error("key expired (keyId: ".concat(l,")")):"released"===e?r=new Error("key released"):"status-pending"===e||a.warn('unhandled key status change "'.concat(e,'" (keyId: ').concat(l,")")),r&&(c.eventNames().length?c.emit("error",r):a.handleError(r))},f=e._onkeystatuseschange=function(t){if(e.mediaKeysSession){var r=a.getKeyStatuses(e);if(Object.keys(r).some(function(e){return"status-pending"!==r[e]})){if("expired"===r[l])return a.log("Expired key ".concat(Kt(r),' in key-session "').concat(e.mediaKeysSession.sessionId,'"')),void a.renewKeySession(e);var i=r[l];if(i)h(i,e);else{var n;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(n=e.keyStatusTimeouts)[l]||(n[l]=self.setTimeout(function(){if(e.mediaKeysSession&&a.mediaKeys){var t=a.getKeyStatus(e.decryptdata);if(t&&"status-pending"!==t)return a.log("No status for keyId ".concat(l,' in key-session "').concat(e.mediaKeysSession.sessionId,'". Using session key-status ').concat(t," from other session.")),h(t,e);a.log("key status for ".concat(l,' in key-session "').concat(e.mediaKeysSession.sessionId,'" timed out after ').concat(1e3,"ms")),h(i="internal-error",e)}},1e3)),a.log("No status for keyId ".concat(l," (").concat(Kt(r),")."))}}}else c.emit("error",new Error("invalid state"))};ln(e.mediaKeysSession,"message",d),ln(e.mediaKeysSession,"keystatuseschange",f);var v=new Promise(function(e,t){c.on("error",t),c.on("resolved",e)});return e.mediaKeysSession.generateRequest(t,r).then(function(){a.log('Request generated for key-session "'.concat(e.mediaKeysSession.sessionId,'" keyId: ').concat(l," URI: ").concat(u))}).catch(function(t){throw new Eo({type:J.KEY_SYSTEM_ERROR,details:Z.KEY_SYSTEM_NO_SESSION,error:t,decryptdata:e.decryptdata,fatal:!1},"Error generating key-session request: ".concat(t))}).then(function(){return v}).catch(function(t){return c.removeAllListeners(),a.removeSession(e).then(function(){throw t})}).then(function(){return c.removeAllListeners(),e})}},{key:"getKeyStatuses",value:function(e){var t=this,r={};return e.mediaKeysSession.keyStatuses.forEach(function(i,n){if("string"==typeof n&&"object"===S(i)){var a=n;n=i,i=a}var s="buffer"in n?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n);e.keySystem===hi.PLAYREADY&&16===s.length&&ui(s);var o=Ae(s);"internal-error"===i&&(t.bannedKeyIds[o]=i),t.log('key status change "'.concat(i,'" for keyStatuses keyId: ').concat(o,' key-session "').concat(e.mediaKeysSession.sessionId,'"')),r[o]=i}),r}},{key:"fetchServerCertificate",value:function(e){var t=this.config,r=new(0,t.loader)(t),i=this.getServerCertificateUrl(e);return i?(this.log('Fetching server certificate for "'.concat(e,'"')),new Promise(function(n,a){var s={responseType:"arraybuffer",url:i},o=t.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:function(e,t,r,i){n(e.data)},onError:function(t,r,n,o){a(new Eo({type:J.KEY_SYSTEM_ERROR,details:Z.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:n,response:fe({url:s.url,data:void 0},t)},'"'.concat(e,'" certificate request failed (').concat(i,"). Status: ").concat(t.code," (").concat(t.text,")")))},onTimeout:function(t,r,n){a(new Eo({type:J.KEY_SYSTEM_ERROR,details:Z.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:n,response:{url:s.url,data:void 0}},'"'.concat(e,'" certificate request timed out (').concat(i,")")))},onAbort:function(e,t,r){a(new Error("aborted"))}};r.load(s,l,u)})):Promise.resolve()}},{key:"setMediaKeysServerCertificate",value:function(e,t,r){var i=this;return new Promise(function(n,a){e.setServerCertificate(r).then(function(a){i.log("setServerCertificate ".concat(a?"success":"not supported by CDM"," (").concat(r.byteLength,') on "').concat(t,'"')),n(e)}).catch(function(e){a(new Eo({type:J.KEY_SYSTEM_ERROR,details:Z.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))})})}},{key:"renewLicense",value:function(e,t){var r=this;return this.requestLicense(e,new Uint8Array(t)).then(function(t){return r.updateKeySession(e,new Uint8Array(t)).catch(function(t){throw new Eo({type:J.KEY_SYSTEM_ERROR,details:Z.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:t,fatal:!1},t.message)})})}},{key:"unpackPlayReadyKeyMessage",value:function(e,t){var r=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!r.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;var i=(new DOMParser).parseFromString(r,"application/xml"),n=i.querySelectorAll("HttpHeader");if(n.length>0)for(var a,s=0,o=n.length;s<o;s++){var l,u,c=null==(l=(a=n[s]).querySelector("name"))?void 0:l.textContent,d=null==(u=a.querySelector("value"))?void 0:u.textContent;c&&d&&e.setRequestHeader(c,d)}var h=i.querySelector("Challenge"),f=null==h?void 0:h.textContent;if(!f)throw new Error("Cannot find <Challenge> in key message");return li(atob(f))}},{key:"setupLicenseXHR",value:function(e,t,r,i){var n=this,a=this.config.licenseXhrSetup;return a?Promise.resolve().then(function(){if(!r.decryptdata)throw new Error("Key removed");return a.call(n.hls,e,t,r,i)}).catch(function(s){if(!r.decryptdata)throw s;return e.open("POST",t,!0),a.call(n.hls,e,t,r,i)}).then(function(r){return e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:r||i}}):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:i}))}},{key:"requestLicense",value:function(e,t){var r=this,i=this.config.keyLoadPolicy.default;return new Promise(function(n,a){var s=r.getLicenseServerUrlOrThrow(e.keySystem);r.log("Sending license request to URL: ".concat(s));var o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=function(){if(!r.hls||!e.mediaKeysSession)return a(new Error("invalid state"));if(4===o.readyState)if(200===o.status){r._requestLicenseFailureCount=0;var l=o.response;r.log("License received ".concat(l instanceof ArrayBuffer?l.byteLength:l));var u=r.config.licenseResponseCallback;if(u)try{l=u.call(r.hls,o,s,e)}catch(e){r.error(e)}n(l)}else{var c=i.errorRetry,d=c?c.maxNumRetry:0;if(r._requestLicenseFailureCount++,r._requestLicenseFailureCount>d||o.status>=400&&o.status<500)a(new Eo({type:J.KEY_SYSTEM_ERROR,details:Z.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:o,response:{url:s,data:void 0,code:o.status,text:o.statusText}},"License Request XHR failed (".concat(s,"). Status: ").concat(o.status," (").concat(o.statusText,")")));else{var h=d-r._requestLicenseFailureCount+1;r.warn("Retrying license request, ".concat(h," attempts left")),r.requestLicense(e,t).then(n,a)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,r.setupLicenseXHR(o,s,e,t).then(function(t){var i=t.xhr,n=t.licenseChallenge;e.keySystem==hi.PLAYREADY&&(n=r.unpackPlayReadyKeyMessage(i,n)),i.send(n)}).catch(a)})}},{key:"onDestroying",value:function(){this.unregisterListeners(),this._clear()}},{key:"onMediaAttached",value:function(e,t){if(this.config.emeEnabled){var r=t.media;this.media=r,ln(r,"encrypted",this.onMediaEncrypted),ln(r,"waitingforkey",this.onWaitingForKey);var i=this.mediaResolved;i?i():this.mediaKeys=r.mediaKeys}}},{key:"onMediaDetached",value:function(){var e=this.media;e&&(un(e,"encrypted",this.onMediaEncrypted),un(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}},{key:"_clear",value:function(){var e,r=this;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};var i=this.mediaResolved;if(i&&i(),this.mediaKeys||this.mediaKeySessions.length){var n=this.media,a=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,Ai.clearKeyUriToKeyIdMap();var s=a.length;t.CDMCleanupPromise=Promise.all(a.map(function(e){return r.removeSession(e)}).concat((null==n||null==(e=n.setMediaKeys(null))?void 0:e.catch(function(e){r.log("Could not clear media keys: ".concat(e)),r.hls&&r.hls.trigger(ee.ERROR,{type:J.OTHER_ERROR,details:Z.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error("Could not clear media keys: ".concat(e))})}))||Promise.resolve())).catch(function(e){r.log("Could not close sessions and clear media keys: ".concat(e)),r.hls&&r.hls.trigger(ee.ERROR,{type:J.OTHER_ERROR,details:Z.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error("Could not close sessions and clear media keys: ".concat(e))})}).then(function(){s&&r.log("finished closing key sessions and clearing media keys")})}}},{key:"onManifestLoading",value:function(){this._clear()}},{key:"onManifestLoaded",value:function(e,t){var r=t.sessionKeys;if(r&&this.config.emeEnabled&&!this.keyFormatPromise){var i=r.reduce(function(e,t){return-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e},[]);this.log("Selecting key-system from session-keys ".concat(i.join(", "))),this.keyFormatPromise=this.getKeyFormatPromise(i)}}},{key:"removeSession",value:function(e){var t=this,r=e.mediaKeysSession,i=e.licenseXhr,n=e.decryptdata;if(r){this.log('Remove licenses and keys and close session "'.concat(r.sessionId,'" keyId: ').concat(Ae((null==n?void 0:n.keyId)||[]))),e._onmessage&&(r.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(r.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;var a=this.mediaKeySessions.indexOf(e);a>-1&&this.mediaKeySessions.splice(a,1);var s=e.keyStatusTimeouts;s&&Object.keys(s).forEach(function(e){return self.clearTimeout(s[e])});var o=function(e){var t;return!(!e||"persistent-license"!==e.sessionType&&(null==(t=e.sessionTypes)||!t.some(function(e){return"persistent-license"===e})))}(this.config.drmSystemOptions)?new Promise(function(e,t){self.setTimeout(function(){return t(new Error("MediaKeySession.remove() timeout"))},8e3),r.remove().then(e).catch(t)}):Promise.resolve();return o.catch(function(e){t.log("Could not remove session: ".concat(e)),t.hls&&t.hls.trigger(ee.ERROR,{type:J.OTHER_ERROR,details:Z.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error("Could not remove session: ".concat(e))})}).then(function(){return r.close()}).catch(function(e){t.log("Could not close session: ".concat(e)),t.hls&&t.hls.trigger(ee.ERROR,{type:J.OTHER_ERROR,details:Z.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error("Could not close session: ".concat(e))})})}return Promise.resolve()}}])}(ve);function yo(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(null===e.keyId)throw new Error("keyId is null");return Ae(e.keyId)}function To(e,t){return e.keyId&&t.mediaKeysSession.keyStatuses.has(e.keyId)?t.mediaKeysSession.keyStatuses.get(e.keyId):e.matches(t.decryptdata)?t.keyStatus:void 0}mo.CDMCleanupPromise=void 0;var Eo=function(e){function t(e,r){var i;return a(this,t),(i=n(this,t,[r])).data=void 0,e.error||(e.error=new Error(r)),i.data=e,e.err=e.error,i}return d(t,e),o(t)}(L(Error));function ko(e,t){var r="output-restricted"===e,i=r?Z.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:Z.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Eo({type:J.KEY_SYSTEM_ERROR,details:i,fatal:!1,decryptdata:t},r?"HDCP level output restricted":'key status changed to "'.concat(e,'"'))}var So=function(){return o(function e(t){a(this,e),this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=t,this.registerListeners()},[{key:"setStreamController",value:function(e){this.streamController=e}},{key:"registerListeners",value:function(){this.hls.on(ee.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(ee.MEDIA_DETACHING,this.onMediaDetaching,this)}},{key:"unregisterListeners",value:function(){this.hls.off(ee.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(ee.MEDIA_DETACHING,this.onMediaDetaching,this)}},{key:"destroy",value:function(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}},{key:"onMediaAttaching",value:function(e,t){var r=this.hls.config;if(r.capLevelOnFPSDrop){var i=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=i,i&&"function"==typeof i.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}}},{key:"onMediaDetaching",value:function(){this.media=null}},{key:"checkFPS",value:function(e,t,r){var i=performance.now();if(t){if(this.lastTime){var n=i-this.lastTime,a=r-this.lastDroppedFrames,s=t-this.lastDecodedFrames,o=1e3*a/n,l=this.hls;if(l.trigger(ee.FPS_DROP,{currentDropped:a,currentDecoded:s,totalDroppedFrames:r}),o>0&&a>l.config.fpsDroppedMonitoringThreshold*s){var u=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(-1===l.autoLevelCapping||l.autoLevelCapping>=u)&&(u-=1,l.trigger(ee.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:l.currentLevel}),l.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=r,this.lastDecodedFrames=t}}},{key:"checkFPSInterval",value:function(){var e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){var t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}])}();function bo(e,t){var r;try{r=new Event("addtrack")}catch(e){(r=document.createEvent("Event")).initEvent("addtrack",!1,!1)}r.track=e,t.dispatchEvent(r)}function Ao(e,t){var r=e.mode;if("disabled"===r&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error("addCue is failed for: ".concat(t))}catch(r){Ee.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){Ee.debug("[texttrack-utils]: Legacy TextTrackCue fallback failed: ".concat(e))}}"disabled"===r&&(e.mode=r)}function Lo(e,t){var r=e.mode;if("disabled"===r&&(e.mode="hidden"),e.cues)for(var i=e.cues.length;i--;)t&&e.cues[i].removeEventListener("enter",t),e.removeCue(e.cues[i]);"disabled"===r&&(e.mode=r)}function Ro(e,t,r,i){var n=e.mode;if("disabled"===n&&(e.mode="hidden"),e.cues&&e.cues.length>0)for(var a=function(e,t,r){var i=[],n=function(e,t){if(t<=e[0].startTime)return 0;var r=e.length-1;if(t>e[r].endTime)return-1;var i,n=0,a=r;for(;n<=a;)if(t<e[i=Math.floor((a+n)/2)].startTime)a=i-1;else{if(!(t>e[i].startTime&&n<r))return i;n=i+1}return e[n].startTime-t<t-e[a].startTime?n:a}(e,t);if(n>-1)for(var a=n,s=e.length;a<s;a++){var o=e[a];if(o.startTime>=t&&o.endTime<=r)i.push(o);else if(o.startTime>r)return i}return i}(e.cues,t,r),s=0;s<a.length;s++)i&&!i(a[s])||e.removeCue(a[s]);"disabled"===n&&(e.mode=n)}function Io(e){for(var t=[],r=0;r<e.length;r++){var i=e[r];"subtitles"!==i.kind&&"captions"!==i.kind||!i.label||t.push(e[r])}return t}var wo=function(e){function t(e){var r;return a(this,t),(r=n(this,t,[e,"subtitle-track-controller"])).media=null,r.tracks=[],r.groupIds=null,r.tracksInGroup=[],r.trackId=-1,r.currentTrack=null,r.selectDefaultTrack=!0,r.queuedDefaultTrack=-1,r.useTextTrackPolling=!1,r.subtitlePollingInterval=-1,r._subtitleDisplay=!0,r.asyncPollTrackChange=function(){return r.pollTrackChange(0)},r.onTextTracksChanged=function(){if(r.useTextTrackPolling||self.clearInterval(r.subtitlePollingInterval),r.media&&r.hls.config.renderTextTracksNatively){for(var e=null,t=Io(r.media.textTracks),i=0;i<t.length;i++)if("hidden"===t[i].mode)e=t[i];else if("showing"===t[i].mode){e=t[i];break}var n=r.findTrackForTextTrack(e);r.subtitleTrack!==n&&r.setSubtitleTrack(n)}},r.registerListeners(),r}return d(t,e),o(t,[{key:"destroy",value:function(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,T(t,"destroy",this,3)([])}},{key:"subtitleDisplay",get:function(){return this._subtitleDisplay},set:function(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}},{key:"registerListeners",value:function(){var e=this.hls;e.on(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.MANIFEST_PARSED,this.onManifestParsed,this),e.on(ee.LEVEL_LOADING,this.onLevelLoading,this),e.on(ee.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(ee.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(ee.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.MANIFEST_PARSED,this.onManifestParsed,this),e.off(ee.LEVEL_LOADING,this.onLevelLoading,this),e.off(ee.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(ee.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(ee.ERROR,this.onError,this)}},{key:"onMediaAttached",value:function(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}},{key:"pollTrackChange",value:function(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}},{key:"onMediaDetaching",value:function(e,t){var r=this.media;if(r){var i=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||r.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,!i)Io(r.textTracks).forEach(function(e){Lo(e)})}}},{key:"onManifestLoading",value:function(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}},{key:"onManifestParsed",value:function(e,t){this.tracks=t.subtitleTracks}},{key:"onSubtitleTrackLoaded",value:function(e,t){var r=t.id,i=t.groupId,n=t.details,a=this.tracksInGroup[r];if(a&&a.groupId===i){var s=a.details;a.details=t.details,this.log("Subtitle track ".concat(r,' "').concat(a.name,'" lang:').concat(a.lang," group:").concat(i," loaded [").concat(n.startSN,"-").concat(n.endSN,"]")),r===this.trackId&&this.playlistLoaded(r,t,s)}else this.warn("Subtitle track with id:".concat(r," and group:").concat(i," not found in active group ").concat(null==a?void 0:a.groupId))}},{key:"onLevelLoading",value:function(e,t){this.switchLevel(t.level)}},{key:"onLevelSwitching",value:function(e,t){this.switchLevel(t.level)}},{key:"switchLevel",value:function(e){var t=this.hls.levels[e];if(t){var r=t.subtitleGroups||null,i=this.groupIds,n=this.currentTrack;if(!r||(null==i?void 0:i.length)!==(null==r?void 0:r.length)||null!=r&&r.some(function(e){return-1===(null==i?void 0:i.indexOf(e))})){this.groupIds=r,this.trackId=-1,this.currentTrack=null;var a=this.tracks.filter(function(e){return!r||-1!==r.indexOf(e.groupId)});if(a.length)this.selectDefaultTrack&&!a.some(function(e){return e.default})&&(this.selectDefaultTrack=!1),a.forEach(function(e,t){e.id=t});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=a;var s=this.hls.config.subtitlePreference;if(!n&&s){this.selectDefaultTrack=!1;var o=Yt(s,a);if(o>-1)n=a[o];else{var l=Yt(s,this.tracks);n=this.tracks[l]}}var u=this.findTrackId(n);-1===u&&n&&(u=this.findTrackId(null));var c={subtitleTracks:a};this.log("Updating subtitle tracks, ".concat(a.length,' track(s) found in "').concat(null==r?void 0:r.join(","),'" group-id')),this.hls.trigger(ee.SUBTITLE_TRACKS_UPDATED,c),-1!==u&&-1===this.trackId&&this.setSubtitleTrack(u)}}}},{key:"findTrackId",value:function(e){for(var t=this.tracksInGroup,r=this.selectDefaultTrack,i=0;i<t.length;i++){var n=t[i];if((!r||n.default)&&(r||e)&&(!e||zt(n,e)))return i}if(e){for(var a=0;a<t.length;a++){var s=t[a];if(ls(e.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return a}for(var o=0;o<t.length;o++){var l=t[o];if(ls(e.attrs,l.attrs,["LANGUAGE"]))return o}}return-1}},{key:"findTrackForTextTrack",value:function(e){if(e)for(var t=this.tracksInGroup,r=0;r<t.length;r++){if(us(t[r],e))return r}return-1}},{key:"onError",value:function(e,t){!t.fatal&&t.context&&(t.context.type!==ne||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))}},{key:"allSubtitleTracks",get:function(){return this.tracks}},{key:"subtitleTracks",get:function(){return this.tracksInGroup}},{key:"subtitleTrack",get:function(){return this.trackId},set:function(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}},{key:"setSubtitleOption",value:function(e){if(this.hls.config.subtitlePreference=e,e){if(-1===e.id)return this.setSubtitleTrack(-1),null;var t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){var r=this.currentTrack;if(r&&zt(e,r))return r;var i=Yt(e,this.tracksInGroup);if(i>-1){var n=this.tracksInGroup[i];return this.setSubtitleTrack(i),n}if(r)return null;var a=Yt(e,t);if(a>-1)return t[a]}}return null}},{key:"loadPlaylist",value:function(e){T(t,"loadPlaylist",this,3)([]),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}},{key:"loadingPlaylist",value:function(e,r){T(t,"loadingPlaylist",this,3)([e,r]);var i=e.id,n=e.groupId,a=this.getUrlWithDirectives(e.url,r),s=e.details,o=null==s?void 0:s.age;this.log("Loading subtitle ".concat(i,' "').concat(e.name,'" lang:').concat(e.lang," group:").concat(n).concat(void 0!==(null==r?void 0:r.msn)?" at sn "+r.msn+" part "+r.part:"").concat(o&&s.live?" age "+o.toFixed(1)+(s.type&&" "+s.type||""):""," ").concat(a)),this.hls.trigger(ee.SUBTITLE_TRACK_LOADING,{url:a,id:i,groupId:n,deliveryDirectives:r||null,track:e})}},{key:"toggleTrackModes",value:function(){var e=this.media;if(e){var t,r=Io(e.textTracks),i=this.currentTrack;if(i&&((t=r.filter(function(e){return us(i,e)})[0])||this.warn('Unable to find subtitle TextTrack with name "'.concat(i.name,'" and language "').concat(i.lang,'"'))),[].slice.call(r).forEach(function(e){"disabled"!==e.mode&&e!==t&&(e.mode="disabled")}),t){var n=this.subtitleDisplay?"showing":"hidden";t.mode!==n&&(t.mode=n)}}}},{key:"setSubtitleTrack",value:function(e){var t=this.tracksInGroup;if(this.media)if(e<-1||e>=t.length||!X(e))this.warn("Invalid subtitle track id: ".concat(e));else{this.selectDefaultTrack=!1;var r=this.currentTrack,i=t[e]||null;if(this.trackId=e,this.currentTrack=i,this.toggleTrackModes(),i){var n=!!i.details&&!i.details.live;if(e!==this.trackId||i!==r||!n){this.log("Switching to subtitle-track ".concat(e)+(i?' "'.concat(i.name,'" lang:').concat(i.lang," group:").concat(i.groupId):""));var a=i.id,s=i.groupId,o=void 0===s?"":s,l=i.name,u=i.type,c=i.url;this.hls.trigger(ee.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:l,type:u,url:c});var d=this.switchParams(i.url,null==r?void 0:r.details,i.details);this.loadPlaylist(d)}}else this.hls.trigger(ee.SUBTITLE_TRACK_SWITCH,{id:e})}else this.queuedDefaultTrack=e}}])}(ss);function Po(e){for(var t=5381,r=e.length;r;)t=33*t^e.charCodeAt(--r);return(t>>>0).toString()}var Do=.025,xo=function(e){return e[e.Point=0]="Point",e[e.Range=1]="Range",e}({});function Co(e,t,r){return"".concat(e.identifier,"-").concat(r+1,"-").concat(Po(t))}var _o=function(){return o(function e(t,r){a(this,e),this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=r,this.dateRange=t,this.setDateRange(t)},[{key:"setDateRange",value:function(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}},{key:"reset",value:function(){var e;this.appendInPlaceStarted=!1,null==(e=this.assetListLoader)||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}},{key:"isAssetPastPlayoutLimit",value:function(e){var t;if(e>0&&e>=this.assetList.length)return!0;var r=this.playoutLimit;return!(e<=0||isNaN(r))&&(0===r||((null==(t=this.assetList[e])?void 0:t.startOffset)||0)>r)}},{key:"findAssetIndex",value:function(e){return this.assetList.indexOf(e)}},{key:"identifier",get:function(){return this.dateRange.id}},{key:"startDate",get:function(){return this.dateRange.startDate}},{key:"startTime",get:function(){var e=this.dateRange.startTime;if(this.snapOptions.out){var t=this.dateRange.tagAnchor;if(t)return Mo(e,t)}return e}},{key:"startOffset",get:function(){return this.cue.pre?0:this.startTime}},{key:"startIsAligned",get:function(){if(0===this.startTime||this.snapOptions.out)return!0;var e=this.dateRange.tagAnchor;if(e){var t=this.dateRange.startTime;return t-Mo(t,e)<.1}return!1}},{key:"resumptionOffset",get:function(){var e=this.resumeOffset,t=X(e)?e:this.duration;return this.cumulativeDuration+t}},{key:"resumeTime",get:function(){var e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){var t=this.resumeAnchor;if(t)return Mo(e,t)}return e}},{key:"appendInPlace",get:function(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||!this.startIsAligned||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<Do))},set:function(e){this.appendInPlaceStarted?this.resetOnResume=!e:this.appendInPlaceDisabled=!e}},{key:"timelineStart",get:function(){return null!==this._timelineStart?this._timelineStart:this.startTime},set:function(e){this._timelineStart=e}},{key:"duration",get:function(){var e,t=this.playoutLimit;return e=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(t)&&t<e&&(e=t),e},set:function(e){this._duration=e}},{key:"cue",get:function(){return this.dateRange.cue}},{key:"timelineOccupancy",get:function(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?xo.Range:xo.Point}},{key:"supplementsPrimary",get:function(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}},{key:"contentMayVary",get:function(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}},{key:"assetUrl",get:function(){return this.dateRange.attr["X-ASSET-URI"]}},{key:"assetListUrl",get:function(){return this.dateRange.attr["X-ASSET-LIST"]}},{key:"baseUrl",get:function(){return this.base.url}},{key:"assetListLoaded",get:function(){return this.assetList.length>0||null!==this.assetListResponse}},{key:"toString",value:function(){return'["'.concat((e=this).identifier,'" ').concat(e.cue.pre?"<pre>":e.cue.post?"<post>":"").concat(e.timelineStart.toFixed(2),"-").concat(e.resumeTime.toFixed(2),"]");var e}}])}();function Mo(e,t){return e-t.start<t.duration/2&&!(Math.abs(e-(t.start+t.duration))<Do)?t.start:t.start+t.duration}function Oo(e,t,r){var i=new self.URL(e,r);return"data:"!==i.protocol&&i.searchParams.set("_HLS_primary_id",t),i}function Fo(e,t){for(;null!=(r=e.assetList[++t])&&r.error;)var r;return t}function Uo(e){var t=e.timelineStart,r=e.duration||0;return'["'.concat(e.identifier,'" ').concat(t.toFixed(2),"-").concat((t+r).toFixed(2),"]")}var No=function(){return o(function e(t,r,i,n){var s=this;a(this,e),this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=function(){s.reachedPlayout(s.currentTime)&&s.hls&&s.hls.trigger(ee.PLAYOUT_LIMIT_REACHED,{})};var o=this.hls=new t(r);this.interstitial=i,this.assetItem=n;var l=function(){s.hasDetails=!0};o.once(ee.LEVEL_LOADED,l),o.once(ee.AUDIO_TRACK_LOADED,l),o.once(ee.SUBTITLE_TRACK_LOADED,l),o.on(ee.MEDIA_ATTACHING,function(e,t){var r=t.media;s.removeMediaListeners(),s.mediaAttached=r,s.interstitial.playoutLimit&&(r.addEventListener("timeupdate",s.checkPlayout),s.appendInPlace&&o.on(ee.BUFFER_APPENDED,function(){var e=s.bufferedEnd;s.reachedPlayout(e)&&(s._bufferedEosTime=e,o.trigger(ee.BUFFERED_TO_END,void 0))}))})},[{key:"appendInPlace",get:function(){return this.interstitial.appendInPlace}},{key:"loadSource",value:function(){var e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{var t=this.assetItem.uri;try{t=Oo(t,e.config.primarySessionId||"").href}catch(e){}e.loadSource(t)}}},{key:"bufferedInPlaceToEnd",value:function(e){var t;if(!this.appendInPlace)return!1;if(null!=(t=this.hls)&&t.bufferedToEnd)return!0;if(!e)return!1;var r=Math.min(this._bufferedEosTime||1/0,this.duration),i=this.timelineOffset,n=jr.bufferInfo(e,i,0);return this.getAssetTime(n.end)>=r-.02}},{key:"reachedPlayout",value:function(e){var t=this.interstitial.playoutLimit;return this.startOffset+e>=t}},{key:"destroyed",get:function(){var e;return!(null!=(e=this.hls)&&e.userConfig)}},{key:"assetId",get:function(){return this.assetItem.identifier}},{key:"interstitialId",get:function(){return this.assetItem.parentIdentifier}},{key:"media",get:function(){var e;return(null==(e=this.hls)?void 0:e.media)||null}},{key:"bufferedEnd",get:function(){var e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;var t=jr.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}},{key:"currentTime",get:function(){var e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}},{key:"duration",get:function(){var e=this.assetItem.duration;if(!e)return 0;var t=this.interstitial.playoutLimit;if(t){var r=t-this.startOffset;if(r>0&&r<e)return r}return e}},{key:"remaining",get:function(){var e=this.duration;return e?Math.max(0,e-this.currentTime):0}},{key:"startOffset",get:function(){return this.assetItem.startOffset}},{key:"timelineOffset",get:function(){var e;return(null==(e=this.hls)?void 0:e.config.timelineOffset)||0},set:function(e){var t=this.timelineOffset;if(e!==t){var r=e-t;if(Math.abs(r)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}},{key:"getAssetTime",value:function(e){var t=this.timelineOffset,r=this.duration;return Math.min(Math.max(0,e-t),r)}},{key:"removeMediaListeners",value:function(){var e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}},{key:"bufferSnapShot",value:function(){var e;this.mediaAttached&&(null!=(e=this.hls)&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd))}},{key:"destroy",value:function(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}},{key:"attachMedia",value:function(e){var t;this.loadSource(),null==(t=this.hls)||t.attachMedia(e)}},{key:"detachMedia",value:function(){var e;this.removeMediaListeners(),this.mediaAttached=null,null==(e=this.hls)||e.detachMedia()}},{key:"resumeBuffering",value:function(){var e;null==(e=this.hls)||e.resumeBuffering()}},{key:"pauseBuffering",value:function(){var e;null==(e=this.hls)||e.pauseBuffering()}},{key:"transferMedia",value:function(){var e;return this.bufferSnapShot(),(null==(e=this.hls)?void 0:e.transferMedia())||null}},{key:"resetDetails",value:function(){var e=this.hls;if(e&&this.hasDetails){e.stopLoad();var t=function(e){return delete e.details};e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}},{key:"on",value:function(e,t,r){var i;null==(i=this.hls)||i.on(e,t)}},{key:"once",value:function(e,t,r){var i;null==(i=this.hls)||i.once(e,t)}},{key:"off",value:function(e,t,r){var i;null==(i=this.hls)||i.off(e,t)}},{key:"toString",value:function(){var e;return"HlsAssetPlayer: ".concat(Uo(this.assetItem)," ").concat(null==(e=this.hls)?void 0:e.sessionId," ").concat(this.appendInPlace?"append-in-place":"")}}])}(),Bo=function(e){function t(e,r){var i;return a(this,t),(i=n(this,t,["interstitials-sched",r])).onScheduleUpdate=void 0,i.eventMap={},i.events=null,i.items=null,i.durations={primary:0,playout:0,integrated:0},i.onScheduleUpdate=e,i}return d(t,e),o(t,[{key:"destroy",value:function(){this.reset(),this.onScheduleUpdate=null}},{key:"reset",value:function(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(function(e){return e.reset()}),this.events=this.items=null}},{key:"resetErrorsInRange",value:function(e,t){return this.events?this.events.reduce(function(r,i){return e<=i.startOffset&&t>i.startOffset?(delete i.error,r+1):r},0):0}},{key:"duration",get:function(){var e=this.items;return e?e[e.length-1].end:0}},{key:"length",get:function(){return this.items?this.items.length:0}},{key:"getEvent",value:function(e){return e&&this.eventMap[e]||null}},{key:"hasEvent",value:function(e){return e in this.eventMap}},{key:"findItemIndex",value:function(e,t){if(e.event)return this.findEventIndex(e.event.identifier);var r=-1;e.nextEvent?r=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(r=this.findEventIndex(e.previousEvent.identifier)+1);var i=this.items;if(i)for(i[r]||(void 0===t&&(t=e.start),r=this.findItemIndexAtTime(t));r>=0&&null!=(n=i[r])&&n.event;){var n;r--}return r}},{key:"findItemIndexAtTime",value:function(e,t){var r=this.items;if(r)for(var i=0;i<r.length;i++){var n=r[i];if(t&&"primary"!==t&&(n=n[t]),e===n.start||e>n.start&&e<n.end)return i}return-1}},{key:"findJumpRestrictedIndex",value:function(e,t){var r=this.items;if(r)for(var i=e;i<=t&&r[i];i++){var n=r[i].event;if(null!=n&&n.restrictions.jump&&!n.appendInPlace)return i}return-1}},{key:"findEventIndex",value:function(e){var t=this.items;if(t)for(var r=t.length;r--;){var i;if((null==(i=t[r].event)?void 0:i.identifier)===e)return r}return-1}},{key:"findAssetIndex",value:function(e,t){var r=e.assetList,i=r.length;if(i>1)for(var n=0;n<i;n++){var a=r[n];if(!a.error){var s=a.timelineStart;if(t===s||t>s&&(t<s+(a.duration||0)||n===i-1))return n}}return 0}},{key:"assetIdAtEnd",get:function(){var e,t=null==(e=this.items)||null==(e=e[this.length-1])?void 0:e.event;if(t){var r=t.assetList,i=r[r.length-1];if(i)return i.identifier}return null}},{key:"parseInterstitialDateRanges",value:function(e,t){var r=this,i=e.main.details,n=i.dateRanges,a=this.events,s=this.parseDateRanges(n,{url:i.url},t),o=Object.keys(n),l=a?a.filter(function(e){return!o.includes(e.identifier)}):[];s.length&&s.sort(function(e,t){var r=e.cue.pre,i=e.cue.post,n=t.cue.pre,a=t.cue.post;if(r&&!n)return-1;if(n&&!r)return 1;if(i&&!a)return 1;if(a&&!i)return-1;if(!(r||n||i||a)){var s=e.startTime,o=t.startTime;if(s!==o)return s-o}return e.dateRange.tagOrder-t.dateRange.tagOrder}),this.events=s,l.forEach(function(e){r.removeEvent(e)}),this.updateSchedule(e,l)}},{key:"updateSchedule",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=this.events||[];if(i.length||t.length||this.length<2){var n=this.items,a=this.parseSchedule(i,e);(r||t.length||(null==n?void 0:n.length)!==a.length||a.some(function(e,t){return Math.abs(e.playout.start-n[t].playout.start)>.005||Math.abs(e.playout.end-n[t].playout.end)>.005}))&&(this.items=a,this.onScheduleUpdate(t,n))}}},{key:"parseDateRanges",value:function(e,t,r){for(var i=[],n=Object.keys(e),a=0;a<n.length;a++){var s=n[a],o=e[s];if(o.isInterstitial){var l=this.eventMap[s];l?l.setDateRange(o):(l=new _o(o,t),this.eventMap[s]=l,!1===r&&(l.appendInPlace=r)),i.push(l)}}return i}},{key:"parseSchedule",value:function(e,t){var r=[],i=t.main.details,n=i.live?1/0:i.edge,a=0;if((e=e.filter(function(e){return!(e.error||e.cue.once&&e.hasPlayed)})).length){this.resolveOffsets(e,t);var s=0,o=0;if(e.forEach(function(t,i){var l=t.cue.pre,u=t.cue.post,c=e[i-1]||null,d=t.appendInPlace,h=u?n:t.startOffset,f=t.duration,v=t.timelineOccupancy===xo.Range?f:0,g=t.resumptionOffset,p=(null==c?void 0:c.startTime)===h,m=h+t.cumulativeDuration,y=d?m+f:h+g;if(l||!u&&h<=0){var T=o;o+=v,t.timelineStart=m;var E=a;a+=f,r.push({event:t,start:m,end:y,playout:{start:E,end:a},integrated:{start:T,end:o}})}else{if(!(h<=n))return;if(!p){var k=h-s;if(k>.033){var S=s,b=o;o+=k;var A=a;a+=k;var L={previousEvent:e[i-1]||null,nextEvent:t,start:S,end:S+k,playout:{start:A,end:a},integrated:{start:b,end:o}};r.push(L)}else k>0&&c&&(c.cumulativeDuration+=k,r[r.length-1].end=h)}u&&(y=m),t.timelineStart=m;var R=o;o+=v;var I=a;a+=f,r.push({event:t,start:m,end:y,playout:{start:I,end:a},integrated:{start:R,end:o}})}var w=t.resumeTime;s=u||w>n?n:w}),s<n){var l,u=s,c=o,d=n-s;o+=d;var h=a;a+=d,r.push({previousEvent:(null==(l=r[r.length-1])?void 0:l.event)||null,nextEvent:null,start:s,end:u+d,playout:{start:h,end:a},integrated:{start:c,end:o}})}this.setDurations(n,a,o)}else{r.push({previousEvent:null,nextEvent:null,start:0,end:n,playout:{start:0,end:n},integrated:{start:0,end:n}}),this.setDurations(n,n,n)}return r}},{key:"setDurations",value:function(e,t,r){this.durations={primary:e,playout:t,integrated:r}}},{key:"resolveOffsets",value:function(e,t){var r=this,i=t.main.details,n=i.live?1/0:i.edge,a=0,s=-1;e.forEach(function(o,l){var u=o.cue.pre,c=o.cue.post,d=u?0:c?n:o.startTime;(r.updateAssetDurations(o),s===d?o.cumulativeDuration=a:(a=0,s=d),!c&&o.snapOptions.in&&(o.resumeAnchor=er(null,i.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted)&&(r.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1));!o.appendInPlace&&l+1<e.length&&(e[l+1].startTime-e[l].resumeTime<.033&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&r.warn("Could not change append strategy for abutting event ".concat(o))));var h=X(o.resumeOffset)?o.resumeOffset:o.duration;a+=h})}},{key:"primaryCanResumeInPlaceAt",value:function(e,t){var r=this,i=e.resumeTime,n=e.startTime+e.resumptionOffset;return Math.abs(i-n)>Do?(this.log('"'.concat(e.identifier,'" resumption ').concat(i," not aligned with estimated timeline end ").concat(n)),!1):!Object.keys(t).some(function(n){var a=t[n].details,s=a.edge;if(i>=s)return r.log('"'.concat(e.identifier,'" resumption ').concat(i," past ").concat(n," playlist end ").concat(s)),!1;var o=er(null,a.fragments,i);if(!o)return r.log('"'.concat(e.identifier,'" resumption ').concat(i," does not align with any fragments in ").concat(n," playlist (").concat(a.fragStart,"-").concat(a.fragmentEnd,")")),!0;var l="audio"===n?.175:0;return!(Math.abs(o.start-i)<Do+l||Math.abs(o.end-i)<Do+l)&&(r.log('"'.concat(e.identifier,'" resumption ').concat(i," not aligned with ").concat(n," fragment bounds (").concat(o.start,"-").concat(o.end," sn: ").concat(o.sn," cc: ").concat(o.cc,")")),!0)})}},{key:"updateAssetDurations",value:function(e){if(e.assetListLoaded){for(var t=e.timelineStart,r=0,i=!1,n=!1,a=0;a<e.assetList.length;a++){var s=e.assetList[a],o=t+r;s.startOffset=r,s.timelineStart=o,i||(i=null===s.duration),n||(n=!!s.error),r+=s.error?0:s.duration||0}e.duration=i&&!n?Math.max(r,e.duration):r}}},{key:"removeEvent",value:function(e){e.reset(),delete this.eventMap[e.identifier]}}])}(ve);function Vo(e){return"[".concat(e.event?'"'+e.event.identifier+'"':"primary",": ").concat(e.start.toFixed(2),"-").concat(e.end.toFixed(2),"]")}var Go=function(){return o(function e(t){a(this,e),this.hls=void 0,this.hls=t},[{key:"destroy",value:function(){this.hls=null}},{key:"loadAssetList",value:function(e,t){var r,i=this,n=e.assetListUrl;try{r=Oo(n,this.hls.sessionId,e.baseUrl)}catch(t){var a=this.assignAssetListError(e,Z.ASSET_LIST_LOAD_ERROR,t,n);return void this.hls.trigger(ee.ERROR,a)}t&&"data:"!==r.protocol&&r.searchParams.set("_HLS_start_offset",""+t);var s=this.hls.config,o=new(0,s.loader)(s),l={responseType:"json",url:r.href},u=s.interstitialAssetListLoadPolicy.default,c={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:function(t,r,n,a){var s=t.data,o=null==s?void 0:s.ASSETS;if(Array.isArray(o))e.assetListResponse=s,i.hls.trigger(ee.ASSET_LIST_LOADED,{event:e,assetListResponse:s,networkDetails:a});else{var l=i.assignAssetListError(e,Z.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),n.url,r,a);i.hls.trigger(ee.ERROR,l)}},onError:function(t,r,n,a){var s=i.assignAssetListError(e,Z.ASSET_LIST_LOAD_ERROR,new Error("Error loading X-ASSET-LIST: HTTP status ".concat(t.code," ").concat(t.text," (").concat(r.url,")")),r.url,a,n);i.hls.trigger(ee.ERROR,s)},onTimeout:function(t,r,n){var a=i.assignAssetListError(e,Z.ASSET_LIST_LOAD_TIMEOUT,new Error("Timeout loading X-ASSET-LIST (".concat(r.url,")")),r.url,t,n);i.hls.trigger(ee.ERROR,a)}};return o.load(l,c,d),this.hls.trigger(ee.ASSET_LIST_LOADING,{event:e}),o}},{key:"assignAssetListError",value:function(e,t,r,i,n,a){return e.error=r,{type:J.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:i,error:r,networkDetails:a,stats:n}}}])}();function Ho(e){var t;null==e||null==(t=e.play())||t.catch(function(){})}function Ko(e,t){return"[".concat(e,"] Advancing timeline position to ").concat(t)}var jo=function(e){function t(e,r){var i;return a(this,t),(i=n(this,t,["interstitials",e.logger])).HlsPlayerClass=void 0,i.hls=void 0,i.assetListLoader=void 0,i.mediaSelection=null,i.altSelection=null,i.media=null,i.detachedData=null,i.requiredTracks=null,i.manager=null,i.playerQueue=[],i.bufferedPos=-1,i.timelinePos=-1,i.schedule=void 0,i.playingItem=null,i.bufferingItem=null,i.waitingItem=null,i.endedItem=null,i.playingAsset=null,i.endedAsset=null,i.bufferingAsset=null,i.shouldPlay=!1,i.onPlay=function(){i.shouldPlay=!0},i.onPause=function(){i.shouldPlay=!1},i.onSeeking=function(){var e=i.currentTime;if(void 0!==e&&!i.playbackDisabled&&i.schedule){var t=e-i.timelinePos;if(!(Math.abs(t)<1/7056e5)){var r=t<=-.01;i.timelinePos=e,i.bufferedPos=e;var n=i.playingItem;if(n){if(r)i.schedule.resetErrorsInRange(e,e-t)&&i.updateSchedule(!0);if(i.checkBuffer(),r&&e<n.start||e>=n.end){var a,s=i.findItemIndex(n),o=i.schedule.findItemIndexAtTime(e);if(-1===o&&(o=s+(r?-1:1),i.log("seeked ".concat(r?"back ":"","to position not covered by schedule ").concat(e," (resolving from ").concat(s," to ").concat(o,")"))),!i.isInterstitial(n)&&null!=(a=i.media)&&a.paused&&(i.shouldPlay=!1),!r&&o>s){var l=i.schedule.findJumpRestrictedIndex(s+1,o);if(l>s)return void i.setSchedulePosition(l)}i.setSchedulePosition(o)}else{var u=i.playingAsset;if(u){var c,d=u.timelineStart,h=u.duration||0;if(r&&e<d||e>=d+h)null!=(c=n.event)&&c.appendInPlace&&(i.clearInterstitial(n.event,n),i.flushFrontBuffer(e)),i.setScheduleToAssetAtTime(e,u)}else if(i.playingLastItem&&i.isInterstitial(n)){var f=n.event.assetList[0];f&&(i.endedItem=i.playingItem,i.playingItem=null,i.setScheduleToAssetAtTime(e,f))}}}else i.checkBuffer()}}},i.onTimeupdate=function(){var e=i.currentTime;if(void 0!==e&&!i.playbackDisabled&&e>i.timelinePos){i.timelinePos=e,e>i.bufferedPos&&i.checkBuffer();var t=i.playingItem;if(t&&!i.playingLastItem){if(e>=t.end){i.timelinePos=t.end;var r=i.findItemIndex(t);i.setSchedulePosition(r+1)}var n=i.playingAsset;if(n)e>=n.timelineStart+(n.duration||0)&&i.setScheduleToAssetAtTime(e,n)}}},i.onScheduleUpdate=function(e,t){var r=i.schedule;if(r){var n=i.playingItem,a=r.events||[],s=r.items||[],o=r.durations,l=e.map(function(e){return e.identifier}),u=!(!a.length&&!l.length);(u||t)&&i.log("INTERSTITIALS_UPDATED (".concat(a.length,"): ").concat(a,"\nSchedule: ").concat(s.map(function(e){return Vo(e)})," pos: ").concat(i.timelinePos)),l.length&&i.log("Removed events ".concat(l));var c=null,d=null;n&&(c=i.updateItem(n,i.timelinePos),i.itemsMatch(n,c)?i.playingItem=c:i.waitingItem=i.endedItem=null),i.waitingItem=i.updateItem(i.waitingItem),i.endedItem=i.updateItem(i.endedItem);var h=i.bufferingItem;if(h&&(d=i.updateItem(h,i.bufferedPos),i.itemsMatch(h,d)?i.bufferingItem=d:h.event&&(i.bufferingItem=i.playingItem,i.clearInterstitial(h.event,null))),e.forEach(function(e){e.assetList.forEach(function(e){i.clearAssetPlayer(e.identifier,null)})}),i.playerQueue.forEach(function(e){if(e.interstitial.appendInPlace){var t=e.assetItem.timelineStart,r=e.timelineOffset-t;if(r)try{e.timelineOffset=t}catch(n){Math.abs(r)>Do&&i.warn("".concat(n,' ("').concat(e.assetId,'" ').concat(e.timelineOffset,"->").concat(t,")"))}}}),u||t){if(i.hls.trigger(ee.INTERSTITIALS_UPDATED,{events:a.slice(0),schedule:s.slice(0),durations:o,removedIds:l}),i.isInterstitial(n)&&l.includes(n.event.identifier))return i.warn('Interstitial "'.concat(n.event.identifier,'" removed while playing')),void i.primaryFallback(n.event);n&&i.trimInPlace(c,n),h&&d!==c&&i.trimInPlace(d,h),i.checkBuffer()}}},i.hls=e,i.HlsPlayerClass=r,i.assetListLoader=new Go(e),i.schedule=new Bo(i.onScheduleUpdate,e.logger),i.registerListeners(),i}return d(t,e),o(t,[{key:"registerListeners",value:function(){var e=this.hls;e&&(e.on(ee.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(ee.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(ee.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(ee.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(ee.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(ee.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(ee.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(ee.BUFFER_APPENDED,this.onBufferAppended,this),e.on(ee.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(ee.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(ee.MEDIA_ENDED,this.onMediaEnded,this),e.on(ee.ERROR,this.onError,this),e.on(ee.DESTROYING,this.onDestroying,this))}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ee.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(ee.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(ee.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(ee.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(ee.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(ee.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(ee.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(ee.BUFFER_CODECS,this.onBufferCodecs,this),e.off(ee.BUFFER_APPENDED,this.onBufferAppended,this),e.off(ee.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(ee.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(ee.MEDIA_ENDED,this.onMediaEnded,this),e.off(ee.ERROR,this.onError,this),e.off(ee.DESTROYING,this.onDestroying,this))}},{key:"startLoad",value:function(){this.resumeBuffering()}},{key:"stopLoad",value:function(){this.pauseBuffering()}},{key:"resumeBuffering",value:function(){var e;null==(e=this.getBufferingPlayer())||e.resumeBuffering()}},{key:"pauseBuffering",value:function(){var e;null==(e=this.getBufferingPlayer())||e.pauseBuffering()}},{key:"destroy",value:function(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}},{key:"onDestroying",value:function(){var e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}},{key:"removeMediaListeners",value:function(e){un(e,"play",this.onPlay),un(e,"pause",this.onPause),un(e,"seeking",this.onSeeking),un(e,"timeupdate",this.onTimeupdate)}},{key:"onMediaAttaching",value:function(e,t){var r=this.media=t.media;ln(r,"seeking",this.onSeeking),ln(r,"timeupdate",this.onTimeupdate),ln(r,"play",this.onPlay),ln(r,"pause",this.onPause)}},{key:"onMediaAttached",value:function(e,t){var r=this.effectivePlayingItem,i=this.detachedData;if(this.detachedData=null,null===r)this.checkStart();else if(!i){this.clearScheduleState();var n=this.findItemIndex(r);this.setSchedulePosition(n)}}},{key:"clearScheduleState",value:function(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}},{key:"onMediaDetaching",value:function(e,t){var r=!!t.transferMedia,i=this.media;if(this.media=null,!r&&(i&&this.removeMediaListeners(i),this.detachedData)){var n=this.getBufferingPlayer();n&&(this.log("Removing schedule state for detachedData and ".concat(n)),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,n.detachMedia()),this.shouldPlay=!1}}},{key:"interstitialsManager",get:function(){if(!this.hls)return null;if(this.manager)return this.manager;var e=this,t=function(){return e.bufferingItem||e.waitingItem},r=function(t){return t?e.getAssetPlayer(t.identifier):t},i=function(t,i,a,s,o){if(t){var l=t[i].start,u=t.event;if(u){if("playout"===i||u.timelineOccupancy!==xo.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,T=(f?m:p.currentTime)+y;if(T>=0&&(!g||f||T<=g.duration))return void(p.currentTime=T)}}if(c){var E=t;if("primary"!==n){var k=t-c[n].start;E=c.start+k}var S=!e.isInterstitial(c);if(e.isInterstitial(l)&&!l.event.appendInPlace||!S&&!c.event.appendInPlace){if(l){var b=e.findItemIndex(l);if(u>b){var A=e.schedule.findJumpRestrictedIndex(b+1,u);if(A>b)return void e.setSchedulePosition(A)}var L=0;if(S)e.timelinePos=E,e.checkBuffer();else for(var R=c.event.assetList,I=t-(c[n]||c).start,w=R.length;w--;){var P=R[w];if(P.duration&&I>=P.startOffset&&I<P.startOffset+P.duration){L=w;break}}e.setSchedulePosition(u,L)}}else{var D=e.media||(f?null==d?void 0:d.media:null);D&&(D.currentTime=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(){var t;return(null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0}},integrated:{get bufferedEnd(){return i(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(e){s(e,"integrated")},get duration(){return a("integrated")},get seekableStart(){var t;return function(t,r){var i;if(0!==t&&"primary"!==r&&null!=(i=e.schedule)&&i.length){var n,a=e.schedule.findItemIndexAtTime(t),s=null==(n=e.schedule.items)?void 0:n[a];if(s)return t+(s[r].start-s.start)}return t}((null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0,"integrated")}},skip:function(){var t=e.effectivePlayingItem,r=null==t?void 0:t.event;if(r&&!r.restrictions.skip){var i=e.findItemIndex(t);if(r.appendInPlace){var n=t.playout.start+t.event.duration;s(n+.001,"playout")}else e.advanceAfterAssetEnded(r,i,1/0)}}}}},{key:"effectivePlayingItem",get:function(){return this.waitingItem||this.playingItem||this.endedItem}},{key:"effectivePlayingAsset",get:function(){return this.playingAsset||this.endedAsset}},{key:"playingLastItem",get:function(){var e,t=this.playingItem,r=null==(e=this.schedule)?void 0:e.items;return!!(this.playbackStarted&&t&&r)&&this.findItemIndex(t)===r.length-1}},{key:"playbackStarted",get:function(){return null!==this.effectivePlayingItem}},{key:"currentTime",get:function(){var e,t;if(null!==this.mediaSelection){var r=this.waitingItem||this.playingItem;if(!this.isInterstitial(r)||r.event.appendInPlace){var i=this.media;!i&&null!=(e=this.bufferingItem)&&null!=(e=e.event)&&e.appendInPlace&&(i=this.primaryMedia);var n=null==(t=i)?void 0:t.currentTime;if(void 0!==n&&X(n))return n}}}},{key:"primaryMedia",get:function(){var e;return this.media||(null==(e=this.detachedData)?void 0:e.media)||null}},{key:"isInterstitial",value:function(e){return!(null==e||!e.event)}},{key:"retreiveMediaSource",value:function(e,t){var r=this.getAssetPlayer(e);r&&this.transferMediaFromPlayer(r,t)}},{key:"transferMediaFromPlayer",value:function(e,t){var r=e.interstitial.appendInPlace,i=e.media;if(r&&i===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&i)return void(this.detachedData={media:i});var n=e.transferMedia();this.log("transfer MediaSource from ".concat(e," ").concat(Kt(n))),this.detachedData=n}else t&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))}},{key:"transferMediaTo",value:function(e,t){var r,i,n=this;if(e.media!==t){var a,s=null,o=this.hls,l=e!==o,u=l&&e.interstitial.appendInPlace,c=null==(r=this.detachedData)?void 0:r.mediaSource;if(o.media)u&&(s=o.transferMedia(),this.detachedData=s),a="Primary";else if(c){var d=this.getBufferingPlayer();d?(s=d.transferMedia(),a="".concat(d)):a="detached MediaSource"}else a="detached media";if(!s)if(c)s=this.detachedData,this.log("using detachedData: MediaSource ".concat(Kt(s)));else if(!this.detachedData||o.media===t){var h=this.playerQueue;h.length>1&&h.forEach(function(e){if(l&&e.interstitial.appendInPlace!==u){var t=e.interstitial;n.clearInterstitial(e.interstitial,null),t.appendInPlace=!1,t.appendInPlace&&n.warn("Could not change append strategy for queued assets ".concat(t))}}),this.hls.detachMedia(),this.detachedData={media:t}}var f=s&&"mediaSource"in s&&"closed"!==(null==(i=s.mediaSource)?void 0:i.readyState),v=f&&s?s:t;this.log("".concat(f?"transfering MediaSource":"attaching media"," to ").concat(l?e:"Primary"," from ").concat(a," (media.currentTime: ").concat(t.currentTime,")"));var g=this.schedule;if(v===s&&g){var p=l&&e.assetId===g.assetIdAtEnd;v.overrides={duration:g.duration,endOfStream:!l||p,cueRemoval:!l}}e.attachMedia(v)}}},{key:"onInterstitialCueEnter",value:function(){this.onTimeupdate()}},{key:"checkStart",value:function(){var e=this.schedule,t=null==e?void 0:e.events;if(t&&!this.playbackDisabled&&this.media){-1===this.bufferedPos&&(this.bufferedPos=0);var r=this.timelinePos,i=this.effectivePlayingItem;if(-1===r){var n=this.hls.startPosition;if(this.log(Ko("checkStart",n)),this.timelinePos=n,t.length&&t[0].cue.pre){var a=e.findEventIndex(t[0].identifier);this.setSchedulePosition(a)}else if(n>=0||!this.primaryLive){var s=this.timelinePos=n>0?n:0,o=e.findItemIndexAtTime(s);this.setSchedulePosition(o)}}else if(i&&!this.playingItem){var l=e.findItemIndex(i);this.setSchedulePosition(l)}}}},{key:"advanceAssetBuffering",value:function(e,t){var r=e.event,i=r.findAssetIndex(t),n=Fo(r,i);if(r.isAssetPastPlayoutLimit(n)){if(this.schedule){var a,s=null==(a=this.schedule.items)?void 0:a[this.findItemIndex(e)+1];s&&this.bufferedToItem(s)}}else this.bufferedToEvent(e,n)}},{key:"advanceAfterAssetEnded",value:function(e,t,r){var i=Fo(e,r);if(e.isAssetPastPlayoutLimit(i)){if(this.schedule){var n=this.schedule.items;if(n){var a=t+1;if(a>=n.length)return void this.setSchedulePosition(-1);var s=e.resumeTime;this.timelinePos<s&&(this.log(Ko("advanceAfterAssetEnded",s)),this.timelinePos=s,e.appendInPlace&&this.advanceInPlace(s),this.checkBuffer(this.bufferedPos<s)),this.setSchedulePosition(a)}}}else{if(e.appendInPlace){var o=e.assetList[i];o&&this.advanceInPlace(o.timelineStart)}this.setSchedulePosition(t,i)}}},{key:"setScheduleToAssetAtTime",value:function(e,t){var r=this.schedule;if(r){var i=t.parentIdentifier,n=r.getEvent(i);if(n){var a=r.findEventIndex(i),s=r.findAssetIndex(n,e);this.advanceAfterAssetEnded(n,a,s-1)}}}},{key:"setSchedulePosition",value:function(e,t){var r,i=null==(r=this.schedule)?void 0:r.items;if(i&&!this.playbackDisabled){var n=e>=0?i[e]:null;this.log("setSchedulePosition ".concat(e,", ").concat(t," (").concat(n?Vo(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(Uo(l))),this.endedAsset=l,this.playingAsset=null,this.hls.trigger(ee.INTERSTITIAL_ASSET_ENDED,{asset:l,assetListIndex:h,event:o,schedule:i.slice(0),scheduleIndex:e,player:c}),a!==this.playingItem)return void(this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(o,this.findItemIndex(this.playingItem),h));this.retreiveMediaSource(u,n),!c.media||null!=(d=this.detachedData)&&d.mediaSource||c.detachMedia()}if(!this.eventItemsMatch(a,n)&&(this.endedItem=a,this.playingItem=null,this.log("INTERSTITIAL_ENDED ".concat(o," ").concat(Vo(a))),o.hasPlayed=!0,this.hls.trigger(ee.INTERSTITIAL_ENDED,{event:o,schedule:i.slice(0),scheduleIndex:e}),o.cue.once)){var f;this.updateSchedule();var v=null==(f=this.schedule)?void 0:f.items;if(n&&v){var g=this.findItemIndex(n);this.advanceSchedule(g,v,t,a,s)}return}}this.advanceSchedule(e,i,t,a,s)}}},{key:"advanceSchedule",value:function(e,t,r,i,n){var a=this,s=this.schedule;if(s){var o=t[e]||null,l=this.primaryMedia,u=this.playerQueue;if(u.length&&u.forEach(function(t){var r=t.interstitial,i=s.findEventIndex(r.identifier);(i<e||i>e+1)&&a.clearInterstitial(r,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);var c=o.event;if(void 0===r){var d=Fo(c,(r=s.findAssetIndex(c,this.timelinePos))-1);if(c.isAssetPastPlayoutLimit(d)||c.appendInPlace&&this.timelinePos===o.end)return void this.advanceAfterAssetEnded(c,e,r);r=d}var h=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);var f=this.preloadAssets(c,r);if(this.eventItemsMatch(o,h||i)||(this.waitingItem=o,this.log("INTERSTITIAL_STARTED ".concat(Vo(o)," ").concat(c.appendInPlace?"append in place":"")),this.hls.trigger(ee.INTERSTITIAL_STARTED,{event:c,schedule:t.slice(0),scheduleIndex:e})),!c.assetListLoaded)return void this.log("Waiting for ASSET-LIST to complete loading ".concat(c));if(c.assetListLoader&&(c.assetListLoader.destroy(),c.assetListLoader=void 0),!l)return void this.log("Waiting for attachMedia to start Interstitial ".concat(c));this.waitingItem=this.endedItem=null,this.playingItem=o;var v=c.assetList[r];if(!v)return void this.advanceAfterAssetEnded(c,e,r||0);if(f||(f=this.getAssetPlayer(v.identifier)),null===f||f.destroyed){var g=c.assetList.length;this.warn("asset ".concat(r+1,"/").concat(g," player destroyed ").concat(c)),(f=this.createAssetPlayer(c,v,r)).loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&c.appendInPlace&&this.isAssetBuffered(v))return;this.startAssetPlayer(f,r,t,e,l),this.shouldPlay&&Ho(f.media)}else o?(this.resumePrimary(o,e,i),this.shouldPlay&&Ho(this.hls.media)):n&&this.isInterstitial(i)&&(this.endedItem=null,this.playingItem=i,i.event.appendInPlace||this.attachPrimary(s.durations.primary,null))}}},{key:"playbackDisabled",get:function(){return!1===this.hls.config.enableInterstitialPlayback}},{key:"primaryDetails",get:function(){var e;return null==(e=this.mediaSelection)?void 0:e.main.details}},{key:"primaryLive",get:function(){var e;return!(null==(e=this.primaryDetails)||!e.live)}},{key:"resumePrimary",value:function(e,t,r){var i,n;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log("resuming ".concat(Vo(e))),null==(i=this.detachedData)||!i.mediaSource){var a=this.timelinePos;(a<e.start||a>=e.end)&&(a=this.getPrimaryResumption(e,t),this.log(Ko("resumePrimary",a)),this.timelinePos=a),this.attachPrimary(a,e)}if(r){var s=null==(n=this.schedule)?void 0:n.items;s&&(this.log("INTERSTITIALS_PRIMARY_RESUMED ".concat(Vo(e))),this.hls.trigger(ee.INTERSTITIALS_PRIMARY_RESUMED,{schedule:s.slice(0),scheduleIndex:t}),this.checkBuffer())}}},{key:"getPrimaryResumption",value:function(e,t){var r=e.start;if(this.primaryLive){var i=this.primaryDetails;if(0===t)return this.hls.startPosition;if(i&&(r<i.fragmentStart||r>i.edge))return this.hls.liveSyncPosition||-1}return r}},{key:"isAssetBuffered",value:function(e){var t=this.getAssetPlayer(e.identifier);return null!=t&&t.hls?t.hls.bufferedToEnd:jr.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}},{key:"attachPrimary",value:function(e,t,r){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;var i=this.primaryMedia;if(i){var n=this.hls;n.media?this.checkBuffer():(this.transferMediaTo(n,i),r&&this.startLoadingPrimaryAt(e,r)),r||(this.log(Ko("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,r))}}},{key:"startLoadingPrimaryAt",value:function(e,t){var r,i=this.hls;!i.loadingEnabled||!i.media||Math.abs(((null==(r=i.mainForwardBufferInfo)?void 0:r.start)||i.media.currentTime)-e)>.5?i.startLoad(e,t):i.bufferingEnabled||i.resumeBuffering()}},{key:"onManifestLoading",value:function(){var e;this.stopLoad(),null==(e=this.schedule)||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(ee.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(ee.BUFFER_CODECS,this.onBufferCodecs,this)}},{key:"onLevelUpdated",value:function(e,t){if(-1!==t.level&&this.schedule){var r=this.hls.levels[t.level];if(r.details){var i=fe(fe({},this.mediaSelection||this.altSelection),{},{main:r});this.mediaSelection=i,this.schedule.parseInterstitialDateRanges(i,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}}}},{key:"onAudioTrackUpdated",value:function(e,t){var r=this.hls.audioTracks[t.id],i=this.mediaSelection;if(i){var n=fe(fe({},i),{},{audio:r});this.mediaSelection=n}else this.altSelection=fe(fe({},this.altSelection),{},{audio:r})}},{key:"onSubtitleTrackUpdated",value:function(e,t){var r=this.hls.subtitleTracks[t.id],i=this.mediaSelection;if(i){var n=fe(fe({},i),{},{subtitles:r});this.mediaSelection=n}else this.altSelection=fe(fe({},this.altSelection),{},{subtitles:r})}},{key:"onAudioTrackSwitching",value:function(e,t){var r=Wt(t);this.playerQueue.forEach(function(e){var i=e.hls;return i&&(i.setAudioOption(t)||i.setAudioOption(r))})}},{key:"onSubtitleTrackSwitch",value:function(e,t){var r=Wt(t);this.playerQueue.forEach(function(e){var i=e.hls;return i&&(i.setSubtitleOption(t)||-1!==t.id&&i.setSubtitleOption(r))})}},{key:"onBufferCodecs",value:function(e,t){var r=t.tracks;r&&(this.requiredTracks=r)}},{key:"onBufferAppended",value:function(e,t){this.checkBuffer()}},{key:"onBufferFlushed",value:function(e,t){var r=this.playingItem;if(r&&!this.itemsMatch(r,this.bufferingItem)&&!this.isInterstitial(r)){var i=this.timelinePos;this.bufferedPos=i,this.checkBuffer()}}},{key:"onBufferedToEnd",value:function(e){if(this.schedule){var t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(var r=0;r<t.length;r++){var i=t[r];if(i.cue.post){var n,a=this.schedule.findEventIndex(i.identifier),s=null==(n=this.schedule.items)?void 0:n[a];this.isInterstitial(s)&&this.eventItemsMatch(s,this.bufferingItem)&&this.bufferedToItem(s,0);break}}this.bufferedPos=Number.MAX_VALUE}}}},{key:"onMediaEnded",value:function(e){var t=this.playingItem;if(!this.playingLastItem&&t){var r=this.findItemIndex(t);this.setSchedulePosition(r+1)}else this.shouldPlay=!1}},{key:"updateItem",value:function(e,t){var r,i=null==(r=this.schedule)?void 0:r.items;return e&&i&&i[this.findItemIndex(e,t)]||null}},{key:"trimInPlace",value:function(e,t){var r=this;if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach(function(t,i){e.event.isAssetPastPlayoutLimit(i)&&r.clearAssetPlayer(t.identifier,null)});var i=e.end+.25,n=jr.bufferInfo(this.primaryMedia,i,0);if(n.end>i||(n.nextStart||0)>i){this.log("trim buffered interstitial ".concat(Vo(e)," (was ").concat(Vo(t),")"));this.attachPrimary(i,null,!0),this.flushFrontBuffer(i)}}}},{key:"itemsMatch",value:function(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}},{key:"eventItemsMatch",value:function(e,t){var r;return!!t&&(e===t||e.event.identifier===(null==(r=t.event)?void 0:r.identifier))}},{key:"findItemIndex",value:function(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}},{key:"updateSchedule",value:function(){var e,t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],r=this.mediaSelection;r&&(null==(e=this.schedule)||e.updateSchedule(r,[],t))}},{key:"checkBuffer",value:function(e){var t,r=null==(t=this.schedule)?void 0:t.items;if(r){var i=jr.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=i.len<1),this.updateBufferedPos(i.end,r,e)}}},{key:"updateBufferedPos",value:function(e,t,r){var i=this.schedule,n=this.bufferingItem;if(!(this.bufferedPos>e)&&i)if(1===t.length&&this.itemsMatch(t[0],n))this.bufferedPos=e;else{var a=this.playingItem,s=this.findItemIndex(a),o=i.findItemIndexAtTime(e);if(this.bufferedPos<e){var l,u=this.findItemIndex(n),c=Math.min(u+1,t.length-1),d=t[c];if((-1===o&&n&&e>=n.end||null!=(l=d.event)&&l.appendInPlace&&e+.01>=d.start)&&(o=c),this.isInterstitial(n)){var h=n.event;if(c-s>1&&!1===h.appendInPlace)return;if(0===h.assetList.length&&h.assetListLoader)return}if(this.bufferedPos=e,o>u&&o>s)this.bufferedToItem(d);else{var f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&d.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(d)&&this.preloadAssets(d.event,0)}}else r&&a&&!this.itemsMatch(a,n)&&(o===s?this.bufferedToItem(a):o===s+1&&this.bufferedToItem(t[o]))}}},{key:"assetsBuffered",value:function(e,t){var r=this;return 0!==e.event.assetList.length&&!e.event.assetList.some(function(e){var i=r.getAssetPlayer(e.identifier);return!(null!=i&&i.bufferedInPlaceToEnd(t))})}},{key:"setBufferingItem",value:function(e){var t=this,r=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(e,r)&&i){var n=i.items,a=i.events;if(!n||!a)return r;var s=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));var l=o?o.remaining:r?r.end-this.timelinePos:0;if(this.log("INTERSTITIALS_BUFFERED_TO_BOUNDARY ".concat(Vo(e))+(r?" (".concat(l.toFixed(2)," remaining)"):"")),!this.playbackDisabled)if(s){var u=i.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach(function(e,r){var i=t.getAssetPlayer(e.identifier);i&&(r===u&&i.loadSource(),i.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(function(e){return e.pauseBuffering()});this.hls.trigger(ee.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:a.slice(0),schedule:n.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return r}},{key:"bufferedToItem",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=this.setBufferingItem(e);if(!this.playbackDisabled)if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(null!==r){this.bufferingAsset=null;var i=this.detachedData;if(i)if(i.mediaSource){this.attachPrimary(e.start,e,!0)}else this.preloadPrimary(e);else this.preloadPrimary(e)}}},{key:"preloadPrimary",value:function(e){var t=this.findItemIndex(e),r=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(r)}},{key:"bufferedToEvent",value:function(e,t){var r=e.event,i=0===r.assetList.length&&!r.assetListLoader,n=r.cue.once;if(i||!n){var a=this.preloadAssets(r,t);if(null!=a&&a.interstitial.appendInPlace){var s=this.primaryMedia;s&&this.bufferAssetPlayer(a,s)}}}},{key:"preloadAssets",value:function(e,t){var r=e.assetUrl,i=e.assetList.length,n=0===i&&!e.assetListLoader,a=e.cue.once;if(n){var s,o=e.timelineStart;if(e.appendInPlace){var l,u=this.playingItem;this.isInterstitial(u)||(null==u||null==(l=u.nextEvent)?void 0:l.identifier)!==e.identifier||this.flushFrontBuffer(o+.25)}var c=0;if(!this.playingItem&&this.primaryLive&&-1===(c=this.hls.startPosition)&&(c=this.hls.liveSyncPosition||0),c&&!e.cue.pre&&!e.cue.post){var d=c-o;d>0&&(s=Math.round(1e3*d)/1e3)}if(this.log("Load interstitial asset ".concat(t+1,"/").concat(r?1:i," ").concat(e).concat(s?" live-start: ".concat(c," start-offset: ").concat(s):"")),r)return this.createAsset(e,0,0,o,e.duration,r);var h=this.assetListLoader.loadAssetList(e,s);h&&(e.assetListLoader=h)}else if(!a&&i){for(var f=t;f<i;f++){var v=e.assetList[f],g=this.getAssetPlayerQueueIndex(v.identifier);-1!==g&&!this.playerQueue[g].destroyed||v.error||this.createAssetPlayer(e,v,f)}var p=e.assetList[t];if(p){var m=this.getAssetPlayer(p.identifier);return m&&m.loadSource(),m}}return null}},{key:"flushFrontBuffer",value:function(e){var t=this,r=this.requiredTracks;r&&(this.log("Removing front buffer starting at ".concat(e)),Object.keys(r).forEach(function(r){t.hls.trigger(ee.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:r})}))}},{key:"getAssetPlayerQueueIndex",value:function(e){for(var t=this.playerQueue,r=0;r<t.length;r++)if(e===t[r].assetId)return r;return-1}},{key:"getAssetPlayer",value:function(e){var t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}},{key:"getBufferingPlayer",value:function(){var e=this.playerQueue,t=this.primaryMedia;if(t)for(var r=0;r<e.length;r++)if(e[r].media===t)return e[r];return null}},{key:"createAsset",value:function(e,t,r,i,n,a){var s={parentIdentifier:e.identifier,identifier:Co(e,a,t),duration:n,startOffset:r,timelineStart:i,uri:a};return this.createAssetPlayer(e,s,t)}},{key:"createAssetPlayer",value:function(e,t,r){var i=this,n=this.hls,a=n.userConfig,s=a.videoPreference,o=n.loadLevelObj||n.levels[n.currentLevel];(s||o)&&(s=de({},s),o.videoCodec&&(s.videoCodec=o.videoCodec),o.videoRange&&(s.allowedVideoRanges=[o.videoRange]));var l=n.audioTracks[n.audioTrack],u=n.subtitleTracks[n.subtitleTrack],c=0;if(this.primaryLive||e.appendInPlace){var d=this.timelinePos-t.timelineStart;if(d>1){var h=t.duration;h&&d<h&&(c=d)}}var f=t.identifier,v=fe(fe({},a),{},{maxMaxBufferLength:Math.min(180,n.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:n.sessionId,assetPlayerId:f,abrEwmaDefaultEstimate:n.bandwidthEstimate,interstitialsController:void 0,startPosition:c,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:s,audioPreference:l||a.audioPreference,subtitlePreference:u||a.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(v.timelineOffset=t.timelineStart));var g=v.cmcd;null!=g&&g.sessionId&&g.contentId&&(v.cmcd=de({},g,{contentId:Po(t.uri)})),this.getAssetPlayer(f)&&this.warn("Duplicate date range identifier ".concat(e," and asset ").concat(f));var p=new No(this.HlsPlayerClass,v,e,t);this.playerQueue.push(p),e.assetList[r]=t;var m=!0,y=function(n){if(n.live){var a,s=new Error("Interstitials MUST be VOD assets ".concat(e)),o={fatal:!0,type:J.OTHER_ERROR,details:Z.INTERSTITIAL_ASSET_ITEM_ERROR,error:s},l=(null==(a=i.schedule)?void 0:a.findEventIndex(e.identifier))||-1;i.handleAssetItemError(o,e,l,r,s.message)}else{var u=n.edge-n.fragmentStart,c=t.duration;(m||null===c||u>c)&&(m=!1,i.log('Interstitial asset "'.concat(f,'" duration change ').concat(c," > ").concat(u)),t.duration=u,i.updateSchedule())}};p.on(ee.LEVEL_UPDATED,function(e,t){var r=t.details;return y(r)}),p.on(ee.LEVEL_PTS_UPDATED,function(e,t){var r=t.details;return y(r)}),p.on(ee.EVENT_CUE_ENTER,function(){return i.onInterstitialCueEnter()});var T=function(e,t){var r=i.getAssetPlayer(f);if(r&&t.tracks){r.off(ee.BUFFER_CODECS,T),r.tracks=t.tracks;var n=i.primaryMedia;i.bufferingAsset===r.assetItem&&n&&!r.media&&i.bufferAssetPlayer(r,n)}};p.on(ee.BUFFER_CODECS,T);p.on(ee.BUFFERED_TO_END,function(){var r,n=i.getAssetPlayer(f);if(i.log("buffered to end of asset ".concat(n)),n&&i.schedule){var a=i.schedule.findEventIndex(e.identifier),s=null==(r=i.schedule.items)?void 0:r[a];i.isInterstitial(s)&&i.advanceAssetBuffering(s,t)}});var E=function(t){return function(){if(i.getAssetPlayer(f)&&i.schedule){i.shouldPlay=!0;var r=i.schedule.findEventIndex(e.identifier);i.advanceAfterAssetEnded(e,r,t)}}};return p.once(ee.MEDIA_ENDED,E(r)),p.once(ee.PLAYOUT_LIMIT_REACHED,E(1/0)),p.on(ee.ERROR,function(t,n){if(i.schedule){var a=i.getAssetPlayer(f);if(n.details===Z.BUFFER_STALLED_ERROR)return null!=a&&a.appendInPlace?void i.handleInPlaceStall(e):(i.onTimeupdate(),void i.checkBuffer(!0));i.handleAssetItemError(n,e,i.schedule.findEventIndex(e.identifier),r,"Asset player error ".concat(n.error," ").concat(e))}}),p.on(ee.DESTROYING,function(){if(i.getAssetPlayer(f)&&i.schedule){var t=new Error("Asset player destroyed unexpectedly ".concat(f)),n={fatal:!0,type:J.OTHER_ERROR,details:Z.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};i.handleAssetItemError(n,e,i.schedule.findEventIndex(e.identifier),r,t.message)}}),this.log("INTERSTITIAL_ASSET_PLAYER_CREATED ".concat(Uo(t))),this.hls.trigger(ee.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:r,event:e,player:p}),p}},{key:"clearInterstitial",value:function(e,t){var r=this;e.assetList.forEach(function(e){r.clearAssetPlayer(e.identifier,t)}),e.reset()}},{key:"resetAssetPlayer",value:function(e){var t=this.getAssetPlayerQueueIndex(e);if(-1!==t){this.log('reset asset player "'.concat(e,'" after error'));var r=this.playerQueue[t];this.transferMediaFromPlayer(r,null),r.resetDetails()}}},{key:"clearAssetPlayer",value:function(e,t){var r=this.getAssetPlayerQueueIndex(e);if(-1!==r){var i=this.playerQueue[r];this.log("clear ".concat(i," toSegment: ").concat(t?Vo(t):t)),this.transferMediaFromPlayer(i,t),this.playerQueue.splice(r,1),i.destroy()}}},{key:"emptyPlayerQueue",value:function(){for(var e;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}},{key:"startAssetPlayer",value:function(e,t,r,i,n){var a=e.interstitial,s=e.assetItem,o=e.assetId,l=a.assetList.length,u=this.playingAsset;this.endedAsset=null,this.playingAsset=s,u&&u.identifier===o||(u&&(this.clearAssetPlayer(u.identifier,r[i]),delete u.error),this.log("INTERSTITIAL_ASSET_STARTED ".concat(t+1,"/").concat(l," ").concat(Uo(s))),this.hls.trigger(ee.INTERSTITIAL_ASSET_STARTED,{asset:s,assetListIndex:t,event:a,schedule:r.slice(0),scheduleIndex:i,player:e})),this.bufferAssetPlayer(e,n)}},{key:"bufferAssetPlayer",value:function(e,t){var r,i;if(this.schedule){var n=e.interstitial,a=e.assetItem,s=this.schedule.findEventIndex(n.identifier),o=null==(r=this.schedule.items)?void 0:r[s];if(o){e.loadSource(),this.setBufferingItem(o),this.bufferingAsset=a;var l=this.getBufferingPlayer();if(l!==e){var u=n.appendInPlace;if(!u||!1!==(null==l?void 0:l.interstitial.appendInPlace)){var c=(null==l?void 0:l.tracks)||(null==(i=this.detachedData)?void 0:i.tracks)||this.requiredTracks;if(u&&a!==this.playingAsset){if(!e.tracks)return void this.log("Waiting for track info before buffering ".concat(e));if(c&&!Se(c,e.tracks)){var d=new Error("Asset ".concat(Uo(a)," SourceBuffer tracks ('").concat(Object.keys(e.tracks),"') are not compatible with primary content tracks ('").concat(Object.keys(c),"')")),h={fatal:!0,type:J.OTHER_ERROR,details:Z.INTERSTITIAL_ASSET_ITEM_ERROR,error:d},f=n.findAssetIndex(a);return void this.handleAssetItemError(h,n,s,f,d.message)}}this.transferMediaTo(e,t)}}}}}},{key:"handleInPlaceStall",value:function(e){var t=this.schedule,r=this.primaryMedia;if(t&&r){var i=r.currentTime,n=t.findAssetIndex(e,i),a=e.assetList[n];if(a){var s=this.getAssetPlayer(a.identifier);if(s){var o=s.currentTime||i-a.timelineStart,l=s.duration-o;if(this.warn("Stalled at ".concat(o," of ").concat(o+l," in ").concat(s," ").concat(e," (media.currentTime: ").concat(i,")")),o&&(l/r.playbackRate<.5||s.bufferedInPlaceToEnd(r))&&s.hls){var u=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,u,n)}}}}}},{key:"advanceInPlace",value:function(e){var t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}},{key:"handleAssetItemError",value:function(e,t,r,i,n){if(e.details!==Z.BUFFER_STALLED_ERROR){var a=t.assetList[i]||null;if(this.warn("INTERSTITIAL_ASSET_ERROR ".concat(a?Uo(a):a," ").concat(e.error)),this.schedule){var s=(null==a?void 0:a.identifier)||"",o=this.getAssetPlayerQueueIndex(s),l=this.playerQueue[o]||null,u=this.schedule.items,c=de({},e,{fatal:!1,errorAction:kr(!0),asset:a,assetListIndex:i,event:t,schedule:u,scheduleIndex:r,player:l});if(this.hls.trigger(ee.INTERSTITIAL_ASSET_ERROR,c),e.fatal){var d=this.playingAsset,h=this.bufferingAsset,f=new Error(n);if(a&&(this.clearAssetPlayer(s,null),a.error=f),t.assetList.some(function(e){return!e.error}))for(var v=i;v<t.assetList.length;v++)this.resetAssetPlayer(t.assetList[v].identifier);else t.error=f;this.updateSchedule(!0),t.error?this.primaryFallback(t):d&&d.identifier===s?this.advanceAfterAssetEnded(t,r,i):h&&h.identifier===s&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,h)}}}}},{key:"primaryFallback",value:function(e){var t=e.timelineStart,r=this.effectivePlayingItem;if(r){this.log('Fallback to primary from event "'.concat(e.identifier,'" start: ').concat(t," pos: ").concat(this.timelinePos," playing: ").concat(Vo(r)," error: ").concat(e.error));var i=this.timelinePos;-1===i&&(i=this.hls.startPosition);var n=this.updateItem(r,i);if(this.itemsMatch(r,n)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t)),!this.schedule)return;var a=this.schedule.findItemIndexAtTime(i);this.setSchedulePosition(a)}else this.checkStart()}},{key:"onAssetListLoaded",value:function(e,t){var r,i,n=this,a=t.event,s=a.identifier,o=t.assetListResponse.ASSETS;if(null!=(r=this.schedule)&&r.hasEvent(s)){var l=a.timelineStart,u=a.duration,c=0;o.forEach(function(e,t){var r=parseFloat(e.DURATION);n.createAsset(a,t,c,l+c,r,e.URI),c+=r}),a.duration=c,this.log("Loaded asset-list with duration: ".concat(c," (was: ").concat(u,") ").concat(a));var d=this.waitingItem,h=(null==d?void 0:d.event.identifier)===s;this.updateSchedule();var f=null==(i=this.bufferingItem)?void 0:i.event;if(h){var v,g=this.schedule.findEventIndex(s),p=null==(v=this.schedule.items)?void 0:v[g];if(p){if(!this.playingItem&&this.timelinePos>p.end)if(this.schedule.findItemIndexAtTime(this.timelinePos)!==g)return a.error=new Error("Interstitial no longer within playback range ".concat(this.timelinePos," ").concat(a)),this.updateSchedule(!0),void this.primaryFallback(a);this.setBufferingItem(p)}this.setSchedulePosition(g)}else if((null==f?void 0:f.identifier)===s){var m=a.assetList[0];if(m){var y=this.getAssetPlayer(m.identifier);if(f.appendInPlace){var T=this.primaryMedia;y&&T&&this.bufferAssetPlayer(y,T)}else y&&y.loadSource()}}}}},{key:"onError",value:function(e,t){if(this.schedule)switch(t.details){case Z.ASSET_LIST_PARSING_ERROR:case Z.ASSET_LIST_LOAD_ERROR:case Z.ASSET_LIST_LOAD_TIMEOUT:var r=t.interstitial;r&&(this.updateSchedule(!0),this.primaryFallback(r));break;case Z.BUFFER_STALLED_ERROR:var i=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&i.event.appendInPlace)return void this.handleInPlaceStall(i.event);this.log("Primary player stall @".concat(this.timelinePos," bufferedPos: ").concat(this.bufferedPos)),this.onTimeupdate(),this.checkBuffer(!0)}}}])}(ve),qo=function(e){function t(e,r,i){var s;return a(this,t),(s=n(this,t,[e,r,i,"subtitle-stream-controller",oe])).currentTrackId=-1,s.tracksBuffered=[],s.mainDetails=null,s.registerListeners(),s}return d(t,e),o(t,[{key:"onHandlerDestroying",value:function(){this.unregisterListeners(),T(t,"onHandlerDestroying",this,3)([]),this.mainDetails=null}},{key:"registerListeners",value:function(){T(t,"registerListeners",this,3)([]);var e=this.hls;e.on(ee.LEVEL_LOADED,this.onLevelLoaded,this),e.on(ee.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(ee.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(ee.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(ee.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(ee.BUFFER_FLUSHING,this.onBufferFlushing,this)}},{key:"unregisterListeners",value:function(){T(t,"unregisterListeners",this,3)([]);var e=this.hls;e.off(ee.LEVEL_LOADED,this.onLevelLoaded,this),e.off(ee.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(ee.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(ee.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(ee.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(ee.BUFFER_FLUSHING,this.onBufferFlushing,this)}},{key:"startLoad",value:function(e,t){this.stopLoad(),this.state=hn,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}},{key:"onManifestLoading",value:function(){T(t,"onManifestLoading",this,3)([]),this.mainDetails=null}},{key:"onMediaDetaching",value:function(e,r){this.tracksBuffered=[],T(t,"onMediaDetaching",this,3)([e,r])}},{key:"onLevelLoaded",value:function(e,t){this.mainDetails=t.details}},{key:"onSubtitleFragProcessed",value:function(e,t){var r=t.frag,i=t.success;if(this.fragContextChanged(r)||(Oe(r)&&(this.fragPrevious=r),this.state=hn),i){var n=this.tracksBuffered[this.currentTrackId];if(n){for(var a,s=r.start,o=0;o<n.length;o++)if(s>=n[o].start&&s<=n[o].end){a=n[o];break}var l=r.start+r.duration;a?a.end=l:(a={start:s,end:l},n.push(a)),this.fragmentTracker.fragBuffered(r),this.fragBufferedComplete(r,null),this.media&&this.tick()}}}},{key:"onBufferFlushing",value:function(e,t){var r=t.startOffset,i=t.endOffset;if(0===r&&i!==Number.POSITIVE_INFINITY){var n=i-1;if(n<=0)return;t.endOffsetSubtitles=Math.max(0,n),this.tracksBuffered.forEach(function(e){for(var t=0;t<e.length;)if(e[t].end<=n)e.shift();else{if(!(e[t].start<n))break;e[t].start=n,t++}}),this.fragmentTracker.removeFragmentsInRange(r,n,oe)}}},{key:"onError",value:function(e,t){var r=t.frag;(null==r?void 0:r.type)===oe&&(t.details===Z.FRAG_GAP&&this.fragmentTracker.fragBuffered(r,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==dn&&(this.state=hn))}},{key:"onSubtitleTracksUpdated",value:function(e,t){var r=this,i=t.subtitleTracks;this.levels&&os(this.levels,i)?this.levels=i.map(function(e){return new Vt(e)}):(this.tracksBuffered=[],this.levels=i.map(function(e){var t=new Vt(e);return r.tracksBuffered[t.id]=[],t}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,oe),this.fragPrevious=null,this.mediaBuffer=null)}},{key:"onSubtitleTrackSwitch",value:function(e,t){var r;if(this.currentTrackId=t.id,null!=(r=this.levels)&&r.length&&-1!==this.currentTrackId){var i=this.levels[this.currentTrackId];null!=i&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.state!==dn&&this.setInterval(500)}else this.clearInterval()}},{key:"onSubtitleTrackLoaded",value:function(e,t){var r,i=this.currentTrackId,n=this.levels,a=t.details,s=t.id;if(n){var o=n[s];if(!(s>=n.length)&&o){this.log("Subtitle track ".concat(s," loaded [").concat(a.startSN,",").concat(a.endSN,"]").concat(a.lastPartSn?"[part-".concat(a.lastPartSn,"-").concat(a.lastPartIndex,"]"):"",",duration:").concat(a.totalduration)),this.mediaBuffer=this.mediaBufferTimeRanges;var l=0;if(a.live||null!=(r=o.details)&&r.live){if(a.deltaUpdateFailed)return;var u=this.mainDetails;if(!u)return void(this.startFragRequested=!1);var c,d=u.fragments[0];if(o.details)0===(l=this.alignPlaylists(a,o.details,null==(c=this.levelLastLoaded)?void 0:c.details))&&d&&zi(a,l=d.start);else a.hasProgramDateTime&&u.hasProgramDateTime?(on(a,u),l=a.fragmentStart):d&&zi(a,l=d.start);u&&!this.startFragRequested&&this.setStartPosition(u,l)}if(o.details=a,this.levelLastLoaded=o,s===i)if(this.hls.trigger(ee.SUBTITLE_TRACK_UPDATED,{details:a,id:s,groupId:t.groupId}),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===hn)er(null,a.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)}}else this.warn("Subtitle tracks were reset while loading level ".concat(s))}},{key:"_handleFragmentLoadComplete",value:function(e){var t=this,r=e.frag,i=e.payload,n=r.decryptdata,a=this.hls;if(!this.fragContextChanged(r)&&i&&i.byteLength>0&&null!=n&&n.key&&n.iv&&ai(n.method)){var s=performance.now();this.decrypter.decrypt(new Uint8Array(i),n.key.buffer,n.iv.buffer,si(n.method)).catch(function(e){throw a.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:r}),e}).then(function(e){var t=performance.now();a.trigger(ee.FRAG_DECRYPTED,{frag:r,payload:e,stats:{tstart:s,tdecrypt:t}})}).catch(function(e){t.warn("".concat(e.name,": ").concat(e.message)),t.state=hn})}}},{key:"doTick",value:function(){if(this.media){if(this.state===hn){var e=this.currentTrackId,t=this.levels,r=null==t?void 0:t[e];if(!r||!t.length||!r.details)return;if(this.waitForLive(r))return;var i=this.config,n=this.getLoadPosition(),a=jr.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,i.maxBufferHole),s=a.end,o=a.len,l=r.details;if(o>this.hls.maxBufferLength+l.levelTargetDuration)return;var u=l.fragments,c=u.length,d=l.edge,h=null,f=this.fragPrevious;if(s<d){var v=i.maxFragLookUpTolerance,g=s>d-v?0:v;!(h=er(f,u,Math.max(u[0].start,s),g))&&f&&f.start<u[0].start&&(h=u[0])}else h=u[c-1];if(!(h=this.filterReplacedPrimary(h,r.details)))return;var p=u[h.sn-l.startSN-1];if(p&&p.cc===h.cc&&this.fragmentTracker.getState(p)===Sr&&(h=p),this.fragmentTracker.getState(h)===Sr){var m=this.mapToInitFragWhenRequired(h);m&&this.loadFragment(m,r,s)}}}else this.state=hn}},{key:"loadFragment",value:function(e,r,i){Oe(e)?T(t,"loadFragment",this,3)([e,r,i]):this._loadInitSegment(e,r)}},{key:"mediaBufferTimeRanges",get:function(){return new Wo(this.tracksBuffered[this.currentTrackId]||[])}}])}(bn),Wo=o(function e(t){a(this,e),this.buffered=void 0;var r=function(e,r,i){if((r>>>=0)>i-1)throw new DOMException("Failed to execute '".concat(e,"' on 'TimeRanges': The index provided (").concat(r,") is greater than the maximum bound (").concat(i,")"));return t[r][e]};this.buffered={get length(){return t.length},end:function(e){return r("end",e,t.length)},start:function(e){return r("start",e,t.length)}}}),Yo={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},zo=function(e){return String.fromCharCode(Yo[e]||e)},Xo=15,Qo=100,$o={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Jo={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Zo={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},el={25:2,26:4,29:6,30:8,31:10,27:13,28:15},tl=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],rl=function(){return o(function e(){a(this,e),this.time=null,this.verboseLevel=0},[{key:"log",value:function(e,t){if(this.verboseLevel>=e){var r="function"==typeof t?t():t;Ee.log("".concat(this.time," [").concat(e,"] ").concat(r))}}}])}(),il=function(e){for(var t=[],r=0;r<e.length;r++)t.push(e[r].toString(16));return t},nl=function(){return o(function e(){a(this,e),this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1},[{key:"reset",value:function(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}},{key:"setStyles",value:function(e){for(var t=["foreground","underline","italics","background","flash"],r=0;r<t.length;r++){var i=t[r];e.hasOwnProperty(i)&&(this[i]=e[i])}}},{key:"isDefault",value:function(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}},{key:"equals",value:function(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}},{key:"copy",value:function(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}},{key:"toString",value:function(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}])}(),al=function(){return o(function e(){a(this,e),this.uchar=" ",this.penState=new nl},[{key:"reset",value:function(){this.uchar=" ",this.penState.reset()}},{key:"setChar",value:function(e,t){this.uchar=e,this.penState.copy(t)}},{key:"setPenState",value:function(e){this.penState.copy(e)}},{key:"equals",value:function(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}},{key:"copy",value:function(e){this.uchar=e.uchar,this.penState.copy(e.penState)}},{key:"isEmpty",value:function(){return" "===this.uchar&&this.penState.isDefault()}}])}(),sl=function(){return o(function e(t){a(this,e),this.chars=[],this.pos=0,this.currPenState=new nl,this.cueStartTime=null,this.logger=void 0;for(var r=0;r<Qo;r++)this.chars.push(new al);this.logger=t},[{key:"equals",value:function(e){for(var t=0;t<Qo;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}},{key:"copy",value:function(e){for(var t=0;t<Qo;t++)this.chars[t].copy(e.chars[t])}},{key:"isEmpty",value:function(){for(var e=!0,t=0;t<Qo;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}},{key:"setCursor",value:function(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>Qo&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Qo)}},{key:"moveCursor",value:function(e){var t=this.pos+e;if(e>1)for(var r=this.pos+1;r<t+1;r++)this.chars[r].setPenState(this.currPenState);this.setCursor(t)}},{key:"backSpace",value:function(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}},{key:"insertChar",value:function(e){var t=this;e>=144&&this.backSpace();var r=zo(e);this.pos>=Qo?this.logger.log(0,function(){return"Cannot insert "+e.toString(16)+" ("+r+") at position "+t.pos+". Skipping it!"}):(this.chars[this.pos].setChar(r,this.currPenState),this.moveCursor(1))}},{key:"clearFromPos",value:function(e){var t;for(t=e;t<Qo;t++)this.chars[t].reset()}},{key:"clear",value:function(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}},{key:"clearToEndOfRow",value:function(){this.clearFromPos(this.pos)}},{key:"getTextString",value:function(){for(var e=[],t=!0,r=0;r<Qo;r++){var i=this.chars[r].uchar;" "!==i&&(t=!1),e.push(i)}return t?"":e.join("")}},{key:"setPenStyles",value:function(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}])}(),ol=function(){return o(function e(t){a(this,e),this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(var r=0;r<Xo;r++)this.rows.push(new sl(t));this.logger=t},[{key:"reset",value:function(){for(var e=0;e<Xo;e++)this.rows[e].clear();this.currRow=14}},{key:"equals",value:function(e){for(var t=!0,r=0;r<Xo;r++)if(!this.rows[r].equals(e.rows[r])){t=!1;break}return t}},{key:"copy",value:function(e){for(var t=0;t<Xo;t++)this.rows[t].copy(e.rows[t])}},{key:"isEmpty",value:function(){for(var e=!0,t=0;t<Xo;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}},{key:"backSpace",value:function(){this.rows[this.currRow].backSpace()}},{key:"clearToEndOfRow",value:function(){this.rows[this.currRow].clearToEndOfRow()}},{key:"insertChar",value:function(e){this.rows[this.currRow].insertChar(e)}},{key:"setPen",value:function(e){this.rows[this.currRow].setPenStyles(e)}},{key:"moveCursor",value:function(e){this.rows[this.currRow].moveCursor(e)}},{key:"setCursor",value:function(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}},{key:"setPAC",value:function(e){this.logger.log(2,function(){return"pacData = "+Kt(e)});var t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(var r=0;r<Xo;r++)this.rows[r].clear();var i=this.currRow+1-this.nrRollUpRows,n=this.lastOutputScreen;if(n){var a=n.rows[i].cueStartTime,s=this.logger.time;if(null!==a&&null!==s&&a<s)for(var o=0;o<this.nrRollUpRows;o++)this.rows[t-this.nrRollUpRows+o+1].copy(n.rows[i+o])}}this.currRow=t;var l=this.rows[this.currRow];if(null!==e.indent){var u=e.indent,c=Math.max(u-1,0);l.setCursor(e.indent),e.color=l.chars[c].penState.foreground}var d={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(d)}},{key:"setBkgData",value:function(e){this.logger.log(2,function(){return"bkgData = "+Kt(e)}),this.backSpace(),this.setPen(e),this.insertChar(32)}},{key:"setRollUpRows",value:function(e){this.nrRollUpRows=e}},{key:"rollUp",value:function(){var e=this;if(null!==this.nrRollUpRows){this.logger.log(1,function(){return e.getDisplayText()});var t=this.currRow+1-this.nrRollUpRows,r=this.rows.splice(t,1)[0];r.clear(),this.rows.splice(this.currRow,0,r),this.logger.log(2,"Rolling up")}else this.logger.log(3,"roll_up but nrRollUpRows not set yet")}},{key:"getDisplayText",value:function(e){e=e||!1;for(var t=[],r="",i=-1,n=0;n<Xo;n++){var a=this.rows[n].getTextString();a&&(i=n+1,e?t.push("Row "+i+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(r=e?"["+t.join(" | ")+"]":t.join("\n")),r}},{key:"getTextAndFormat",value:function(){return this.rows}}])}(),ll=function(){return o(function e(t,r,i){a(this,e),this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=t,this.outputFilter=r,this.mode=null,this.verbose=0,this.displayedMemory=new ol(i),this.nonDisplayedMemory=new ol(i),this.lastOutputScreen=new ol(i),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i},[{key:"reset",value:function(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}},{key:"getHandler",value:function(){return this.outputFilter}},{key:"setHandler",value:function(e){this.outputFilter=e}},{key:"setPAC",value:function(e){this.writeScreen.setPAC(e)}},{key:"setBkgData",value:function(e){this.writeScreen.setBkgData(e)}},{key:"setMode",value:function(e){e!==this.mode&&(this.mode=e,this.logger.log(2,function(){return"MODE="+e}),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}},{key:"insertChars",value:function(e){for(var t=this,r=0;r<e.length;r++)this.writeScreen.insertChar(e[r]);var i=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,function(){return i+": "+t.writeScreen.getDisplayText(!0)}),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,function(){return"DISPLAYED: "+t.displayedMemory.getDisplayText(!0)}),this.outputDataUpdate())}},{key:"ccRCL",value:function(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}},{key:"ccBS",value:function(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}},{key:"ccAOF",value:function(){}},{key:"ccAON",value:function(){}},{key:"ccDER",value:function(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}},{key:"ccRU",value:function(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}},{key:"ccFON",value:function(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}},{key:"ccRDC",value:function(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}},{key:"ccTR",value:function(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}},{key:"ccRTD",value:function(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}},{key:"ccEDM",value:function(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}},{key:"ccCR",value:function(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}},{key:"ccENM",value:function(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}},{key:"ccEOC",value:function(){var e=this;if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){var t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,function(){return"DISP: "+e.displayedMemory.getDisplayText()})}this.outputDataUpdate(!0)}},{key:"ccTO",value:function(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}},{key:"ccMIDROW",value:function(e){var t={flash:!1};if(t.underline=e%2==1,t.italics=e>=46,t.italics)t.foreground="white";else{var r=Math.floor(e/2)-16;t.foreground=["white","green","blue","cyan","red","yellow","magenta"][r]}this.logger.log(2,"MIDROW: "+Kt(t)),this.writeScreen.setPen(t)}},{key:"outputDataUpdate",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))}},{key:"cueSplitAtTime",value:function(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}])}(),ul=function(){return o(function e(t,r,i){a(this,e),this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;var n=this.logger=new rl;this.channels=[null,new ll(t,r,n),new ll(t+1,i,n)]},[{key:"getHandler",value:function(e){return this.channels[e].getHandler()}},{key:"setHandler",value:function(e,t){this.channels[e].setHandler(t)}},{key:"addData",value:function(e,t){var r=this;this.logger.time=e;for(var i=function(e){var i=127&t[e],n=127&t[e+1],a=!1,s=null;if(0===i&&0===n)return 0;r.logger.log(3,function(){return"["+il([t[e],t[e+1]])+"] -> ("+il([i,n])+")"});var o=r.cmdHistory;if(i>=16&&i<=31){if(function(e,t,r){return r.a===e&&r.b===t}(i,n,o))return cl(null,null,o),r.logger.log(3,function(){return"Repeated command ("+il([i,n])+") is dropped"}),0;cl(i,n,r.cmdHistory),(a=r.parseCmd(i,n))||(a=r.parseMidrow(i,n)),a||(a=r.parsePAC(i,n)),a||(a=r.parseBackgroundAttributes(i,n))}else cl(null,null,o);if(!a&&(s=r.parseChars(i,n))){var l=r.currentChannel;if(l&&l>0)r.channels[l].insertChars(s);else r.logger.log(2,"No channel found yet. TEXT-MODE?")}a||s||r.logger.log(2,function(){return"Couldn't parse cleaned data "+il([i,n])+" orig: "+il([t[e],t[e+1]])})},n=0;n<t.length;n+=2)i(n)}},{key:"parseCmd",value:function(e,t){if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=33&&t<=35))return!1;var r=20===e||21===e||23===e?1:2,i=this.channels[r];return 20===e||21===e||28===e||29===e?32===t?i.ccRCL():33===t?i.ccBS():34===t?i.ccAOF():35===t?i.ccAON():36===t?i.ccDER():37===t?i.ccRU(2):38===t?i.ccRU(3):39===t?i.ccRU(4):40===t?i.ccFON():41===t?i.ccRDC():42===t?i.ccTR():43===t?i.ccRTD():44===t?i.ccEDM():45===t?i.ccCR():46===t?i.ccENM():47===t&&i.ccEOC():i.ccTO(t-32),this.currentChannel=r,!0}},{key:"parseMidrow",value:function(e,t){var r=0;if((17===e||25===e)&&t>=32&&t<=47){if((r=17===e?1:2)!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;var i=this.channels[r];return!!i&&(i.ccMIDROW(t),this.logger.log(3,function(){return"MIDROW ("+il([e,t])+")"}),!0)}return!1}},{key:"parsePAC",value:function(e,t){var r;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127)&&!((16===e||24===e)&&t>=64&&t<=95))return!1;var i=e<=23?1:2;r=t>=64&&t<=95?1===i?$o[e]:Zo[e]:1===i?Jo[e]:el[e];var n=this.channels[i];return!!n&&(n.setPAC(this.interpretPAC(r,t)),this.currentChannel=i,!0)}},{key:"interpretPAC",value:function(e,t){var r,i={color:null,italics:!1,indent:null,underline:!1,row:e};return r=t>95?t-96:t-64,i.underline=!(1&~r),r<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(i.italics=!0,i.color="white"):i.indent=4*Math.floor((r-16)/2),i}},{key:"parseChars",value:function(e,t){var r,i,n=null,a=null;(e>=25?(r=2,a=e-8):(r=1,a=e),a>=17&&a<=19)?(i=17===a?t+80:18===a?t+112:t+144,this.logger.log(2,function(){return"Special char '"+zo(i)+"' in channel "+r}),n=[i]):e>=32&&e<=127&&(n=0===t?[e]:[e,t]);return n&&this.logger.log(3,function(){return"Char codes = "+il(n).join(",")}),n}},{key:"parseBackgroundAttributes",value:function(e,t){var r;if(!((16===e||24===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=45&&t<=47))return!1;var i={};16===e||24===e?(r=Math.floor((t-32)/2),i.background=tl[r],t%2==1&&(i.background=i.background+"_semi")):45===t?i.background="transparent":(i.foreground="black",47===t&&(i.underline=!0));var n=e<=23?1:2;return this.channels[n].setBkgData(i),!0}},{key:"reset",value:function(){for(var e=0;e<Object.keys(this.channels).length;e++){var t=this.channels[e];t&&t.reset()}cl(null,null,this.cmdHistory)}},{key:"cueSplitAtTime",value:function(e){for(var t=0;t<this.channels.length;t++){var r=this.channels[t];r&&r.cueSplitAtTime(e)}}}])}();function cl(e,t,r){r.a=e,r.b=t}var dl=function(){if(null!=di&&di.VTTCue)return self.VTTCue;var e=["","lr","rl"],t=["start","middle","end","left","right"];function r(e,t){if("string"!=typeof t)return!1;if(!Array.isArray(e))return!1;var r=t.toLowerCase();return!!~e.indexOf(r)&&r}function i(e){return r(t,e)}function n(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];for(var n=1;n<arguments.length;n++){var a=arguments[n];for(var s in a)e[s]=a[s]}return e}function a(t,a,s){var o=this,l={enumerable:!0};o.hasBeenReset=!1;var u="",c=!1,d=t,h=a,f=s,v=null,g="",p=!0,m="auto",y="start",T=50,E="middle",k=50,S="middle";Object.defineProperty(o,"id",n({},l,{get:function(){return u},set:function(e){u=""+e}})),Object.defineProperty(o,"pauseOnExit",n({},l,{get:function(){return c},set:function(e){c=!!e}})),Object.defineProperty(o,"startTime",n({},l,{get:function(){return d},set:function(e){if("number"!=typeof e)throw new TypeError("Start time must be set to a number.");d=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",n({},l,{get:function(){return h},set:function(e){if("number"!=typeof e)throw new TypeError("End time must be set to a number.");h=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",n({},l,{get:function(){return f},set:function(e){f=""+e,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",n({},l,{get:function(){return v},set:function(e){v=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",n({},l,{get:function(){return g},set:function(t){var 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 T},set:function(e){if(e<0||e>100)throw new Error("Position must be between 0 and 100.");T=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 k},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");k=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",n({},l,{get:function(){return S},set:function(e){var t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");S=t,this.hasBeenReset=!0}})),o.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}(),hl=function(){return o(function e(){a(this,e)},[{key:"decode",value:function(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}])}();function fl(e){function t(e,t,r,i){return 3600*(0|e)+60*(0|t)+(0|r)+parseFloat(i||0)}var r=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return r?parseFloat(r[2])>59?t(r[2],r[3],0,r[4]):t(r[1],r[2],r[3],r[4]):null}var vl=function(){return o(function e(){a(this,e),this.values=Object.create(null)},[{key:"set",value:function(e,t){this.get(e)||""===t||(this.values[e]=t)}},{key:"get",value:function(e,t,r){return r?this.has(e)?this.values[e]:t[r]:this.has(e)?this.values[e]:t}},{key:"has",value:function(e){return e in this.values}},{key:"alt",value:function(e,t,r){for(var i=0;i<r.length;++i)if(t===r[i]){this.set(e,t);break}}},{key:"integer",value:function(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}},{key:"percent",value:function(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){var r=parseFloat(t);if(r>=0&&r<=100)return this.set(e,r),!0}return!1}}])}();function gl(e,t,r,i){var n=i?e.split(i):[e];for(var a in n)if("string"==typeof n[a]){var s=n[a].split(r);if(2===s.length)t(s[0],s[1])}}var pl=new dl(0,0,""),ml="middle"===pl.align?"middle":"center";function yl(e,t,r){var i=e;function n(){var t=fl(e);if(null===t)throw new Error("Malformed timestamp: "+i);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function a(){e=e.replace(/^\s+/,"")}if(a(),t.startTime=n(),a(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+i);e=e.slice(3),a(),t.endTime=n(),a(),function(e,t){var i=new vl;gl(e,function(e,t){var n;switch(e){case"region":for(var a=r.length-1;a>=0;a--)if(r[a].id===t){i.set(e,r[a].region);break}break;case"vertical":i.alt(e,t,["rl","lr"]);break;case"line":n=t.split(","),i.integer(e,n[0]),i.percent(e,n[0])&&i.set("snapToLines",!1),i.alt(e,n[0],["auto"]),2===n.length&&i.alt("lineAlign",n[1],["start",ml,"end"]);break;case"position":n=t.split(","),i.percent(e,n[0]),2===n.length&&i.alt("positionAlign",n[1],["start",ml,"end","line-left","line-right","auto"]);break;case"size":i.percent(e,t);break;case"align":i.alt(e,t,["start",ml,"end","left","right"])}},/:/,/\s/),t.region=i.get("region",null),t.vertical=i.get("vertical","");var n=i.get("line","auto");"auto"===n&&-1===pl.line&&(n=-1),t.line=n,t.lineAlign=i.get("lineAlign","start"),t.snapToLines=i.get("snapToLines",!0),t.size=i.get("size",100),t.align=i.get("align",ml);var a=i.get("position","auto");"auto"===a&&50===pl.position&&(a="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=a}(e,t)}function Tl(e){return e.replace(/<br(?: \/)?>/gi,"\n")}var El=function(){return o(function e(){a(this,e),this.state="INITIAL",this.buffer="",this.decoder=new hl,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0},[{key:"parse",value:function(e){var t=this;function r(){var e=t.buffer,r=0;for(e=Tl(e);r<e.length&&"\r"!==e[r]&&"\n"!==e[r];)++r;var i=e.slice(0,r);return"\r"===e[r]&&++r,"\n"===e[r]&&++r,t.buffer=e.slice(r),i}function i(e){gl(e,function(e,t){},/:/)}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{var n="";if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;var a=(n=r()).match(/^()?WEBVTT([ \t].*)?$/);if(null==a||!a[0])throw new Error("Malformed WebVTT signature.");t.state="HEADER"}for(var s=!1;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(s?s=!1:n=r(),t.state){case"HEADER":/:/.test(n)?i(n):n||(t.state="ID");continue;case"NOTE":n||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(n)){t.state="NOTE";break}if(!n)continue;if(t.cue=new dl(0,0,""),t.state="CUE",-1===n.indexOf("--\x3e")){t.cue.id=n;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{yl(n,t.cue,t.regionList)}catch(e){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":var o=-1!==n.indexOf("--\x3e");if(!n||o&&(s=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(null===t.cue)continue;t.cue.text&&(t.cue.text+="\n"),t.cue.text+=n;continue;case"BADCUE":n||(t.state="ID")}}}catch(e){"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this}},{key:"flush",value:function(){var e=this;try{if((e.cue||"HEADER"===e.state)&&(e.buffer+="\n\n",e.parse()),"INITIAL"===e.state||"BADWEBVTT"===e.state)throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}])}(),kl=/\r\n|\n\r|\n|\r/g,Sl=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;return e.slice(r,r+t.length)===t};function bl(e,t,r){return Po(e.toString())+Po(t.toString())+Po(r)}function Al(e,t,r,i,n,a,s){var o,l=new El,u=be(new Uint8Array(e)).trim().replace(kl,"\n").split("\n"),c=[],d=t?function(e){return Ua(e,9e4,1/(arguments.length>1&&void 0!==arguments[1]?arguments[1]:1))}(t.baseTime,t.timescale):0,h="00:00.000",f=0,v=0,g=!0;l.oncue=function(e){var a=r[i],s=r.ccOffset,l=(f-d)/9e4;if(null!=a&&a.new&&(void 0!==v?s=r.ccOffset=a.start:function(e,t,r){var i=e[t],n=e[i.prevCC];if(!n||!n.new&&i.new)return e.ccOffset=e.presentationOffset=i.start,void(i.new=!1);for(;null!=(a=n)&&a.new;){var a;e.ccOffset+=i.start-n.start,i.new=!1,n=e[(i=n).prevCC]}e.presentationOffset=r}(r,i,l)),l){if(!t)return void(o=new Error("Missing initPTS for VTT MPEGTS"));s=l-r.presentationOffset}var u=e.endTime-e.startTime,h=ja(9e4*(e.startTime+s-v),9e4*n)/9e4;e.startTime=Math.max(h,0),e.endTime=Math.max(h+u,0);var g=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(g)),e.id||(e.id=bl(e.startTime,e.endTime,g)),e.endTime>0&&c.push(e)},l.onparsingerror=function(e){o=e},l.onflush=function(){o?s(o):a(c)},u.forEach(function(e){if(g){if(Sl(e,"X-TIMESTAMP-MAP=")){g=!1,e.slice(16).split(",").forEach(function(e){Sl(e,"LOCAL:")?h=e.slice(6):Sl(e,"MPEGTS:")&&(f=parseInt(e.slice(7)))});try{v=function(e){var t=parseInt(e.slice(-3)),r=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),n=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(X(t)&&X(r)&&X(i)&&X(n)))throw Error("Malformed X-TIMESTAMP-MAP: Local:".concat(e));return t+=1e3*r,t+=6e4*i,t+36e5*n}(h)/1e3}catch(e){o=e}return}""===e&&(g=!1)}l.parse(e+"\n")}),l.flush()}var Ll="stpp.ttml.im1t",Rl=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Il=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,wl={left:"start",center:"center",right:"end",start:"start",end:"end"};function Pl(e,t,r,i){var n=Ye(new Uint8Array(e),["mdat"]);if(0!==n.length){var a=n.map(function(e){return be(e)}),s=function(e,t){return Ua(e,t,1/(arguments.length>2&&void 0!==arguments[2]?arguments[2]:1),arguments.length>3&&void 0!==arguments[3]&&arguments[3])}(t.baseTime,1,t.timescale);try{a.forEach(function(e){return r(function(e,t){var r=(new DOMParser).parseFromString(e,"text/xml"),i=r.getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");var n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(n).reduce(function(e,t){return e[t]=i.getAttribute("ttp:".concat(t))||n[t],e},{}),s="preserve"!==i.getAttribute("xml:space"),o=xl(Dl(i,"styling","style")),l=xl(Dl(i,"layout","region")),u=Dl(i,"body","[begin]");return[].map.call(u,function(e){var r=Cl(e,s);if(!r||!e.hasAttribute("begin"))return null;var i=Ol(e.getAttribute("begin"),a),n=Ol(e.getAttribute("dur"),a),u=Ol(e.getAttribute("end"),a);if(null===i)throw Ml(e);if(null===u){if(null===n)throw Ml(e);u=i+n}var c=new dl(i-t,u-t,r);c.id=bl(c.startTime,c.endTime,c.text);var d=function(e,t,r){var i="http://www.w3.org/ns/ttml#styling",n=null,a=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],s=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;s&&r.hasOwnProperty(s)&&(n=r[s]);return a.reduce(function(r,a){var s=_l(t,i,a)||_l(e,i,a)||_l(n,i,a);return s&&(r[a]=s),r},{})}(l[e.getAttribute("region")],o[e.getAttribute("style")],o),h=d.textAlign;if(h){var f=wl[h];f&&(c.lineAlign=f),c.align=h}return de(c,d),c}).filter(function(e){return null!==e})}(e,s))})}catch(e){i(e)}}else i(new Error("Could not parse IMSC1 mdat"))}function Dl(e,t,r){var i=e.getElementsByTagName(t)[0];return i?[].slice.call(i.querySelectorAll(r)):[]}function xl(e){return e.reduce(function(e,t){var r=t.getAttribute("xml:id");return r&&(e[r]=t),e},{})}function Cl(e,t){return[].slice.call(e.childNodes).reduce(function(e,r,i){var n;return"br"===r.nodeName&&i?e+"\n":null!=(n=r.childNodes)&&n.length?Cl(r,t):t?e+r.textContent.trim().replace(/\s+/g," "):e+r.textContent},"")}function _l(e,t,r){return e&&e.hasAttributeNS(t,r)?e.getAttributeNS(t,r):null}function Ml(e){return new Error("Could not parse ttml timestamp ".concat(e))}function Ol(e,t){if(!e)return null;var r=fl(e);return null===r&&(Rl.test(e)?r=function(e,t){var r=Rl.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):Il.test(e)&&(r=function(e,t){var r=Il.exec(e),i=Number(r[1]);switch(r[2]){case"h":return 3600*i;case"m":return 60*i;case"ms":return 1e3*i;case"f":return i/t.frameRate;case"t":return i/t.tickRate}return i}(e,t))),r}var Fl=function(){return o(function e(t,r){a(this,e),this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=t,this.trackName=r},[{key:"dispatchCue",value:function(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}},{key:"newCue",value:function(e,t,r){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=r,this.timelineController.createCaptionsTrack(this.trackName)}},{key:"reset",value:function(){this.cueRanges=[],this.startTime=null}}])}(),Ul=function(){return o(function e(t){a(this,e),this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=t,this.config=t.config,this.Cues=t.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},t.on(ee.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(ee.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ee.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(ee.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(ee.FRAG_LOADING,this.onFragLoading,this),t.on(ee.FRAG_LOADED,this.onFragLoaded,this),t.on(ee.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(ee.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(ee.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(ee.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(ee.BUFFER_FLUSHING,this.onBufferFlushing,this)},[{key:"destroy",value:function(){var e=this.hls;e.off(ee.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(ee.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(ee.FRAG_LOADING,this.onFragLoading,this),e.off(ee.FRAG_LOADED,this.onFragLoaded,this),e.off(ee.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(ee.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(ee.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(ee.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(ee.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}},{key:"initCea608Parsers",value:function(){var e=new Fl(this,"textTrack1"),t=new Fl(this,"textTrack2"),r=new Fl(this,"textTrack3"),i=new Fl(this,"textTrack4");this.cea608Parser1=new ul(1,e,t),this.cea608Parser2=new ul(3,r,i)}},{key:"addCues",value:function(e,t,r,i,n){for(var a=!1,s=n.length;s--;){var o=n[s],l=Vl(o[0],o[1],t,r);if(l>=0&&(o[0]=Math.min(o[0],t),o[1]=Math.max(o[1],r),a=!0,l/(r-t)>.5))return}if(a||n.push([t,r]),this.config.renderTextTracksNatively){var u=this.captionsTracks[e];this.Cues.newCue(u,t,r,i)}else{var c=this.Cues.newCue(null,t,r,i);this.hls.trigger(ee.CUES_PARSED,{type:"captions",cues:c,track:e})}}},{key:"onInitPtsFound",value:function(e,t){var r=this,i=t.frag,n=t.id,a=t.initPTS,s=t.timescale,o=t.trackId,l=this.unparsedVttFrags;n===ae&&(this.initPTS[i.cc]={baseTime:a,timescale:s,trackId:o}),l.length&&(this.unparsedVttFrags=[],l.forEach(function(e){r.initPTS[e.frag.cc]?r.onFragLoaded(ee.FRAG_LOADED,e):r.hls.trigger(ee.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}},{key:"getExistingTrack",value:function(e,t){var r=this.media;if(r)for(var i=0;i<r.textTracks.length;i++){var n=r.textTracks[i];if(Bl(n,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return n}return null}},{key:"createCaptionsTrack",value:function(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}},{key:"createNativeTrack",value:function(e){if(!this.captionsTracks[e]){var t=this.captionsProperties,r=this.captionsTracks,i=this.media,n=t[e],a=n.label,s=n.languageCode,o=this.getExistingTrack(a,s);if(o)r[e]=o,Lo(r[e]),bo(r[e],i);else{var l=this.createTextTrack("captions",a,s);l&&(l[e]=!0,r[e]=l)}}}},{key:"createNonNativeTrack",value:function(e){if(!this.nonNativeCaptionsTracks[e]){var t=this.captionsProperties[e];if(t){var r={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=r,this.hls.trigger(ee.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[r]})}}}},{key:"createTextTrack",value:function(e,t,r){var i=this.media;if(i)return i.addTextTrack(e,t,r)}},{key:"onMediaAttaching",value:function(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}},{key:"onMediaDetaching",value:function(e,t){var r=!!t.transferMedia;if(this.media=null,!r){var i=this.captionsTracks;Object.keys(i).forEach(function(e){Lo(i[e]),delete i[e]}),this.nonNativeCaptionsTracks={}}}},{key:"onManifestLoading",value:function(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}},{key:"_cleanTracks",value:function(){var e=this.media;if(e){var t=e.textTracks;if(t)for(var r=0;r<t.length;r++)Lo(t[r])}}},{key:"onSubtitleTracksUpdated",value:function(e,t){var r=this,i=t.subtitleTracks||[],n=i.some(function(e){return e.textCodec===Ll});if(this.config.enableWebVTT||n&&this.config.enableIMSC1){if(os(this.tracks,i))return void(this.tracks=i);if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){var a=this.media,s=a?Io(a.textTracks):null;if(this.tracks.forEach(function(e,t){var i;if(s){for(var n=null,a=0;a<s.length;a++)if(s[a]&&Bl(s[a],e)){n=s[a],s[a]=null;break}n&&(i=n)}if(i)Lo(i);else{var o=Nl(e);(i=r.createTextTrack(o,e.name,e.lang))&&(i.mode="disabled")}i&&r.textTracks.push(i)}),null!=s&&s.length){var o=s.filter(function(e){return null!==e}).map(function(e){return e.label});o.length&&this.hls.logger.warn("Media element contains unused subtitle tracks: ".concat(o.join(", "),". Replace media element for each source to clear TextTracks and captions menu."))}}else if(this.tracks.length){var l=this.tracks.map(function(e){return{label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e}});this.hls.trigger(ee.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:l})}}}},{key:"onManifestLoaded",value:function(e,t){var r=this;this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(function(e){var t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(t){var i="textTrack".concat(t[1]),n=r.captionsProperties[i];n&&(n.label=e.name,e.lang&&(n.languageCode=e.lang),n.media=e)}})}},{key:"closedCaptionsForLevel",value:function(e){var t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]}},{key:"onFragLoading",value:function(e,t){if(this.enabled&&t.frag.type===ae){var r,i,n=this.cea608Parser1,a=this.cea608Parser2,s=this.lastSn,o=t.frag,l=o.cc,u=o.sn,c=null!=(r=null==(i=t.part)?void 0:i.index)?r:-1;n&&a&&(u!==s+1||u===s&&c!==this.lastPartIndex+1||l!==this.lastCc)&&(n.reset(),a.reset()),this.lastCc=l,this.lastSn=u,this.lastPartIndex=c}}},{key:"onFragLoaded",value:function(e,t){var r=t.frag,i=t.payload;if(r.type===oe)if(i.byteLength){var n=r.decryptdata,a="stats"in t;if(null==n||!n.encrypted||a){var s=this.tracks[r.level],o=this.vttCCs;o[r.cc]||(o[r.cc]={start:r.start,prevCC:this.prevCC,new:!0},this.prevCC=r.cc),s&&s.textCodec===Ll?this._parseIMSC1(r,i):this._parseVTTs(t)}}else this.hls.trigger(ee.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:new Error("Empty subtitle payload")})}},{key:"_parseIMSC1",value:function(e,t){var r=this,i=this.hls;Pl(t,this.initPTS[e.cc],function(t){r._appendCues(t,e.level),i.trigger(ee.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},function(t){i.logger.log("Failed to parse IMSC1: ".concat(t)),i.trigger(ee.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})})}},{key:"_parseVTTs",value:function(e){var t,r=this,i=e.frag,n=e.payload,a=this.initPTS,s=this.unparsedVttFrags,o=a.length-1;if(a[i.cc]||-1!==o){var l=this.hls;Al(null!=(t=i.initSegment)&&t.data?it(i.initSegment.data,new Uint8Array(n)).buffer:n,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,function(e){r._appendCues(e,i.level),l.trigger(ee.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},function(t){var a="Missing initPTS for VTT MPEGTS"===t.message;a?s.push(e):r._fallbackToIMSC1(i,n),l.logger.log("Failed to parse VTT cue: ".concat(t)),a&&o>i.cc||l.trigger(ee.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:t})})}else s.push(e)}},{key:"_fallbackToIMSC1",value:function(e,t){var r=this,i=this.tracks[e.level];i.textCodec||Pl(t,this.initPTS[e.cc],function(){i.textCodec=Ll,r._parseIMSC1(e,t)},function(){i.textCodec="wvtt"})}},{key:"_appendCues",value:function(e,t){var r=this.hls;if(this.config.renderTextTracksNatively){var i=this.textTracks[t];if(!i||"disabled"===i.mode)return;e.forEach(function(e){return Ao(i,e)})}else{var n=this.tracks[t];if(!n)return;var a=n.default?"default":"subtitles"+t;r.trigger(ee.CUES_PARSED,{type:"subtitles",cues:e,track:a})}}},{key:"onFragDecrypted",value:function(e,t){t.frag.type===oe&&this.onFragLoaded(ee.FRAG_LOADED,t)}},{key:"onSubtitleTracksCleared",value:function(){this.tracks=[],this.captionsTracks={}}},{key:"onFragParsingUserdata",value:function(e,t){if(this.enabled&&this.config.enableCEA708Captions){var r=t.frag,i=t.samples;if(r.type!==ae||"NONE"!==this.closedCaptionsForLevel(r))for(var n=0;n<i.length;n++){var a=i[n].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();var s=this.extractCea608Data(a);this.cea608Parser1.addData(i[n].pts,s[0]),this.cea608Parser2.addData(i[n].pts,s[1])}}}}},{key:"onBufferFlushing",value:function(e,t){var r=t.startOffset,i=t.endOffset,n=t.endOffsetSubtitles,a=t.type,s=this.media;if(s&&!(s.currentTime<i)){if(!a||"video"===a){var o=this.captionsTracks;Object.keys(o).forEach(function(e){return Ro(o[e],r,i)})}if(this.config.renderTextTracksNatively&&0===r&&void 0!==n){var l=this.textTracks;Object.keys(l).forEach(function(e){return Ro(l[e],r,n)})}}}},{key:"extractCea608Data",value:function(e){for(var t=[[],[]],r=31&e[0],i=2,n=0;n<r;n++){var a=e[i++],s=127&e[i++],o=127&e[i++];if(0!==s||0!==o)if(!!(4&a)){var l=3&a;0!==l&&1!==l||(t[l].push(s),t[l].push(o))}}return t}}])}();function Nl(e){return e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function Bl(e,t){return!!e&&e.kind===Nl(t)&&us(t,e)}function Vl(e,t,r,i){return Math.min(t,i)-Math.max(e,r)}var Gl=/\s/,Hl={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++)Gl.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=Tl(l.trim()),g=bl(t,r,v);null!=e&&null!=(h=e.cues)&&h.getCueById(g)||((a=new c(t,r,v)).id=g,a.line=d+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*o/32)),u.push(a))}return e&&u.length&&(u.sort(function(e,t){return"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line}),u.forEach(function(t){return Ao(e,t)})),u}};var Kl=/(\d+)-(\d+)\/(\d+)/,jl=function(){return o(function e(t){a(this,e),this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=t.fetchSetup||ql,this.controller=new self.AbortController,this.stats=new De},[{key:"destroy",value:function(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}},{key:"abortInternal",value:function(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}},{key:"abort",value:function(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}},{key:"load",value:function(e,t,r){var i=this,n=this.stats;if(n.loading.start)throw new Error("Loader can only be used once.");n.loading.start=self.performance.now();var a=function(e,t){var r={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(de({},e.headers))};e.rangeEnd&&r.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return r}(e,this.controller.signal),s="arraybuffer"===e.responseType,o=s?"byteLength":"length",l=t.loadPolicy,u=l.maxTimeToFirstByteMs,c=l.maxLoadTimeMs;this.context=e,this.config=t,this.callbacks=r,this.request=this.fetchSetup(e,a),self.clearTimeout(this.requestTimeout),t.timeout=u&&X(u)?u:c,this.requestTimeout=self.setTimeout(function(){i.callbacks&&(i.abortInternal(),i.callbacks.onTimeout(n,e,i.response))},t.timeout),(es(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(function(r){var a;i.response=i.loader=r;var o=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(i.requestTimeout),t.timeout=c,i.requestTimeout=self.setTimeout(function(){i.callbacks&&(i.abortInternal(),i.callbacks.onTimeout(n,e,i.response))},c-(o-n.loading.start)),!r.ok){var l=r.status,u=r.statusText;throw new Wl(u||"fetch, bad network response",l,r)}n.loading.first=o,n.total=function(e){var t=e.get("Content-Range");if(t){var r=function(e){var t=Kl.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(X(r))return r}var i=e.get("Content-Length");if(i)return parseInt(i)}(r.headers)||n.total;var d=null==(a=i.callbacks)?void 0:a.onProgress;return d&&X(t.highWaterMark)?i.loadProgressively(r,n,e,t.highWaterMark,d):s?r.arrayBuffer():"json"===e.responseType?r.json():r.text()}).then(function(r){var a,s,l=i.response;if(!l)throw new Error("loader destroyed");self.clearTimeout(i.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);var u=r[o];u&&(n.loaded=n.total=u);var c={url:l.url,data:r,code:l.status},d=null==(a=i.callbacks)?void 0:a.onProgress;d&&!X(t.highWaterMark)&&d(n,e,r,l),null==(s=i.callbacks)||s.onSuccess(c,n,e,l)}).catch(function(t){var r;if(self.clearTimeout(i.requestTimeout),!n.aborted){var a=t&&t.code||0,s=t?t.message:null;null==(r=i.callbacks)||r.onError({code:a,text:s},e,t?t.details:null,n)}})}},{key:"getCacheAge",value:function(){var e=null;if(this.response){var t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}},{key:"getResponseHeader",value:function(e){return this.response?this.response.headers.get(e):null}},{key:"loadProgressively",value:function(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,n=arguments.length>4?arguments[4]:void 0,a=new Ln,s=e.body.getReader(),o=function(){return s.read().then(function(s){if(s.done)return a.dataLength&&n(t,r,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));var l=s.value,u=l.length;return t.loaded+=u,u<i||a.dataLength?(a.push(l),a.dataLength>=i&&n(t,r,a.flush().buffer,e)):n(t,r,l.buffer,e),o()}).catch(function(){return Promise.reject()})};return o()}}])}();function ql(e,t){return new self.Request(e.url,t)}var Wl=function(e){function t(e,r,i){var s;return a(this,t),(s=n(this,t,[e])).code=void 0,s.details=void 0,s.code=r,s.details=i,s}return d(t,e),o(t)}(L(Error)),Yl=/^age:\s*[\d.]+\s*$/im,zl=function(){return o(function e(t){a(this,e),this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=t&&t.xhrSetup||null,this.stats=new De,this.retryDelay=0},[{key:"destroy",value:function(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}},{key:"abortInternal",value:function(){var e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))}},{key:"abort",value:function(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}},{key:"load",value:function(e,t,r){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=r,this.loadInternal()}},{key:"loadInternal",value:function(){var e=this,t=this.config,r=this.context;if(t&&r){var i=this.loader=new self.XMLHttpRequest,n=this.stats;n.loading.first=0,n.loaded=0,n.aborted=!1;var a=this.xhrSetup;a?Promise.resolve().then(function(){if(e.loader===i&&!e.stats.aborted)return a(i,r.url)}).catch(function(t){if(e.loader===i&&!e.stats.aborted)return i.open("GET",r.url,!0),a(i,r.url)}).then(function(){e.loader!==i||e.stats.aborted||e.openAndSendXhr(i,r,t)}).catch(function(t){var a;null==(a=e.callbacks)||a.onError({code:i.status,text:t.message},r,i,n)}):this.openAndSendXhr(i,r,t)}}},{key:"openAndSendXhr",value:function(e,t,r){e.readyState||e.open("GET",t.url,!0);var i=t.headers,n=r.loadPolicy,a=n.maxTimeToFirstByteMs,s=n.maxLoadTimeMs;if(i)for(var o in i)e.setRequestHeader(o,i[o]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),r.timeout=a&&X(a)?a:s,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),e.send()}},{key:"readystatechange",value:function(){var e=this.context,t=this.loader,r=this.stats;if(e&&t){var i=t.readyState,n=this.config;if(!r.aborted&&i>=2&&(0===r.loading.first&&(r.loading.first=Math.max(self.performance.now(),r.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(r.loading.first-r.loading.start)))),4===i)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;var a=t.status,s="text"===t.responseType?t.responseText:null;if(a>=200&&a<300){var o=null!=s?s:t.response;if(null!=o){var l,u;r.loading.end=Math.max(self.performance.now(),r.loading.first);var c="arraybuffer"===t.responseType?o.byteLength:o.length;r.loaded=r.total=c,r.bwEstimate=8e3*r.total/(r.loading.end-r.loading.first);var d=null==(l=this.callbacks)?void 0:l.onProgress;d&&d(r,e,o,t);var h={url:t.responseURL,data:o,code:a};return void(null==(u=this.callbacks)||u.onSuccess(h,r,e,t))}}var f,v=n.loadPolicy.errorRetry;if(cr(v,r.retry,!1,{url:e.url,data:void 0,code:a}))this.retry(v);else Ee.error("".concat(a," while loading ").concat(e.url)),null==(f=this.callbacks)||f.onError({code:a,text:t.statusText},e,t,r)}}}},{key:"loadtimeout",value:function(){if(this.config){var e=this.config.loadPolicy.timeoutRetry;if(cr(e,this.stats.retry,!0))this.retry(e);else{var t;Ee.warn("timeout while loading ".concat(null==(t=this.context)?void 0:t.url));var r=this.callbacks;r&&(this.abortInternal(),r.onTimeout(this.stats,this.context,this.loader))}}}},{key:"retry",value:function(e){var t=this.context,r=this.stats;this.retryDelay=lr(e,r.retry),r.retry++,Ee.warn("".concat(status?"HTTP Status "+status:"Timeout"," while loading ").concat(null==t?void 0:t.url,", retrying ").concat(r.retry,"/").concat(e.maxNumRetry," in ").concat(this.retryDelay,"ms")),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}},{key:"loadprogress",value:function(e){var t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}},{key:"getCacheAge",value:function(){var e=null;if(this.loader&&Yl.test(this.loader.getAllResponseHeaders())){var t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}},{key:"getResponseHeader",value:function(e){return this.loader&&new RegExp("^".concat(e,":\\s*[\\d.]+\\s*$"),"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}])}(),Xl=fe(fe({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:zl,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Jt,bufferController:gs,capLevelController:ys,errorController:Er,fpsController:So,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:ki,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},{cueHandler:Hl,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:qo,subtitleTrackController:wo,timelineController:Ul,audioStreamController:as,audioTrackController:cs,emeController:mo,cmcdController:fo,contentSteeringController:vo,interstitialsController:jo});function Ql(e){return e&&"object"===S(e)?Array.isArray(e)?e.map(Ql):Object.keys(e).reduce(function(t,r){return t[r]=Ql(e[r]),t},{}):e}function $l(e,t){var r=e.loader;r!==jl&&r!==zl?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1):function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}()&&(e.loader=jl,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}var Jl=function(e){function t(e,r){var i;return a(this,t),(i=n(this,t,["gap-controller",e.logger])).hls=void 0,i.fragmentTracker=void 0,i.media=null,i.mediaSource=void 0,i.nudgeRetry=0,i.stallReported=!1,i.stalled=null,i.moved=!1,i.seeking=!1,i.buffered={},i.lastCurrentTime=0,i.ended=0,i.waiting=0,i.onMediaPlaying=function(){i.ended=0,i.waiting=0},i.onMediaWaiting=function(){var e;null!=(e=i.media)&&e.seeking||(i.waiting=self.performance.now(),i.tick())},i.onMediaEnded=function(){var e;i.hls&&(i.ended=(null==(e=i.media)?void 0:e.currentTime)||1,i.hls.trigger(ee.MEDIA_ENDED,{stalled:!1}))},i.hls=e,i.fragmentTracker=r,i.registerListeners(),i}return d(t,e),o(t,[{key:"registerListeners",value:function(){var e=this.hls;e&&(e.on(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ee.BUFFER_APPENDED,this.onBufferAppended,this))}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ee.BUFFER_APPENDED,this.onBufferAppended,this))}},{key:"destroy",value:function(){T(t,"destroy",this,3)([]),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}},{key:"onMediaAttached",value:function(e,t){this.setInterval(100),this.mediaSource=t.mediaSource;var r=this.media=t.media;ln(r,"playing",this.onMediaPlaying),ln(r,"waiting",this.onMediaWaiting),ln(r,"ended",this.onMediaEnded)}},{key:"onMediaDetaching",value:function(e,t){this.clearInterval();var r=this.media;r&&(un(r,"playing",this.onMediaPlaying),un(r,"waiting",this.onMediaWaiting),un(r,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}},{key:"onBufferAppended",value:function(e,t){this.buffered=t.timeRanges}},{key:"hasBuffered",get:function(){return Object.keys(this.buffered).length>0}},{key:"tick",value:function(){var e;if(null!=(e=this.media)&&e.readyState&&this.hasBuffered){var t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}}},{key:"poll",value:function(e,t){var r,i,n=null==(r=this.hls)?void 0:r.config;if(n){var a=this.media;if(a){var s=a.seeking,o=this.seeking&&!s,l=!this.seeking&&s,u=a.paused&&!s||a.ended||0===a.playbackRate;if(this.seeking=s,e!==t)return t&&(this.ended=0),this.moved=!0,s||(this.nudgeRetry=0,n.nudgeOnVideoHole&&!u&&e>t&&this.nudgeOnVideoHole(e,t)),void(0===this.waiting&&this.stallResolved(e));if(l||o)o&&this.stallResolved(e);else{if(u)return this.nudgeRetry=0,this.stallResolved(e),void(!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(ee.MEDIA_ENDED,{stalled:!1})));if(jr.getBuffered(a).length){var c=jr.bufferInfo(a,e,0),d=c.nextStart||0,h=this.fragmentTracker;if(s&&h&&this.hls){var f=Zl(this.hls.inFlightFragments,e),v=c.len>2,g=!d||f||d-e>2&&!h.getPartialFragment(e);if(v||g)return;this.moved=!1}var p=null==(i=this.hls)?void 0:i.latestLevelDetails;if(!this.moved&&null!==this.stalled&&h){if(!(c.len>0)&&!d)return;var m=Math.max(d,c.start||0)-e,y=!(null==p||!p.live)?2*p.targetduration:2,T=tu(e,h);if(m>0&&(m<=y||T))return void(a.paused||this._trySkipBufferHole(T))}var E=n.detectStallWithCurrentTimeMs,k=self.performance.now(),S=this.waiting,b=this.stalled;if(null===b){if(!(S>0&&k-S<E))return void(this.stalled=k);b=this.stalled=S}var A=k-b;if(!s&&(A>=E||S)&&this.hls){var L;if("ended"===(null==(L=this.mediaSource)?void 0:L.readyState)&&(null==p||!p.live)&&Math.abs(e-((null==p?void 0:p.edge)||0))<1){if(this.ended)return;return this.ended=e||1,void this.hls.trigger(ee.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(c),!this.media||!this.hls)return}var R=jr.bufferInfo(a,e,n.maxBufferHole);this._tryFixBufferStall(R,A,e)}else this.nudgeRetry=0}}}}},{key:"stallResolved",value:function(e){var t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){var r=self.performance.now()-t;this.log("playback not stuck anymore @".concat(e,", after ").concat(Math.round(r),"ms")),this.stallReported=!1,this.waiting=0,this.hls.trigger(ee.STALL_RESOLVED,{})}}},{key:"nudgeOnVideoHole",value:function(e,t){var r,i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(r=this.buffered.audio)&&r.length&&i&&i.length>1&&e>i.end(0)){var n=jr.bufferedInfo(jr.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){var a=jr.timeRangesToArray(i),s=jr.bufferedInfo(a,t,0).bufferedIndex;if(s>-1&&s<a.length-1){var o=jr.bufferedInfo(a,e,0).bufferedIndex,l=a[s].end,u=a[s+1].start;if((-1===o||o>s)&&u-l<1&&e-l<2){var c=new Error("nudging playhead to flush pipeline after video hole. currentTime: ".concat(e," hole: ").concat(l," -> ").concat(u," buffered index: ").concat(o));this.warn(c.message),this.media.currentTime+=1e-6;var d=tu(e,this.fragmentTracker);d&&"fragment"in d?d=d.fragment:d||(d=void 0);var h=jr.bufferInfo(this.media,e,0);this.hls.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:c,reason:c.message,frag:d,buffer:h.len,bufferInfo:h})}}}}}},{key:"_tryFixBufferStall",value:function(e,t,r){var i,n,a=this.fragmentTracker,s=this.media,o=null==(i=this.hls)?void 0:i.config;if(s&&a&&o){var l=null==(n=this.hls)?void 0:n.latestLevelDetails,u=tu(r,a);if(u||null!=l&&l.live&&r<l.fragmentStart)if(this._trySkipBufferHole(u)||!this.media)return;var c=e.buffered,d=this.adjacentTraversal(e,r);(c&&c.length>1&&e.len>o.maxBufferHole||e.nextStart&&(e.nextStart-r<o.maxBufferHole||d))&&(t>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}}},{key:"adjacentTraversal",value:function(e,t){var r=this.fragmentTracker,i=e.nextStart;if(r&&i){var n=r.getFragAtPos(t,ae),a=r.getFragAtPos(i,ae);if(n&&a)return a.sn-n.sn<2}return!1}},{key:"_reportStall",value:function(e){var t=this.hls,r=this.media,i=this.stallReported,n=this.stalled;if(!i&&null!==n&&r&&t){this.stallReported=!0;var a=new Error("Playback stalling at @".concat(r.currentTime," due to low buffer (").concat(Kt(e),")"));this.warn(a.message),t.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:n}})}}},{key:"_trySkipBufferHole",value:function(e){var t,r=this.fragmentTracker,i=this.media,n=null==(t=this.hls)?void 0:t.config;if(!i||!r||!n)return 0;var a=i.currentTime,s=jr.bufferInfo(i,a,0),o=a<s.start?s.start:s.nextStart;if(o&&this.hls){var l=s.len<=n.maxBufferHole,u=s.len>0&&s.len<1&&i.readyState<3,c=o-a;if(c>0&&(l||u)){if(c>n.maxBufferHole){var d=!1;if(0===a){var h=r.getAppendedFrag(0,ae);h&&o<h.end&&(d=!0)}if(!d&&e){var f;if(null==(f=this.hls.loadLevelObj)||!f.details)return 0;if(Zl(this.hls.inFlightFragments,o))return 0;for(var v=!1,g=e.end;g<o;){var p=tu(g,r);if(!p){v=!0;break}g+=p.duration}if(v)return 0}}var m=Math.max(o+.05,a+.1);if(this.warn("skipping hole, adjusting currentTime from ".concat(a," to ").concat(m)),this.moved=!0,i.currentTime=m,null==e||!e.gap){var y=new Error("fragment loaded with buffer holes, seeking from ".concat(a," to ").concat(m)),T={type:J.MEDIA_ERROR,details:Z.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:y,reason:y.message,buffer:s.len,bufferInfo:s};e&&("fragment"in e?T.part=e:T.frag=e),this.hls.trigger(ee.ERROR,T)}return m}}return 0}},{key:"_tryNudgeBuffer",value:function(e){var t=this.hls,r=this.media,i=this.nudgeRetry,n=null==t?void 0:t.config;if(!r||!n)return 0;var a=r.currentTime;if(this.nudgeRetry++,i<n.nudgeMaxRetry){var s=a+(i+1)*n.nudgeOffset,o=new Error("Nudging 'currentTime' from ".concat(a," to ").concat(s));this.warn(o.message),r.currentTime=s,t.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:e.len,bufferInfo:e})}else{var l=new Error("Playhead still not moving while enough data buffered @".concat(a," after ").concat(n.nudgeMaxRetry," nudges"));this.error(l.message),t.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.BUFFER_STALLED_ERROR,error:l,fatal:!0,buffer:e.len,bufferInfo:e})}}}])}(Gr);function Zl(e,t){var r=eu(e.main);if(r&&r.start<=t)return r;var i=eu(e.audio);return i&&i.start<=t?i:null}function eu(e){if(!e)return null;switch(e.state){case hn:case dn:case Tn:case En:return null}return e.frag}function tu(e,t){return t.getAppendedFrag(e,ae)||t.getPartialFragment(e)}function ru(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function iu(e,t,r,i,n){var a=new e(t,r,"");try{a.value=i,n&&(a.type=n)}catch(s){a=new e(t,r,Kt(n?fe({type:n},i):i))}return a}var nu=function(){var e=ru();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY}(),au=function(){return o(function e(t){var r=this;a(this,e),this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=function(){r.hls&&r.hls.trigger(ee.EVENT_CUE_ENTER,{})},this.hls=t,this._registerListeners()},[{key:"destroy",value:function(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}},{key:"_registerListeners",value:function(){var e=this.hls;e&&(e.on(ee.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(ee.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(ee.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(ee.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}},{key:"_unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ee.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(ee.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(ee.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(ee.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}},{key:"onMediaAttaching",value:function(e,t){var r;this.media=t.media,!1===(null==(r=t.overrides)?void 0:r.cueRemoval)&&(this.removeCues=!1)}},{key:"onMediaAttached",value:function(){var e,t=null==(e=this.hls)?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}},{key:"onMediaDetaching",value:function(e,t){this.media=null,!!t.transferMedia||(this.id3Track&&(this.removeCues&&Lo(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}},{key:"onManifestLoading",value:function(){this.dateRangeCuesAppended={}}},{key:"createTrack",value:function(e){var t=this.getID3Track(e.textTracks);return t.mode="hidden",t}},{key:"getID3Track",value:function(e){if(this.media){for(var t=0;t<e.length;t++){var r=e[t];if("metadata"===r.kind&&"id3"===r.label)return bo(r,this.media),r}return this.media.addTextTrack("metadata","id3")}}},{key:"onFragParsingMetadata",value:function(e,t){if(this.media&&this.hls){var r=this.hls.config,i=r.enableEmsgMetadataCues,n=r.enableID3MetadataCues;if(i||n){var a=t.samples;this.id3Track||(this.id3Track=this.createTrack(this.media));var s=ru();if(s)for(var o=0;o<a.length;o++){var l=a[o].type;if((l!==Zn.emsg||i)&&n){var u=Xn(a[o].data),c=a[o].pts,d=c+a[o].duration;d>nu&&(d=nu),d-c<=0&&(d=c+.25);for(var h=0;h<u.length;h++){var f=u[h];if(!Qn(f)){this.updateId3CueEnds(c,l);var v=iu(s,c,d,f,l);v&&this.id3Track.addCue(v)}}}}}}}},{key:"updateId3CueEnds",value:function(e,t){var r,i=null==(r=this.id3Track)?void 0:r.cues;if(i)for(var n=i.length;n--;){var a=i[n];a.type===t&&a.startTime<e&&a.endTime===nu&&(a.endTime=e)}}},{key:"onBufferFlushing",value:function(e,t){var r=t.startOffset,i=t.endOffset,n=t.type,a=this.id3Track,s=this.hls;if(s){var o=s.config,l=o.enableEmsgMetadataCues,u=o.enableID3MetadataCues;if(a&&(l||u))Ro(a,r,i,"audio"===n?function(e){return e.type===Zn.audioId3&&u}:"video"===n?function(e){return e.type===Zn.emsg&&l}:function(e){return e.type===Zn.audioId3&&u||e.type===Zn.emsg&&l})}}},{key:"onLevelUpdated",value:function(e,t){var r=t.details;this.updateDateRangeCues(r,!0)}},{key:"onLevelPtsUpdated",value:function(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}},{key:"updateDateRangeCues",value:function(e,t){var r=this;if(this.hls&&this.media){var i=this.hls.config,n=i.assetPlayerId,a=i.timelineOffset,s=i.enableDateRangeMetadataCues,o=i.interstitialsController;if(s){var l=ru();if(n&&a&&!o){var u=e.fragmentStart,c=e.fragmentEnd,d=this.assetCue;d?(d.startTime=u,d.endTime=c):l&&(d=this.assetCue=iu(l,u,c,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"))&&(d.id=n,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(d),d.addEventListener("enter",this.onEventCueEnter))}if(e.hasProgramDateTime){var h,f=this.id3Track,v=e.dateRanges,g=Object.keys(v),p=this.dateRangeCuesAppended;if(f&&t)if(null!=(h=f.cues)&&h.length)for(var m,y=Object.keys(p).filter(function(e){return!g.includes(e)}),T=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.removeCue(i)}catch(e){}}})},E=y.length;E--;)T();else p=this.dateRangeCuesAppended={};var k=e.fragments[e.fragments.length-1];if(0!==g.length&&X(null==k?void 0:k.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(var S=function(){var e=g[b],t=v[e],i=t.startTime,n=p[e],a=(null==n?void 0:n.cues)||{},s=(null==n?void 0:n.durationKnown)||!1,u=nu,c=t.duration;if(t.endDate&&null!==c)u=i+c,s=!0;else if(t.endOnNext&&!s){var d=g.reduce(function(e,r){if(r!==t.id){var i=v[r];if(i.class===t.class&&i.startDate>t.startDate&&(!e||t.startDate<e.startDate))return i}return e},null);d&&(u=d.startTime,s=!0)}for(var h=Object.keys(t.attr),f=0;f<h.length;f++){var m=h[f];if(Zr(m)){var y=a[m];if(y)!s||null!=n&&n.durationKnown?Math.abs(y.startTime-i)>.01&&(y.startTime=i,y.endTime=u):y.endTime=u;else if(l){var T=t.attr[m];ei(m)&&(T=Le(T));var E=iu(l,i,u,{key:m,data:T},Zn.dateRange);E&&(E.id=e,r.id3Track.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}},b=0;b<g.length;b++)S()}}}}}}])}(),su=function(){return o(function e(t){var r=this;a(this,e),this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=function(){var e=r.media,t=r.levelDetails;if(e&&t){r.currentTime=e.currentTime;var i=r.computeLatency();if(null!==i){r._latency=i;var n=r.config,a=n.lowLatencyMode,s=n.maxLiveSyncPlaybackRate;if(a&&1!==s&&t.live){var o=r.targetLatency;if(null!==o){var l=i-o;if(l<Math.min(r.maxLatency,o+t.targetduration)&&l>.05&&r.forwardBufferLength>1){var u=Math.min(2,Math.max(1,s)),c=Math.round(2/(1+Math.exp(-.75*l-r.edgeStalled))*20)/20,d=Math.min(u,Math.max(1,c));r.changeMediaPlaybackRate(e,d)}else 1!==e.playbackRate&&0!==e.playbackRate&&r.changeMediaPlaybackRate(e,1)}}}}},this.hls=t,this.config=t.config,this.registerListeners()},[{key:"levelDetails",get:function(){var e;return(null==(e=this.hls)?void 0:e.latestLevelDetails)||null}},{key:"latency",get:function(){return this._latency||0}},{key:"maxLatency",get:function(){var e=this.config;if(void 0!==e.liveMaxLatencyDuration)return e.liveMaxLatencyDuration;var t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}},{key:"targetLatency",get:function(){var e=this.levelDetails;if(null===e||null===this.hls)return null;var t=e.holdBack,r=e.partHoldBack,i=e.targetduration,n=this.config,a=n.liveSyncDuration,s=n.liveSyncDurationCount,o=n.lowLatencyMode,l=this.hls.userConfig,u=o&&r||t;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||0===u)&&(u=void 0!==a?a:s*i);var c=i;return u+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,c)},set:function(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}},{key:"liveSyncPosition",get:function(){var e=this.estimateLiveEdge(),t=this.targetLatency;if(null===e||null===t)return null;var r=this.levelDetails;if(null===r)return null;var i=r.edge,n=e-t-this.edgeStalled,a=i-r.totalduration,s=i-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(a,n),s)}},{key:"drift",get:function(){var e=this.levelDetails;return null===e?1:e.drift}},{key:"edgeStalled",get:function(){var e=this.levelDetails;if(null===e)return 0;var t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}},{key:"forwardBufferLength",get:function(){var e=this.media,t=this.levelDetails;if(!e||!t)return 0;var r=e.buffered.length;return(r?e.buffered.end(r-1):t.edge)-this.currentTime}},{key:"destroy",value:function(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}},{key:"registerListeners",value:function(){var e=this.hls;e&&(e.on(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(ee.ERROR,this.onError,this))}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(ee.ERROR,this.onError,this))}},{key:"onMediaAttached",value:function(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}},{key:"onMediaDetaching",value:function(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}},{key:"onManifestLoading",value:function(){this._latency=null,this.stallCount=0}},{key:"onLevelUpdated",value:function(e,t){var r=t.details;r.advanced&&this.onTimeupdate(),!r.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}},{key:"onError",value:function(e,t){var r;t.details===Z.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(r=this.levelDetails)&&r.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}},{key:"changeMediaPlaybackRate",value:function(e,t){var r,i;e.playbackRate!==t&&(null==(r=this.hls)||r.logger.debug("[latency-controller]: latency=".concat(this.latency.toFixed(3),", targetLatency=").concat(null==(i=this.targetLatency)?void 0:i.toFixed(3),", forwardBufferLength=").concat(this.forwardBufferLength.toFixed(3),": adjusting playback rate from ").concat(e.playbackRate," to ").concat(t)),e.playbackRate=t)}},{key:"estimateLiveEdge",value:function(){var e=this.levelDetails;return null===e?null:e.edge+e.age}},{key:"computeLatency",value:function(){var e=this.estimateLiveEdge();return null===e?null:e-this.currentTime}}])}(),ou=function(e){function t(e,r){var i;return a(this,t),(i=n(this,t,[e,"level-controller"]))._levels=[],i._firstLevel=-1,i._maxAutoLevel=-1,i._startLevel=void 0,i.currentLevel=null,i.currentLevelIndex=-1,i.manualLevelIndex=-1,i.steering=void 0,i.onParsedComplete=void 0,i.steering=r,i._registerListeners(),i}return d(t,e),o(t,[{key:"_registerListeners",value:function(){var e=this.hls;e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(ee.LEVEL_LOADED,this.onLevelLoaded,this),e.on(ee.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(ee.FRAG_BUFFERED,this.onFragBuffered,this),e.on(ee.ERROR,this.onError,this)}},{key:"_unregisterListeners",value:function(){var e=this.hls;e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(ee.LEVEL_LOADED,this.onLevelLoaded,this),e.off(ee.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(ee.FRAG_BUFFERED,this.onFragBuffered,this),e.off(ee.ERROR,this.onError,this)}},{key:"destroy",value:function(){this._unregisterListeners(),this.steering=null,this.resetLevels(),T(t,"destroy",this,3)([])}},{key:"stopLoad",value:function(){this._levels.forEach(function(e){e.loadError=0,e.fragmentError=0}),T(t,"stopLoad",this,3)([])}},{key:"resetLevels",value:function(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}},{key:"onManifestLoading",value:function(e,t){this.resetLevels()}},{key:"onManifestLoaded",value:function(e,t){var r=this,i=this.hls.config.preferManagedMediaSource,n=[],a={},s={},o=!1,l=!1,u=!1;t.levels.forEach(function(e){var t=e.attrs,c=e.audioCodec,d=e.videoCodec;c&&(e.audioCodec=c=kt(c,i)||void 0),d&&(d=e.videoCodec=function(e){for(var t=e.split(","),r=0;r<t.length;r++){var i=t[r].split(".");i.length>2&&"avc1"===i[0]&&(t[r]="avc1.".concat(parseInt(i[1]).toString(16)).concat(("000"+parseInt(i[2]).toString(16)).slice(-4)))}return t.join(",")}(d));var h=e.width,f=e.height,v=e.unknownCodecs,g=(null==v?void 0:v.length)||0;if(o||(o=!(!h||!f)),l||(l=!!d),u||(u=!!c),g||c&&!r.isAudioSupported(c)||d&&!r.isVideoSupported(d))r.log('Some or all CODECS not supported "'.concat(t.CODECS,'"'));else{var p=t.CODECS,m=t["FRAME-RATE"],y=t["HDCP-LEVEL"],T=t["PATHWAY-ID"],E=t.RESOLUTION,k=t["VIDEO-RANGE"],S="".concat(T||".","-"),b="".concat(S).concat(e.bitrate,"-").concat(E,"-").concat(m,"-").concat(p,"-").concat(k,"-").concat(y);if(a[b])if(a[b].uri===e.url||e.attrs["PATHWAY-ID"])a[b].addGroupId("audio",t.AUDIO),a[b].addGroupId("text",t.SUBTITLES);else{var A=s[b]+=1;e.attrs["PATHWAY-ID"]=new Array(A+1).join(".");var L=r.createLevel(e);a[b]=L,n.push(L)}else{var R=r.createLevel(e);a[b]=R,s[b]=1,n.push(R)}}}),this.filterAndSortMediaOptions(n,t,o,l,u)}},{key:"createLevel",value:function(e){var t=new Vt(e),r=e.supplemental;if(null!=r&&r.videoCodec&&!this.isVideoSupported(r.videoCodec)){var i=new Error('SUPPLEMENTAL-CODECS not supported "'.concat(r.videoCodec,'"'));this.log(i.message),t.supportedResult=Pt(i,[])}return t}},{key:"isAudioSupported",value:function(e){return vt(e,"audio",this.hls.config.preferManagedMediaSource)}},{key:"isVideoSupported",value:function(e){return vt(e,"video",this.hls.config.preferManagedMediaSource)}},{key:"filterAndSortMediaOptions",value:function(e,t,r,i,n){var a,s=this,o=[],l=[],u=e,c=(null==(a=t.stats)?void 0:a.parsing)||{};if((r||i)&&n&&(u=u.filter(function(e){var t,r=e.videoCodec,i=e.videoRange,n=e.width,a=e.height;return(!!r||!(!n||!a))&&(!!(t=i)&&Mt.indexOf(t)>-1)})),0===u.length)return Promise.resolve().then(function(){if(s.hls){var e="no level with compatible codecs found in manifest",r=e;t.levels.length&&(r="one or more CODECS in variant not supported: ".concat(Kt(t.levels.map(function(e){return e.attrs.CODECS}).filter(function(e,t,r){return r.indexOf(e)===t}))),s.warn(r),e+=" (".concat(r,")"));var i=new Error(e);s.hls.trigger(ee.ERROR,{type:J.MEDIA_ERROR,details:Z.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:i,reason:r})}}),void(c.end=performance.now());t.audioTracks&&lu(o=t.audioTracks.filter(function(e){return!e.audioCodec||s.isAudioSupported(e.audioCodec)})),t.subtitles&&lu(l=t.subtitles);var d=u.slice(0);u.sort(function(e,t){if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return Mt.indexOf(e.videoRange)-Mt.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){var i=mt(e.videoCodec),n=mt(t.videoCodec);if(i!==n)return n-i}if(e.uri===t.uri&&e.codecSet!==t.codecSet){var a=yt(e.codecSet),s=yt(t.codecSet);if(a!==s)return s-a}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0});var h=d[0];if(this.steering&&(u=this.steering.filterParsedLevels(u)).length!==d.length)for(var f=0;f<d.length;f++)if(d[f].pathwayId===u[0].pathwayId){h=d[f];break}this._levels=u;for(var v=0;v<u.length;v++)if(u[v]===h){var g;this._firstLevel=v;var p=h.bitrate,m=this.hls.bandwidthEstimate;if(this.log("manifest loaded, ".concat(u.length," level(s) found, first bitrate: ").concat(p)),void 0===(null==(g=this.hls.userConfig)?void 0:g.abrEwmaDefaultEstimate)){var y=Math.min(p,this.hls.config.abrEwmaDefaultEstimateMax);y>m&&m===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=y)}break}var T=n&&!i,E=this.hls.config,k=!(!E.audioStreamController||!E.audioTrackController),S={levels:u,audioTracks:o,subtitleTracks:l,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:i,altAudio:k&&!T&&o.some(function(e){return!!e.url})};c.end=performance.now(),this.hls.trigger(ee.MANIFEST_PARSED,S)}},{key:"levels",get:function(){return 0===this._levels.length?null:this._levels}},{key:"loadLevelObj",get:function(){return this.currentLevel}},{key:"level",get:function(){return this.currentLevelIndex},set:function(e){var t=this._levels;if(0!==t.length){if(e<0||e>=t.length){var r=new Error("invalid level idx"),i=e<0;if(this.hls.trigger(ee.ERROR,{type:J.OTHER_ERROR,details:Z.LEVEL_SWITCH_ERROR,level:e,fatal:i,error:r,reason:r.message}),i)return;e=Math.min(e,t.length-1)}var n=this.currentLevelIndex,a=this.currentLevel,s=a?a.attrs["PATHWAY-ID"]:void 0,o=t[e],l=o.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=o,n!==e||!a||s!==l){this.log("Switching to level ".concat(e," (").concat(o.height?o.height+"p ":"").concat(o.videoRange?o.videoRange+" ":"").concat(o.codecSet?o.codecSet+" ":"","@").concat(o.bitrate,")").concat(l?" with Pathway "+l:""," from level ").concat(n).concat(s?" with Pathway "+s:""));var u={level:e,attrs:o.attrs,details:o.details,bitrate:o.bitrate,averageBitrate:o.averageBitrate,maxBitrate:o.maxBitrate,realBitrate:o.realBitrate,width:o.width,height:o.height,codecSet:o.codecSet,audioCodec:o.audioCodec,videoCodec:o.videoCodec,audioGroups:o.audioGroups,subtitleGroups:o.subtitleGroups,loaded:o.loaded,loadError:o.loadError,fragmentError:o.fragmentError,name:o.name,id:o.id,uri:o.uri,url:o.url,urlId:0,audioGroupIds:o.audioGroupIds,textGroupIds:o.textGroupIds};this.hls.trigger(ee.LEVEL_SWITCHING,u);var c=o.details;if(!c||c.live){var d=this.switchParams(o.uri,null==a?void 0:a.details,c);this.loadPlaylist(d)}}}}},{key:"manualLevel",get:function(){return this.manualLevelIndex},set:function(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}},{key:"firstLevel",get:function(){return this._firstLevel},set:function(e){this._firstLevel=e}},{key:"startLevel",get:function(){if(void 0===this._startLevel){var e=this.hls.config.startLevel;return void 0!==e?e:this.hls.firstAutoLevel}return this._startLevel},set:function(e){this._startLevel=e}},{key:"pathways",get:function(){return this.steering?this.steering.pathways():[]}},{key:"pathwayPriority",get:function(){return this.steering?this.steering.pathwayPriority:null},set:function(e){if(this.steering){var t=this.steering.pathways(),r=e.filter(function(e){return-1!==t.indexOf(e)});if(e.length<1)return void this.warn("pathwayPriority ".concat(e," should contain at least one pathway from list: ").concat(t));this.steering.pathwayPriority=r}}},{key:"onError",value:function(e,t){!t.fatal&&t.context&&t.context.type===re&&t.context.level===this.level&&this.checkRetry(t)}},{key:"onFragBuffered",value:function(e,t){var r=t.frag;if(void 0!==r&&r.type===ae){var i=r.elementaryStreams;if(!Object.keys(i).some(function(e){return!!i[e]}))return;var n=this._levels[r.level];null!=n&&n.loadError&&(this.log("Resetting level error count of ".concat(n.loadError," on frag buffered")),n.loadError=0)}}},{key:"onLevelLoaded",value:function(e,t){var r,i,n=t.level,a=t.details,s=t.levelInfo;if(!s)return this.warn("Invalid level index ".concat(n)),void(null!=(i=t.deliveryDirectives)&&i.skip&&(a.deltaUpdateFailed=!0));if(s===this.currentLevel||t.withoutMultiVariant){0===s.fragmentError&&(s.loadError=0);var o=s.details;o===t.details&&o.advanced&&(o=void 0),this.playlistLoaded(n,t,o)}else null!=(r=t.deliveryDirectives)&&r.skip&&(a.deltaUpdateFailed=!0)}},{key:"loadPlaylist",value:function(e){T(t,"loadPlaylist",this,3)([]),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}},{key:"loadingPlaylist",value:function(e,r){T(t,"loadingPlaylist",this,3)([e,r]);var i=this.getUrlWithDirectives(e.uri,r),n=this.currentLevelIndex,a=e.attrs["PATHWAY-ID"],s=e.details,o=null==s?void 0:s.age;this.log("Loading level index ".concat(n).concat(void 0!==(null==r?void 0:r.msn)?" at sn "+r.msn+" part "+r.part:"").concat(a?" Pathway "+a:"").concat(o&&s.live?" age "+o.toFixed(1)+(s.type&&" "+s.type||""):""," ").concat(i)),this.hls.trigger(ee.LEVEL_LOADING,{url:i,level:n,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:r||null})}},{key:"nextLoadLevel",get:function(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},set:function(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}},{key:"removeLevel",value:function(e){var t,r=this;if(1!==this._levels.length){var i=this._levels.filter(function(t,i){return i!==e||(r.steering&&r.steering.removeLevel(t),t===r.currentLevel&&(r.currentLevel=null,r.currentLevelIndex=-1,t.details&&t.details.fragments.forEach(function(e){return e.level=-1})),!1)});Zi(i),this._levels=i,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);var n=i.length-1;this._firstLevel=Math.min(this._firstLevel,n),this._startLevel&&(this._startLevel=Math.min(this._startLevel,n)),this.hls.trigger(ee.LEVELS_UPDATED,{levels:i})}}},{key:"onLevelsUpdated",value:function(e,t){var r=t.levels;this._levels=r}},{key:"checkMaxAutoUpdated",value:function(){var e=this.hls,t=e.autoLevelCapping,r=e.maxAutoLevel,i=e.maxHdcpLevel;this._maxAutoLevel!==r&&(this._maxAutoLevel=r,this.hls.trigger(ee.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:r,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}])}(ss);function lu(e){var t={};e.forEach(function(e){var r=e.groupId||"";e.id=t[r]=t[r]||0,t[r]++})}function uu(){return self.SourceBuffer||self.WebKitSourceBuffer}function cu(){if(!ke())return!1;var e=uu();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}var du=function(e){function t(e,r,i){var s;return a(this,t),(s=n(this,t,[e,r,i,"stream-controller",ae])).audioCodecSwap=!1,s.level=-1,s._forceStartLoad=!1,s._hasEnoughToStart=!1,s.altAudio=0,s.audioOnly=!1,s.fragPlaying=null,s.fragLastKbps=0,s.couldBacktrack=!1,s.backtrackFragment=null,s.audioCodecSwitch=!1,s.videoBuffer=null,s.onMediaPlaying=function(){s.tick()},s.onMediaSeeked=function(){var e=s.media,t=e?e.currentTime:null;if(null!==t&&X(t)&&(s.log("Media seeked to ".concat(t.toFixed(3))),s.getBufferedFrag(t))){var r=s.getFwdBufferInfoAtPos(e,t,ae,0);null!==r&&0!==r.len?s.tick():s.warn("Main forward buffer length at ".concat(t,' on "seeked" event ').concat(r?r.len:"empty",")"))}},s.registerListeners(),s}return d(t,e),o(t,[{key:"registerListeners",value:function(){T(t,"registerListeners",this,3)([]);var e=this.hls;e.on(ee.MANIFEST_PARSED,this.onManifestParsed,this),e.on(ee.LEVEL_LOADING,this.onLevelLoading,this),e.on(ee.LEVEL_LOADED,this.onLevelLoaded,this),e.on(ee.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(ee.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(ee.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(ee.BUFFER_CREATED,this.onBufferCreated,this),e.on(ee.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(ee.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(ee.FRAG_BUFFERED,this.onFragBuffered,this)}},{key:"unregisterListeners",value:function(){T(t,"unregisterListeners",this,3)([]);var e=this.hls;e.off(ee.MANIFEST_PARSED,this.onManifestParsed,this),e.off(ee.LEVEL_LOADED,this.onLevelLoaded,this),e.off(ee.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(ee.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(ee.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(ee.BUFFER_CREATED,this.onBufferCreated,this),e.off(ee.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(ee.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(ee.FRAG_BUFFERED,this.onFragBuffered,this)}},{key:"onHandlerDestroying",value:function(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),T(t,"onHandlerDestroying",this,3)([])}},{key:"startLoad",value:function(e,t){if(this.levels){var r=this.lastCurrentTime,i=this.hls;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){var n=i.startLevel;-1===n&&(i.config.testBandwidth&&this.levels.length>1?(n=0,this.bitrateTest=!0):n=i.firstAutoLevel),i.nextLoadLevel=n,this.level=i.loadLevel,this._hasEnoughToStart=!!t}r>0&&-1===e&&!t&&(this.log("Override startPosition with lastCurrentTime @".concat(r.toFixed(3))),e=r),this.state=hn,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=dn}},{key:"stopLoad",value:function(){this._forceStartLoad=!1,T(t,"stopLoad",this,3)([])}},{key:"doTick",value:function(){switch(this.state){case Sn:var e=this.levels,t=this.level,r=null==e?void 0:e[t],i=null==r?void 0:r.details;if(i&&(!i.live||this.levelLastLoaded===r&&!this.waitForLive(r))){if(this.waitForCdnTuneIn(i))break;this.state=hn;break}if(this.hls.nextLoadLevel!==this.level){this.state=hn;break}break;case gn:this.checkRetryDate()}this.state===hn&&this.doTickIdle(),this.onTickEnd()}},{key:"onTickEnd",value:function(){var e;T(t,"onTickEnd",this,3)([]),null!=(e=this.media)&&e.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}},{key:"doTickIdle",value:function(){var e=this.hls,t=this.levelLastLoaded,r=this.levels,i=this.media;if(null!==t&&(i||this.primaryPrefetch||!this.startFragRequested&&e.config.startFragPrefetch)&&(!this.altAudio||!this.audioOnly)){var n=this.buffering?e.nextLoadLevel:e.loadLevel;if(null!=r&&r[n]){var a=r[n],s=this.getMainFwdBufferInfo();if(null!==s){var o=this.getLevelDetails();if(o&&this._streamEnded(s,o)){var l={};return 2===this.altAudio&&(l.type="video"),this.hls.trigger(ee.BUFFER_EOS,l),void(this.state=Tn)}if(this.buffering){e.loadLevel!==n&&-1===e.manualLevel&&this.log("Adapting to level ".concat(n," from level ").concat(this.level)),this.level=e.nextLoadLevel=n;var u=a.details;if(!u||this.state===Sn||this.waitForLive(a))return this.level=n,this.state=Sn,void(this.startFragRequested=!1);var c=s.len,d=this.getMaxBufferLength(a.maxBitrate);if(!(c>=d)){this.backtrackFragment&&this.backtrackFragment.start>s.end&&(this.backtrackFragment=null);var h=this.backtrackFragment?this.backtrackFragment.start:s.end,f=this.getNextFragment(h,u);if(this.couldBacktrack&&!this.fragPrevious&&f&&Oe(f)&&this.fragmentTracker.getState(f)!==Lr){var v,g=(null!=(v=this.backtrackFragment)?v:f).sn-u.startSN,p=u.fragments[g-1];p&&f.cc===p.cc&&(f=p,this.fragmentTracker.removeFragment(p))}else this.backtrackFragment&&s.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,h)){if(!f.gap){var m=this.audioOnly&&!this.altAudio?xe:Ce,y=(m===Ce?this.videoBuffer:this.mediaBuffer)||this.media;y&&this.afterBufferFlushed(y,m,ae)}f=this.getNextFragmentLoopLoading(f,u,s,ae,d)}f&&(!f.initSegment||f.initSegment.data||this.bitrateTest||(f=f.initSegment),this.loadFragment(f,a,h))}}}}}}},{key:"loadFragment",value:function(e,r,i){var n=this.fragmentTracker.getState(e);n===Sr||n===Ar?Oe(e)?this.bitrateTest?(this.log("Fragment ".concat(e.sn," of level ").concat(e.level," is being downloaded to test bitrate and will not be buffered")),this._loadBitrateTestFrag(e,r)):T(t,"loadFragment",this,3)([e,r,i]):this._loadInitSegment(e,r):this.clearTrackerIfNeeded(e)}},{key:"getBufferedFrag",value:function(e){return this.fragmentTracker.getBufferedFrag(e,ae)}},{key:"followingBufferedFrag",value:function(e){return e?this.getBufferedFrag(e.end+.5):null}},{key:"immediateLevelSwitch",value:function(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}},{key:"nextLevelSwitch",value:function(){var e=this.levels,t=this.media;if(null!=t&&t.readyState){var r,i=this.getAppendedFrag(t.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);var n=this.getLevelDetails();if(null!=n&&n.live){var a=this.getMainFwdBufferInfo();if(!a||a.len<2*n.targetduration)return}if(!t.paused&&e){var s=e[this.hls.nextLoadLevel],o=this.fragLastKbps;r=o&&this.fragCurrent?this.fragCurrent.duration*s.maxBitrate/(1e3*o)+1:0}else r=0;var l=this.getBufferedFrag(t.currentTime+r);if(l){var u=this.followingBufferedFrag(l);if(u){this.abortCurrentFrag();var c=u.maxStartPTS?u.maxStartPTS:u.start,d=u.duration,h=Math.max(l.end,c+Math.min(Math.max(d-this.config.maxFragLookUpTolerance,d*(this.couldBacktrack?.5:.125)),d*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(h,Number.POSITIVE_INFINITY)}}}}},{key:"abortCurrentFrag",value:function(){var e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case fn:case vn:case gn:case mn:case yn:this.state=hn}this.nextLoadPosition=this.getLoadPosition()}},{key:"flushMainBuffer",value:function(e,r){T(t,"flushMainBuffer",this,3)([e,r,2===this.altAudio?"video":null])}},{key:"onMediaAttached",value:function(e,r){T(t,"onMediaAttached",this,3)([e,r]);var i=r.media;ln(i,"playing",this.onMediaPlaying),ln(i,"seeked",this.onMediaSeeked)}},{key:"onMediaDetaching",value:function(e,r){var i=this.media;i&&(un(i,"playing",this.onMediaPlaying),un(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,T(t,"onMediaDetaching",this,3)([e,r]),!!r.transferMedia||(this._hasEnoughToStart=!1)}},{key:"onManifestLoading",value:function(){T(t,"onManifestLoading",this,3)([]),this.log("Trigger BUFFER_RESET"),this.hls.trigger(ee.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}},{key:"onManifestParsed",value:function(e,t){for(var r,i,n=!1,a=!1,s=0;s<t.levels.length;s++){var o=t.levels[s].audioCodec;o&&(n=n||-1!==o.indexOf("mp4a.40.2"),a=a||-1!==o.indexOf("mp4a.40.5"))}this.audioCodecSwitch=n&&a&&!("function"==typeof(null==(i=uu())||null==(r=i.prototype)?void 0:r.changeType)),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}},{key:"onLevelLoading",value:function(e,t){if(this.levels&&this.state===hn){var r=t.levelInfo;(!r.details||r.details.live&&(this.levelLastLoaded!==r||r.details.expired)||this.waitForCdnTuneIn(r.details))&&(this.state=Sn)}}},{key:"onLevelLoaded",value:function(e,t){var r,i=this.levels,n=this.startFragRequested,a=t.level,s=t.details,o=s.totalduration;if(i){this.log("Level ".concat(a," loaded [").concat(s.startSN,",").concat(s.endSN,"]").concat(s.lastPartSn?"[part-".concat(s.lastPartSn,"-").concat(s.lastPartIndex,"]"):"",", cc [").concat(s.startCC,", ").concat(s.endCC,"] duration:").concat(o));var l=t.levelInfo,u=this.fragCurrent;!u||this.state!==vn&&this.state!==gn||u.level!==t.level&&u.loader&&this.abortCurrentFrag();var c=0;if(s.live||null!=(r=l.details)&&r.live){var d;if(this.checkLiveUpdate(s),s.deltaUpdateFailed)return;c=this.alignPlaylists(s,l.details,null==(d=this.levelLastLoaded)?void 0:d.details)}if(l.details=s,this.levelLastLoaded=l,n||this.setStartPosition(s,c),this.hls.trigger(ee.LEVEL_UPDATED,{details:s,level:a}),this.state===Sn){if(this.waitForCdnTuneIn(s))return;this.state=hn}n&&s.live&&this.synchronizeToLiveEdge(s),this.tick()}else this.warn("Levels were reset while loading level ".concat(a))}},{key:"synchronizeToLiveEdge",value:function(e){var t=this.config,r=this.media;if(r){var i=this.hls.liveSyncPosition,n=this.getLoadPosition(),a=e.fragmentStart,s=e.edge,o=n>=a-t.maxFragLookUpTolerance&&n<=s;if(null!==i&&r.duration>i&&(n<i||!o)){var l=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!o&&r.readyState<4||n<s-l)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),r.readyState))if(this.warn("Playback: ".concat(n.toFixed(3)," is located too far from the end of live sliding playlist: ").concat(s,", reset currentTime to : ").concat(i.toFixed(3))),"buffered"===this.config.liveSyncMode){var u,c=jr.bufferInfo(r,i,0);if(null==(u=c.buffered)||!u.length)return void(r.currentTime=i);if(c.start<=n)return void(r.currentTime=i);var d=jr.bufferedInfo(c.buffered,n,0).nextStart;d&&(r.currentTime=d)}else r.currentTime=i}}}},{key:"_handleFragmentLoadProgress",value:function(e){var t,r=e.frag,i=e.part,n=e.payload,a=this.levels;if(a){var s=a[r.level];if(s){var o=s.details;if(!o)return this.warn("Dropping fragment ".concat(r.sn," of level ").concat(r.level," after level details were reset")),void this.fragmentTracker.removeFragment(r);var l=s.videoCodec,u=o.PTSKnown||!o.live,c=null==(t=r.initSegment)?void 0:t.data,d=this._getAudioCodec(s),h=this.transmuxer=this.transmuxer||new ns(this.hls,ae,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,v=-1!==f,g=new Hr(r.level,r.sn,r.stats.chunkCount,n.byteLength,f,v),p=this.initPTS[r.cc];h.push(n,c,d,l,r,i,o.totalduration,u,g,p)}else this.warn("Level ".concat(r.level," not found on progress"))}else this.warn("Levels were reset while fragment load was in progress. Fragment ".concat(r.sn," of level ").concat(r.level," will not be buffered"))}},{key:"onAudioTrackSwitching",value:function(e,t){var r=this,i=this.hls,n=2===this.altAudio;if($t(t.url,i))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;var a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(n)return this.fragmentTracker.removeAllFragments(),i.once(ee.BUFFER_FLUSHED,function(){r.hls&&r.hls.trigger(ee.AUDIO_TRACK_SWITCHED,t)}),void i.trigger(ee.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});i.trigger(ee.AUDIO_TRACK_SWITCHED,t)}}},{key:"onAudioTrackSwitched",value:function(e,t){var r=$t(t.url,this.hls);if(r){var i=this.videoBuffer;i&&this.mediaBuffer!==i&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=i)}this.altAudio=r?2:0,this.tick()}},{key:"onBufferCreated",value:function(e,t){var r,i,n=t.tracks,a=!1;for(var s in n){var o=n[s];if("main"===o.id){if(i=s,r=o,"video"===s){var l=n[s];l&&(this.videoBuffer=l.buffer)}}else a=!0}a&&r?(this.log("Alternate track found, use ".concat(i,".buffered to schedule main fragment loading")),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}},{key:"onFragBuffered",value:function(e,t){var r=t.frag,i=t.part,n=r.type===ae;if(n){if(this.fragContextChanged(r))return this.warn("Fragment ".concat(r.sn).concat(i?" p: "+i.index:""," of level ").concat(r.level," finished buffering, but was aborted. state: ").concat(this.state)),void(this.state===yn&&(this.state=hn));var a=i?i.stats:r.stats;this.fragLastKbps=Math.round(8*a.total/(a.buffering.end-a.loading.first)),Oe(r)&&(this.fragPrevious=r),this.fragBufferedComplete(r,i)}var s=this.media;s&&(!this._hasEnoughToStart&&jr.getBuffered(s).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),n&&this.tick())}},{key:"hasEnoughToStart",get:function(){return this._hasEnoughToStart}},{key:"onError",value:function(e,t){var r;if(t.fatal)this.state=En;else switch(t.details){case Z.FRAG_GAP:case Z.FRAG_PARSING_ERROR:case Z.FRAG_DECRYPT_ERROR:case Z.FRAG_LOAD_ERROR:case Z.FRAG_LOAD_TIMEOUT:case Z.KEY_LOAD_ERROR:case Z.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(ae,t);break;case Z.LEVEL_LOAD_ERROR:case Z.LEVEL_LOAD_TIMEOUT:case Z.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==Sn||(null==(r=t.context)?void 0:r.type)!==re||(this.state=hn);break;case Z.BUFFER_ADD_CODEC_ERROR:case Z.BUFFER_APPEND_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case Z.BUFFER_FULL_ERROR:if("main"!==t.parent)return;if(this.reduceLengthAndFlushBuffer(t))!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case Z.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}},{key:"onFragLoadEmergencyAborted",value:function(){this.state=hn,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}},{key:"onBufferFlushed",value:function(e,t){var r=t.type;if(r!==xe||!this.altAudio){var i=(r===Ce?this.videoBuffer:this.mediaBuffer)||this.media;i&&(this.afterBufferFlushed(i,r,ae),this.tick())}}},{key:"onLevelsUpdated",value:function(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}},{key:"swapAudioCodec",value:function(){this.audioCodecSwap=!this.audioCodecSwap}},{key:"seekToStartPos",value:function(){var e=this.media;if(e){var t=e.currentTime,r=this.startPosition;if(r>=0&&t<r){if(e.seeking)return void this.log("could not seek to ".concat(r,", already seeking at ").concat(t));var i=this.timelineOffset;i&&r&&(r+=i);var n=this.getLevelDetails(),a=jr.getBuffered(e),s=a.length?a.start(0):0,o=s-r,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*((null==n?void 0:n.partTarget)||0)))&&(this.log("adjusting start position by ".concat(o," to match buffer start")),r+=o,this.startPosition=r),t<r&&(this.log("seek to target start position ".concat(r," from current time ").concat(t," buffer start ").concat(s)),e.currentTime=r)}}}},{key:"_getAudioCodec",value:function(e){var t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),t}},{key:"_loadBitrateTestFrag",value:function(e,t){var r=this;e.bitrateTest=!0,this._doFragLoad(e,t).then(function(e){var i=r.hls,n=null==e?void 0:e.frag;if(n&&!r.fragContextChanged(n)){t.fragmentError=0,r.state=hn,r.startFragRequested=!1,r.bitrateTest=!1;var a=n.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),i.trigger(ee.FRAG_LOADED,e),n.bitrateTest=!1}}).catch(function(t){r.state!==dn&&r.state!==En&&(r.warn(t),r.resetFragmentLoading(e))})}},{key:"_handleTransmuxComplete",value:function(e){var t=this.playlistType,r=this.hls,i=e.remuxResult,n=e.chunkMeta,a=this.getCurrentContext(n);if(a){var s=a.frag,o=a.part,l=a.level,u=i.video,c=i.text,d=i.id3,h=i.initSegment,f=l.details,v=this.altAudio?void 0:i.audio;if(this.fragContextChanged(s))this.fragmentTracker.removeFragment(s);else{if(this.state=mn,h){var g=h.tracks;if(g){var p=s.initSegment||s;if(this.unhandledEncryptionError(h,s))return;this._bufferInitSegment(l,g,p,n),r.trigger(ee.FRAG_PARSING_INIT_SEGMENT,{frag:p,id:t,tracks:g})}var m=h.initPTS,y=h.timescale,T=this.initPTS[s.cc];if(X(m)&&(!T||T.baseTime!==m||T.timescale!==y)){var E=h.trackId;this.initPTS[s.cc]={baseTime:m,timescale:y,trackId:E},r.trigger(ee.INIT_PTS_FOUND,{frag:s,id:t,initPTS:m,timescale:y,trackId:E})}}if(u&&f){v&&"audiovideo"===u.type&&this.logMuxedErr(s);var k=f.fragments[s.sn-1-f.startSN],S=s.sn===f.startSN,b=!k||s.cc>k.cc;if(!1!==i.independent){var A=u.startPTS,L=u.endPTS,R=u.startDTS,I=u.endDTS;if(o)o.elementaryStreams[u.type]={startPTS:A,endPTS:L,startDTS:R,endDTS:I};else if(u.firstKeyFrame&&u.independent&&1===n.id&&!b&&(this.couldBacktrack=!0),u.dropped&&u.independent){var w=this.getMainFwdBufferInfo(),P=(w?w.end:this.getLoadPosition())+this.config.maxBufferHole,D=u.firstKeyFramePTS?u.firstKeyFramePTS:A;if(!S&&P<D-this.config.maxBufferHole&&!b)return void this.backtrack(s);b&&(s.gap=!0),s.setElementaryStreamInfo(u.type,s.start,L,s.start,I,!0)}else S&&A-(f.appliedTimelineOffset||0)>2&&(s.gap=!0);s.setElementaryStreamInfo(u.type,A,L,R,I),this.backtrackFragment&&(this.backtrackFragment=s),this.bufferFragmentData(u,s,o,n,S||b)}else{if(!S&&!b)return void this.backtrack(s);s.gap=!0}}if(v){var x=v.startPTS,C=v.endPTS,_=v.startDTS,M=v.endDTS;o&&(o.elementaryStreams[xe]={startPTS:x,endPTS:C,startDTS:_,endDTS:M}),s.setElementaryStreamInfo(xe,x,C,_,M),this.bufferFragmentData(v,s,o,n)}if(f&&null!=d&&d.samples.length){var O={id:t,frag:s,details:f,samples:d.samples};r.trigger(ee.FRAG_PARSING_METADATA,O)}if(f&&c){var F={id:t,frag:s,details:f,samples:c.samples};r.trigger(ee.FRAG_PARSING_USERDATA,F)}}}else this.resetWhenMissingContext(n)}},{key:"logMuxedErr",value:function(e){this.warn("".concat(Oe(e)?"Media":"Init"," segment with muxed audiovideo where only video expected: ").concat(e.url))}},{key:"_bufferInitSegment",value:function(e,t,r,i){var n=this;if(this.state===mn){this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(r));var a=t.audio,s=t.video,o=t.audiovideo;if(a){var l=e.audioCodec,u=St(a.codec,l);"mp4a"===u&&(u="mp4a.40.5");var c=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){u&&(u=-1!==u.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");var d=a.metadata;d&&"channelCount"in d&&1!==(d.channelCount||1)&&-1===c.indexOf("firefox")&&(u="mp4a.40.5")}u&&-1!==u.indexOf("mp4a.40.5")&&-1!==c.indexOf("android")&&"audio/mpeg"!==a.container&&(u="mp4a.40.2",this.log("Android: force audio codec to ".concat(u))),l&&l!==u&&this.log('Swapping manifest audio codec "'.concat(l,'" for "').concat(u,'"')),a.levelCodec=u,a.id=ae,this.log("Init audio buffer, container:".concat(a.container,", codecs[selected/level/parsed]=[").concat(u||"","/").concat(l||"","/").concat(a.codec,"]")),delete t.audiovideo}if(s){s.levelCodec=e.videoCodec,s.id=ae;var h=s.codec;if(4===(null==h?void 0:h.length))switch(h){case"hvc1":case"hev1":s.codec="hvc1.1.6.L120.90";break;case"av01":s.codec="av01.0.04M.08";break;case"avc1":s.codec="avc1.42e01e"}this.log("Init video buffer, container:".concat(s.container,", codecs[level/parsed]=[").concat(e.videoCodec||"","/").concat(h,"]").concat(s.codec!==h?" parsed-corrected="+s.codec:"").concat(s.supplemental?" supplemental="+s.supplemental:"")),delete t.audiovideo}o&&(this.log("Init audiovideo buffer, container:".concat(o.container,", codecs[level/parsed]=[").concat(e.codecs,"/").concat(o.codec,"]")),delete t.video,delete t.audio);var f=Object.keys(t);if(f.length){if(this.hls.trigger(ee.BUFFER_CODECS,t),!this.hls)return;f.forEach(function(e){var a=t[e].initSegment;null!=a&&a.byteLength&&n.hls.trigger(ee.BUFFER_APPENDING,{type:e,data:a,frag:r,part:null,chunkMeta:i,parent:r.type})})}this.tickImmediate()}}},{key:"getMainFwdBufferInfo",value:function(){var e=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,ae)}},{key:"maxBufferLength",get:function(){var e=this.levels,t=this.level,r=null==e?void 0:e[t];return r?this.getMaxBufferLength(r.maxBitrate):this.config.maxBufferLength}},{key:"backtrack",value:function(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=hn}},{key:"checkFragmentChanged",value:function(){var e=this.media,t=null;if(e&&e.readyState>1&&!1===e.seeking){var r=e.currentTime;if(jr.isBuffered(e,r)?t=this.getAppendedFrag(r):jr.isBuffered(e,r+.1)&&(t=this.getAppendedFrag(r+.1)),t){this.backtrackFragment=null;var i=this.fragPlaying,n=t.level;i&&t.sn===i.sn&&i.level===n||(this.fragPlaying=t,this.hls.trigger(ee.FRAG_CHANGED,{frag:t}),i&&i.level===n||this.hls.trigger(ee.LEVEL_SWITCHED,{level:n}))}}}},{key:"nextLevel",get:function(){var e=this.nextBufferedFrag;return e?e.level:-1}},{key:"currentFrag",get:function(){var e;if(this.fragPlaying)return this.fragPlaying;var t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;return X(t)?this.getAppendedFrag(t):null}},{key:"currentProgramDateTime",get:function(){var e,t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if(X(t)){var r=this.getLevelDetails(),i=this.currentFrag||(r?er(null,r.fragments,t):null);if(i){var n=i.programDateTime;if(null!==n){var a=n+1e3*(t-i.start);return new Date(a)}}}return null}},{key:"currentLevel",get:function(){var e=this.currentFrag;return e?e.level:-1}},{key:"nextBufferedFrag",get:function(){var e=this.currentFrag;return e?this.followingBufferedFrag(e):null}},{key:"forceStartLoad",get:function(){return this._forceStartLoad}}])}(bn),hu=function(e){function t(e,r){var i;return a(this,t),(i=n(this,t,["key-loader",r])).config=void 0,i.keyIdToKeyInfo={},i.emeController=null,i.config=e,i}return d(t,e),o(t,[{key:"abort",value:function(e){for(var t in this.keyIdToKeyInfo){var r=this.keyIdToKeyInfo[t].loader;if(r){var i;if(e&&e!==(null==(i=r.context)?void 0:i.frag.type))return;r.abort()}}}},{key:"detach",value:function(){for(var e in this.keyIdToKeyInfo){var t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}},{key:"destroy",value:function(){for(var e in this.detach(),this.keyIdToKeyInfo){var t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}},{key:"createKeyLoadError",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Z.KEY_LOAD_ERROR,r=arguments.length>2?arguments[2]:void 0,i=arguments.length>3?arguments[3]:void 0,n=arguments.length>4?arguments[4]:void 0;return new Vr({type:J.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:r,networkDetails:i})}},{key:"loadClear",value:function(e,t,r){var i=this;if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(var n,a=function(){var n=t[s];if(e.cc<=n.cc&&(!Oe(e)||!Oe(n)||e.sn<n.sn)||!r&&s==o-1)return{v:i.emeController.selectKeySystemFormat(n).then(function(e){if(i.emeController){n.setKeyFormat(e);var t=mi(e);return t?i.emeController.getKeySystemAccess([t]):void 0}})}},s=0,o=t.length;s<o;s++)if(n=a())return n.v;if(this.config.requireKeySystemAccessOnStart){var l=Ti(this.config);if(l.length)return this.emeController.getKeySystemAccess(l)}}return null}},{key:"load",value:function(e){var t=this;return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(function(r){return t.loadInternal(e,r)}):this.loadInternal(e)}},{key:"loadInternal",value:function(e,t){var r,i;t&&e.setKeyFormat(t);var n=e.decryptdata;if(!n){var a=new Error(t?"Expected frag.decryptdata to be defined after setting format ".concat(t):"Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ".concat(this.emeController&&this.config.emeEnabled,")"));return Promise.reject(this.createKeyLoadError(e,Z.KEY_LOAD_ERROR,a))}var s=n.uri;if(!s)return Promise.reject(this.createKeyLoadError(e,Z.KEY_LOAD_ERROR,new Error('Invalid key URI: "'.concat(s,'"'))));var o=fu(n),l=this.keyIdToKeyInfo[o];if(null!=(r=l)&&r.decryptdata.key)return n.key=l.decryptdata.key,Promise.resolve({frag:e,keyInfo:l});if(this.emeController&&null!=(i=l)&&i.keyLoadPromise)switch(this.emeController.getKeyStatus(l.decryptdata)){case"usable":case"usable-in-future":return l.keyLoadPromise.then(function(t){var r=t.keyInfo;return n.key=r.decryptdata.key,{frag:e,keyInfo:r}})}switch(this.log("".concat(this.keyIdToKeyInfo[o]?"Rel":"L","oading").concat(n.keyId?" keyId: "+Ae(n.keyId):""," URI: ").concat(n.uri," from ").concat(e.type," ").concat(e.level)),l=this.keyIdToKeyInfo[o]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===n.keyFormat?this.loadKeyHTTP(l,e):this.loadKeyEME(l,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(l,e);default:return Promise.reject(this.createKeyLoadError(e,Z.KEY_LOAD_ERROR,new Error('Key supplied with unsupported METHOD: "'.concat(n.method,'"'))))}}},{key:"loadKeyEME",value:function(e,t){var r={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var i;if(!e.decryptdata.keyId&&null!=(i=t.initSegment)&&i.data){var n=function(e){var t=[];return tt(e,function(e){return t.push(e.subarray(8,24))}),t}(t.initSegment.data);if(n.length){var a=n[0];a.some(function(e){return 0!==e})&&(this.log("Using keyId found in init segment ".concat(Ae(a))),e.decryptdata.keyId=a,Ai.setKeyIdForUri(e.decryptdata.uri,a))}}var s=this.emeController.loadKey(r);return(e.keyLoadPromise=s.then(function(t){return e.mediaKeySessionContext=t,r})).catch(function(r){throw e.keyLoadPromise=null,"data"in r&&(r.data.frag=t),r})}return Promise.resolve(r)}},{key:"loadKeyHTTP",value:function(e,t){var r=this,i=this.config,n=new(0,i.loader)(i);return t.keyLoader=e.loader=n,e.keyLoadPromise=new Promise(function(a,s){var o={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},l=i.keyLoadPolicy.default,u={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:function(e,t,i,n){var o=i.frag,l=i.keyInfo,u=fu(l.decryptdata);if(!o.decryptdata||l!==r.keyIdToKeyInfo[u])return s(r.createKeyLoadError(o,Z.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),n));l.decryptdata.key=o.decryptdata.key=new Uint8Array(e.data),o.keyLoader=null,l.loader=null,a({frag:o,keyInfo:l})},onError:function(e,i,n,a){r.resetLoader(i),s(r.createKeyLoadError(t,Z.KEY_LOAD_ERROR,new Error("HTTP Error ".concat(e.code," loading key ").concat(e.text)),n,fe({url:o.url,data:void 0},e)))},onTimeout:function(e,i,n){r.resetLoader(i),s(r.createKeyLoadError(t,Z.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),n))},onAbort:function(e,i,n){r.resetLoader(i),s(r.createKeyLoadError(t,Z.INTERNAL_ABORTED,new Error("key loading aborted"),n))}};n.load(o,u,c)})}},{key:"resetLoader",value:function(e){var t=e.frag,r=e.keyInfo,i=e.url,n=r.loader;t.keyLoader===n&&(t.keyLoader=null,r.loader=null);var a=fu(r.decryptdata)||i;delete this.keyIdToKeyInfo[a],n&&n.destroy()}}])}(ve);function fu(e){if(e.keyFormat!==vi){var t=e.keyId;if(t)return Ae(t)}return e.uri}function vu(e){switch(e.type){case ie:return se;case ne:return oe;default:return ae}}function gu(e,t){var r=e.url;return void 0!==r&&0!==r.indexOf("data:")||(r=t.url),r}var pu=function(){return o(function e(t){a(this,e),this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=t,this.registerListeners()},[{key:"startLoad",value:function(e){}},{key:"stopLoad",value:function(){this.destroyInternalLoaders()}},{key:"registerListeners",value:function(){var e=this.hls;e.on(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ee.LEVEL_LOADING,this.onLevelLoading,this),e.on(ee.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(ee.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(ee.LEVELS_UPDATED,this.onLevelsUpdated,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ee.LEVEL_LOADING,this.onLevelLoading,this),e.off(ee.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(ee.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(ee.LEVELS_UPDATED,this.onLevelsUpdated,this)}},{key:"createInternalLoader",value:function(e){var t=this.hls.config,r=t.pLoader,i=t.loader,n=new(r||i)(t);return this.loaders[e.type]=n,n}},{key:"getInternalLoader",value:function(e){return this.loaders[e.type]}},{key:"resetInternalLoader",value:function(e){this.loaders[e]&&delete this.loaders[e]}},{key:"destroyInternalLoaders",value:function(){for(var e in this.loaders){var t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}},{key:"destroy",value:function(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}},{key:"onManifestLoading",value:function(e,t){var r=t.url;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:te,url:r,deliveryDirectives:null,levelOrTrack:null})}},{key:"onLevelLoading",value:function(e,t){var r=t.id,i=t.level,n=t.pathwayId,a=t.url,s=t.deliveryDirectives,o=t.levelInfo;this.load({id:r,level:i,pathwayId:n,responseType:"text",type:re,url:a,deliveryDirectives:s,levelOrTrack:o})}},{key:"onAudioTrackLoading",value:function(e,t){var r=t.id,i=t.groupId,n=t.url,a=t.deliveryDirectives,s=t.track;this.load({id:r,groupId:i,level:null,responseType:"text",type:ie,url:n,deliveryDirectives:a,levelOrTrack:s})}},{key:"onSubtitleTrackLoading",value:function(e,t){var r=t.id,i=t.groupId,n=t.url,a=t.deliveryDirectives,s=t.track;this.load({id:r,groupId:i,level:null,responseType:"text",type:ne,url:n,deliveryDirectives:a,levelOrTrack:s})}},{key:"onLevelsUpdated",value:function(e,t){var r=this.loaders[re];if(r){var i=r.context;i&&!t.levels.some(function(e){return e===i.levelOrTrack})&&(r.abort(),delete this.loaders[re])}}},{key:"load",value:function(e){var t,r,i,n=this,a=this.hls.config,s=this.getInternalLoader(e);if(s){var o=this.hls.logger,l=s.context;if(l&&l.levelOrTrack===e.levelOrTrack&&(l.url===e.url||l.deliveryDirectives&&!e.deliveryDirectives))return void(l.url===e.url?o.log("[playlist-loader]: ignore ".concat(e.url," ongoing request")):o.log("[playlist-loader]: ignore ".concat(e.url," in favor of ").concat(l.url)));o.log("[playlist-loader]: aborting previous loader for type: ".concat(e.type)),s.abort()}if((r=e.type===te?a.manifestLoadPolicy.default:de({},a.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),X(null==(t=e.deliveryDirectives)?void 0:t.part))&&(e.type===re&&null!==e.level?i=this.hls.levels[e.level].details:e.type===ie&&null!==e.id?i=this.hls.audioTracks[e.id].details:e.type===ne&&null!==e.id&&(i=this.hls.subtitleTracks[e.id].details),i)){var u=i.partTarget,c=i.targetduration;if(u&&c){var d=1e3*Math.max(3*u,.8*c);r=de({},r,{maxTimeToFirstByteMs:Math.min(d,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(d,r.maxTimeToFirstByteMs)})}}var h=r.errorRetry||r.timeoutRetry||{},f={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:h.maxNumRetry||0,retryDelay:h.retryDelayMs||0,maxRetryDelay:h.maxRetryDelayMs||0},v={onSuccess:function(e,t,r,i){var a=n.getInternalLoader(r);n.resetInternalLoader(r.type);var s=e.data;t.parsing.start=performance.now(),xi.isMediaPlaylist(s)||r.type!==te?n.handleTrackOrLevelPlaylist(e,t,r,i||null,a):n.handleMasterPlaylist(e,t,r,i)},onError:function(e,t,r,i){n.handleNetworkError(t,r,!1,e,i)},onTimeout:function(e,t,r){n.handleNetworkError(t,r,!0,void 0,e)}};s.load(e,f,v)}},{key:"checkAutostartLoad",value:function(){if(this.hls){var e=this.hls,t=e.config,r=t.autoStartLoad,i=t.startPosition,n=e.forceStartLoad;(r||n)&&(this.hls.logger.log("".concat(r?"auto":"force"," startLoad with configured startPosition ").concat(i)),this.hls.startLoad(i))}}},{key:"handleMasterPlaylist",value:function(e,t,r,i){var n=this,a=this.hls,s=e.data,o=gu(e,r),l=xi.parseMasterPlaylist(s,o);if(l.playlistParsingError)return t.parsing.end=performance.now(),void this.handleManifestParsingError(e,r,l.playlistParsingError,i,t);var u=l.contentSteering,c=l.levels,d=l.sessionData,h=l.sessionKeys,f=l.startTimeOffset,v=l.variableList;this.variableList=v,c.forEach(function(e){var t=e.unknownCodecs;if(t)for(var r=n.hls.config.preferManagedMediaSource,i=e.audioCodec,a=e.videoCodec,s=t.length;s--;){var o=t[s];vt(o,"audio",r)?(e.audioCodec=i=i?"".concat(i,",").concat(o):o,ht.audio[i.substring(0,4)]=2,t.splice(s,1)):vt(o,"video",r)&&(e.videoCodec=a=a?"".concat(a,",").concat(o):o,ht.video[a.substring(0,4)]=2,t.splice(s,1))}});var g=xi.parseMasterPlaylistMedia(s,o,l),p=g.AUDIO,m=void 0===p?[]:p,y=g.SUBTITLES,T=g["CLOSED-CAPTIONS"];m.length&&(m.some(function(e){return!e.url})||!c[0].audioCodec||c[0].attrs.AUDIO||(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),m.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Jr({}),bitrate:0,url:""})));a.trigger(ee.MANIFEST_LOADED,{levels:c,audioTracks:m,subtitles:y,captions:T,contentSteering:u,url:o,stats:t,networkDetails:i,sessionData:d,sessionKeys:h,startTimeOffset:f,variableList:v})}},{key:"handleTrackOrLevelPlaylist",value:function(e,t,r,i,n){var a=this.hls,s=r.id,o=r.level,l=r.type,u=gu(e,r),c=X(o)?o:X(s)?s:0,d=vu(r),h=xi.parseLevelPlaylist(e.data,u,c,d,0,this.variableList);if(l===te){var f={attrs:new Jr({}),bitrate:0,details:h,name:"",url:u};h.requestScheduled=t.loading.start+Xi(h,0),a.trigger(ee.MANIFEST_LOADED,{levels:[f],audioTracks:[],url:u,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),r.levelDetails=h,this.handlePlaylistLoaded(h,e,t,r,i,n)}},{key:"handleManifestParsingError",value:function(e,t,r,i,n){this.hls.trigger(ee.ERROR,{type:J.NETWORK_ERROR,details:Z.MANIFEST_PARSING_ERROR,fatal:t.type===te,url:e.url,err:r,error:r,reason:r.message,response:e,context:t,networkDetails:i,stats:n})}},{key:"handleNetworkError",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=arguments.length>3?arguments[3]:void 0,n=arguments.length>4?arguments[4]:void 0,a="A network ".concat(r?"timeout":"error"+(i?" (status "+i.code+")":"")," occurred while loading ").concat(e.type);e.type===re?a+=": ".concat(e.level," id: ").concat(e.id):e.type!==ie&&e.type!==ne||(a+=" id: ".concat(e.id,' group-id: "').concat(e.groupId,'"'));var s=new Error(a);this.hls.logger.warn("[playlist-loader]: ".concat(a));var o=Z.UNKNOWN,l=!1,u=this.getInternalLoader(e);switch(e.type){case te:o=r?Z.MANIFEST_LOAD_TIMEOUT:Z.MANIFEST_LOAD_ERROR,l=!0;break;case re:o=r?Z.LEVEL_LOAD_TIMEOUT:Z.LEVEL_LOAD_ERROR,l=!1;break;case ie:o=r?Z.AUDIO_TRACK_LOAD_TIMEOUT:Z.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case ne:o=r?Z.SUBTITLE_TRACK_LOAD_TIMEOUT:Z.SUBTITLE_LOAD_ERROR,l=!1}u&&this.resetInternalLoader(e.type);var c={type:J.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:u,context:e,error:s,networkDetails:t,stats:n};if(i){var d=(null==t?void 0:t.url)||e.url;c.response=fe({url:d,data:void 0},i)}this.hls.trigger(ee.ERROR,c)}},{key:"handlePlaylistLoaded",value:function(e,t,r,i,n,a){var s=this.hls,o=i.type,l=i.level,u=i.levelOrTrack,c=i.id,d=i.groupId,h=i.deliveryDirectives,f=gu(t,i),v=vu(i),g="number"==typeof i.level&&v===ae?l:void 0,p=e.playlistParsingError;if(p){if(this.hls.logger.warn("".concat(p," ").concat(e.url)),!s.config.ignorePlaylistParsingErrors)return void s.trigger(ee.ERROR,{type:J.NETWORK_ERROR,details:Z.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:p,reason:p.message,response:t,context:i,level:g,parent:v,networkDetails:n,stats:r});e.playlistParsingError=null}if(e.fragments.length)switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),a.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case te:case re:if(g)if(u){if(u!==s.levels[g]){var m=s.levels.indexOf(u);m>-1&&(g=m)}}else g=0;s.trigger(ee.LEVEL_LOADED,{details:e,levelInfo:u||s.levels[0],level:g||0,id:c||0,stats:r,networkDetails:n,deliveryDirectives:h,withoutMultiVariant:o===te});break;case ie:s.trigger(ee.AUDIO_TRACK_LOADED,{details:e,track:u,id:c||0,groupId:d||"",stats:r,networkDetails:n,deliveryDirectives:h});break;case ne:s.trigger(ee.SUBTITLE_TRACK_LOADED,{details:e,track:u,id:c||0,groupId:d||"",stats:r,networkDetails:n,deliveryDirectives:h})}else{var y=e.playlistParsingError=new Error("No Segments found in Playlist");s.trigger(ee.ERROR,{type:J.NETWORK_ERROR,details:Z.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:y,reason:y.message,response:t,context:i,level:g,parent:v,networkDetails:n,stats:r})}}}])}(),mu=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};a(this,e),this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Pn,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;var r=this.logger=function(e,t,r){var i=me();if("object"===("undefined"==typeof console?"undefined":S(console))&&!0===e||"object"===S(e)){var n=["debug","log","info","warn","error"];n.forEach(function(t){i[t]=ye(t,e,r)});try{i.log('Debug logs enabled for "'.concat(t,'" in hls.js version ',"1.6.14"))}catch(e){return me()}n.forEach(function(t){Te[t]=ye(t,e)})}else de(Te,i);return i}(t.debug||!1,"Hls instance",t.assetPlayerId),i=this.config=function(e,t,r){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');var i=Ql(e),n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(function(e){var a="".concat("level"===e?"playlist":e,"LoadPolicy"),s=void 0===t[a],o=[];n.forEach(function(r){var n="".concat(e,"Loading").concat(r),l=t[n];if(void 0!==l&&s){o.push(n);var u=i[a].default;switch(t[a]={default:u},r){case"TimeOut":u.maxLoadTimeMs=l,u.maxTimeToFirstByteMs=l;break;case"MaxRetry":u.errorRetry.maxNumRetry=l,u.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":u.errorRetry.retryDelayMs=l,u.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":u.errorRetry.maxRetryDelayMs=l,u.timeoutRetry.maxRetryDelayMs=l}}}),o.length&&r.warn('hls.js config: "'.concat(o.join('", "'),'" setting(s) are deprecated, use "').concat(a,'": ').concat(Kt(t[a])))}),fe(fe({},i),t)}(e.DefaultConfig,t,r);this.userConfig=t,i.progressive&&$l(i,r);var n=i.abrController,s=i.bufferController,o=i.capLevelController,l=i.errorController,u=i.fpsController,c=new l(this),d=this.abrController=new n(this),h=new Rr(this),f=i.interstitialsController,v=f?this.interstitialsController=new f(this,e):null,g=this.bufferController=new s(this,h),p=this.capLevelController=new o(this),m=new u(this),y=new pu(this),T=i.contentSteeringController,E=T?new T(this):null,k=this.levelController=new ou(this,E),b=new au(this),A=new hu(this.config,this.logger),L=this.streamController=new du(this,h,A),R=this.gapController=new Jl(this,h);p.setStreamController(L),m.setStreamController(L);var I=[y,k,L];v&&I.splice(1,0,v),E&&I.splice(1,0,E),this.networkControllers=I;var w=[d,g,R,p,m,b,h];this.audioTrackController=this.createController(i.audioTrackController,I);var P=i.audioStreamController;P&&I.push(this.audioStreamController=new P(this,h,A)),this.subtitleTrackController=this.createController(i.subtitleTrackController,I);var D=i.subtitleStreamController;D&&I.push(this.subtititleStreamController=new D(this,h,A)),this.createController(i.timelineController,w),A.emeController=this.emeController=this.createController(i.emeController,w),this.cmcdController=this.createController(i.cmcdController,w),this.latencyController=this.createController(su,w),this.coreComponents=w,I.push(c);var x=c.onErrorOut;"function"==typeof x&&this.on(ee.ERROR,x,c),this.on(ee.MANIFEST_LOADED,y.onManifestLoaded,y)}return o(e,[{key:"createController",value:function(e,t){if(e){var r=new e(this);return t&&t.push(r),r}return null}},{key:"on",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this;this._emitter.on(e,t,r)}},{key:"once",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this;this._emitter.once(e,t,r)}},{key:"removeAllListeners",value:function(e){this._emitter.removeAllListeners(e)}},{key:"off",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this,i=arguments.length>3?arguments[3]:void 0;this._emitter.off(e,t,r,i)}},{key:"listeners",value:function(e){return this._emitter.listeners(e)}},{key:"emit",value:function(e,t,r){return this._emitter.emit(e,t,r)}},{key:"trigger",value:function(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),!this.triggeringException){this.triggeringException=!0;var r=e===ee.ERROR;this.trigger(ee.ERROR,{type:J.OTHER_ERROR,details:Z.INTERNAL_EXCEPTION,fatal:r,event:e,error:t}),this.triggeringException=!1}}return!1}},{key:"listenerCount",value:function(e){return this._emitter.listenerCount(e)}},{key:"destroy",value:function(){this.logger.log("destroy"),this.trigger(ee.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(function(e){return e.destroy()}),this.networkControllers.length=0,this.coreComponents.forEach(function(e){return e.destroy()}),this.coreComponents.length=0;var e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}},{key:"attachMedia",value:function(e){if(!e||"media"in e&&!e.media){var t=new Error("attachMedia failed: invalid argument (".concat(e,")"));this.trigger(ee.ERROR,{type:J.OTHER_ERROR,details:Z.ATTACH_MEDIA_ERROR,fatal:!0,error:t})}else{this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());var r="media"in e,i=r?e.media:e,n=r?e:{media:i};this._media=i,this.trigger(ee.MEDIA_ATTACHING,n)}}},{key:"detachMedia",value:function(){this.logger.log("detachMedia"),this.trigger(ee.MEDIA_DETACHING,{}),this._media=null}},{key:"transferMedia",value:function(){this._media=null;var e=this.bufferController.transferMedia();return this.trigger(ee.MEDIA_DETACHING,{transferMedia:e}),e}},{key:"loadSource",value:function(e){this.stopLoad();var t=this.media,r=this._url,i=this._url=Pe.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log("loadSource:".concat(i)),t&&r&&(r!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(ee.MANIFEST_LOADING,{url:e})}},{key:"url",get:function(){return this._url}},{key:"hasEnoughToStart",get:function(){return this.streamController.hasEnoughToStart}},{key:"startPosition",get:function(){return this.streamController.startPositionValue}},{key:"startLoad",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:-1,t=arguments.length>1?arguments[1]:void 0;this.logger.log("startLoad(".concat(e+(t?", <skip seek to start>":""),")")),this.started=!0,this.resumeBuffering();for(var r=0;r<this.networkControllers.length&&(this.networkControllers[r].startLoad(e,t),this.started&&this.networkControllers);r++);}},{key:"stopLoad",value:function(){this.logger.log("stopLoad"),this.started=!1;for(var e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!this.started&&this.networkControllers);e++);}},{key:"loadingEnabled",get:function(){return this.started}},{key:"bufferingEnabled",get:function(){return this.streamController.bufferingEnabled}},{key:"resumeBuffering",value:function(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(function(e){e.resumeBuffering&&e.resumeBuffering()}))}},{key:"pauseBuffering",value:function(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(function(e){e.pauseBuffering&&e.pauseBuffering()}))}},{key:"inFlightFragments",get:function(){var e=l({},ae,this.streamController.inFlightFrag);return this.audioStreamController&&(e[se]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[oe]=this.subtititleStreamController.inFlightFrag),e}},{key:"swapAudioCodec",value:function(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}},{key:"recoverMediaError",value:function(){this.logger.log("recoverMediaError");var e=this._media,t=null==e?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}},{key:"removeLevel",value:function(e){this.levelController.removeLevel(e)}},{key:"sessionId",get:function(){var e=this._sessionId;return e||(e=this._sessionId=function(){try{return crypto.randomUUID()}catch(i){try{var e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(e){var r=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=(r+16*Math.random())%16|0;return r=Math.floor(r/16),("x"==e?t:3&t|8).toString(16)})}}}()),e}},{key:"levels",get:function(){var e=this.levelController.levels;return e||[]}},{key:"latestLevelDetails",get:function(){return this.streamController.getLevelDetails()||null}},{key:"loadLevelObj",get:function(){return this.levelController.loadLevelObj}},{key:"currentLevel",get:function(){return this.streamController.currentLevel},set:function(e){this.logger.log("set currentLevel:".concat(e)),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}},{key:"nextLevel",get:function(){return this.streamController.nextLevel},set:function(e){this.logger.log("set nextLevel:".concat(e)),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}},{key:"loadLevel",get:function(){return this.levelController.level},set:function(e){this.logger.log("set loadLevel:".concat(e)),this.levelController.manualLevel=e}},{key:"nextLoadLevel",get:function(){return this.levelController.nextLoadLevel},set:function(e){this.levelController.nextLoadLevel=e}},{key:"firstLevel",get:function(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)},set:function(e){this.logger.log("set firstLevel:".concat(e)),this.levelController.firstLevel=e}},{key:"startLevel",get:function(){var e=this.levelController.startLevel;return-1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e},set:function(e){this.logger.log("set startLevel:".concat(e)),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}},{key:"capLevelToPlayerSize",get:function(){return this.config.capLevelToPlayerSize},set:function(e){var t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}},{key:"autoLevelCapping",get:function(){return this._autoLevelCapping},set:function(e){this._autoLevelCapping!==e&&(this.logger.log("set autoLevelCapping:".concat(e)),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}},{key:"bandwidthEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.getEstimate():NaN},set:function(e){this.abrController.resetEstimator(e)}},{key:"abrEwmaDefaultEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.defaultEstimate:NaN}},{key:"ttfbEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.getEstimateTTFB():NaN}},{key:"maxHdcpLevel",get:function(){return this._maxHdcpLevel},set:function(e){(function(e){return _t.indexOf(e)>-1})(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}},{key:"autoLevelEnabled",get:function(){return-1===this.levelController.manualLevel}},{key:"manualLevel",get:function(){return this.levelController.manualLevel}},{key:"minAutoLevel",get:function(){var e=this.levels,t=this.config.minAutoBitrate;if(!e)return 0;for(var r=e.length,i=0;i<r;i++)if(e[i].maxBitrate>=t)return i;return 0}},{key:"maxAutoLevel",get:function(){var e,t=this.levels,r=this.autoLevelCapping,i=this.maxHdcpLevel;if(e=-1===r&&null!=t&&t.length?t.length-1:r,i)for(var n=e;n--;){var a=t[n].attrs["HDCP-LEVEL"];if(a&&a<=i)return n}return e}},{key:"firstAutoLevel",get:function(){return this.abrController.firstAutoLevel}},{key:"nextAutoLevel",get:function(){return this.abrController.nextAutoLevel},set:function(e){this.abrController.nextAutoLevel=e}},{key:"playingDate",get:function(){return this.streamController.currentProgramDateTime}},{key:"mainForwardBufferInfo",get:function(){return this.streamController.getMainFwdBufferInfo()}},{key:"maxBufferLength",get:function(){return this.streamController.maxBufferLength}},{key:"setAudioOption",value:function(e){var t;return(null==(t=this.audioTrackController)?void 0:t.setAudioOption(e))||null}},{key:"setSubtitleOption",value:function(e){var t;return(null==(t=this.subtitleTrackController)?void 0:t.setSubtitleOption(e))||null}},{key:"allAudioTracks",get:function(){var e=this.audioTrackController;return e?e.allAudioTracks:[]}},{key:"audioTracks",get:function(){var e=this.audioTrackController;return e?e.audioTracks:[]}},{key:"audioTrack",get:function(){var e=this.audioTrackController;return e?e.audioTrack:-1},set:function(e){var t=this.audioTrackController;t&&(t.audioTrack=e)}},{key:"allSubtitleTracks",get:function(){var e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}},{key:"subtitleTracks",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTracks:[]}},{key:"subtitleTrack",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTrack:-1},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}},{key:"media",get:function(){return this._media}},{key:"subtitleDisplay",get:function(){var e=this.subtitleTrackController;return!!e&&e.subtitleDisplay},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}},{key:"lowLatencyMode",get:function(){return this.config.lowLatencyMode},set:function(e){this.config.lowLatencyMode=e}},{key:"liveSyncPosition",get:function(){return this.latencyController.liveSyncPosition}},{key:"latency",get:function(){return this.latencyController.latency}},{key:"maxLatency",get:function(){return this.latencyController.maxLatency}},{key:"targetLatency",get:function(){return this.latencyController.targetLatency},set:function(e){this.latencyController.targetLatency=e}},{key:"drift",get:function(){return this.latencyController.drift}},{key:"forceStartLoad",get:function(){return this.streamController.forceStartLoad}},{key:"pathways",get:function(){return this.levelController.pathways}},{key:"pathwayPriority",get:function(){return this.levelController.pathwayPriority},set:function(e){this.levelController.pathwayPriority=e}},{key:"bufferedToEnd",get:function(){var e;return!(null==(e=this.bufferController)||!e.bufferedToEnd)}},{key:"interstitialsManager",get:function(){var e;return(null==(e=this.interstitialsController)?void 0:e.interstitialsManager)||null}},{key:"getMediaDecodingInfo",value:function(e){return Dt(e,qt(arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.allAudioTracks),navigator.mediaCapabilities)}}],[{key:"version",get:function(){return Dn}},{key:"isMSESupported",value:function(){return cu()}},{key:"isSupported",value:function(){return function(){if(!cu())return!1;var e=ke();return"function"==typeof(null==e?void 0:e.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(function(t){return e.isTypeSupported(pt(t,"video"))})||["mp4a.40.2","fLaC"].some(function(t){return e.isTypeSupported(pt(t,"audio"))}))}()}},{key:"getMediaSource",value:function(){return ke()}},{key:"Events",get:function(){return ee}},{key:"MetadataSchema",get:function(){return Zn}},{key:"ErrorTypes",get:function(){return J}},{key:"ErrorDetails",get:function(){return Z}},{key:"DefaultConfig",get:function(){return e.defaultConfig?e.defaultConfig:Xl},set:function(t){e.defaultConfig=t}}])}();function yu(){var e=navigator.userAgent,t=function(){var e;if("userAgentData"in navigator&&(null===(e=navigator.userAgentData)||void 0===e?void 0:e.platform))return navigator.userAgentData.platform;var t=navigator.userAgent;return/Mac|iPhone|iPad|iPod/i.test(t)?/iPhone|iPad|iPod/i.test(t)?"iPhone":"MacIntel":/Win/i.test(t)?"Win32":/Linux/i.test(t)?/Android/i.test(t)?"Linux armv8l":"Linux x86_64":/CrOS/i.test(t)?"CrOS":navigator.platform||"Unknown"}(),r="Unknown",i="0",n=0,a=!1,s=!1,o=!0,l=!0,u="ima";if(/Web0S|webOS/i.test(e))r="LG WebOS",a=!0,"Unknown"!==(i=(c=e.match(/Web0S[/\s]*([\d.]+)/i))&&c[1]?c[1]:"Unknown")&&(n=(d=i.split("."))[0]?parseInt(d[0],10):0);else if(/Tizen/i.test(e)){var c,d;if(r="Samsung Tizen",a=!0,"Unknown"!==(i=(c=e.match(/Tizen[/\s]*([\d.]+)/i))&&c[1]?c[1]:"Unknown"))n=(d=i.split("."))[0]?parseInt(d[0],10):0}else/SMART-TV|SmartTV/i.test(e)?(r="Smart TV",a=!0):/NetCast/i.test(e)?(r="LG NetCast",a=!0,s=!0):/BRAVIA/i.test(e)&&(r="Sony BRAVIA",a=!0);var h=function(e){var t=e.match(/Chrome\/(\d+)/);return t&&t[1]?parseInt(t[1],10):0}(e),f=function(e){var t=e.match(/AppleWebKit\/(\d+)/);return t&&t[1]?parseInt(t[1],10):0}(e);return h>0&&(a||(r="Chrome",i=h.toString(),n=h),h<50&&(o=!1,l=!1,s=!0,u="hls")),f>0&&f<600&&(l=!1,a&&(s=!0,o=!1,u="hls")),"undefined"!=typeof Promise&&"undefined"!=typeof Map&&"undefined"!=typeof Set||(l=!1,o=!1,u="hls"),"undefined"==typeof URLSearchParams&&(l=!1),{name:r,version:i,majorVersion:n,isSmartTV:a,isLegacyTV:s,platform:t,supportsIMA:o,supportsModernJS:l,recommendedAdPlayer:u}}function Tu(){var e=yu();if(e.isLegacyTV)return!1;if("undefined"==typeof document||"function"!=typeof document.createElement)return!1;try{if(!document.createElement("video"))return!1}catch(e){return!1}return"undefined"!=typeof Promise&&e.supportsIMA}function Eu(e){if(void 0===e&&(e=!1),e){var t=yu(),r=Tu();console.log("[StormcloudVideoPlayer] Browser Compatibility Info:",{browser:"".concat(t.name," ").concat(t.version),platform:t.platform,isSmartTV:t.isSmartTV,isLegacyTV:t.isLegacyTV,supportsIMA:r,supportsModernJS:t.supportsModernJS,recommendedAdPlayer:t.recommendedAdPlayer,userAgent:navigator.userAgent})}}function ku(){var e=yu(),t={};return!e.isLegacyTV&&e.supportsIMA||(t.adPlayerType="hls"),e.isSmartTV&&(t.allowNativeHls=!0),t}function Su(e,t){var r,i,n,a,s,o,l=!1,u=!1,c=!1,d="number"!=typeof e.volume||Number.isNaN(e.volume)?1:Math.max(0,Math.min(1,e.volume)),h=new Map,f=new Map,v=new Map;function g(t){t?e.dataset.stormcloudAdPlaying="true":delete e.dataset.stormcloudAdPlaying}function p(){u||(e.style.transition="opacity 0.3s ease-in-out",e.style.opacity="0",setTimeout(function(){e.style.visibility="hidden"},300),e.muted=!0,e.volume=0,u=!0)}function m(){u&&(e.style.visibility="visible",e.style.transition="opacity 0.3s ease-in-out",e.offsetHeight,e.style.opacity="1",e.muted=c,e.volume=d,u=!1)}function y(){var e=document.createElement("video");return e.style.position="absolute",e.style.top="0",e.style.left="0",e.style.width="100%",e.style.height="100%",e.style.objectFit="contain",e.style.backgroundColor="transparent",e.style.zIndex="15",e.playsInline=!0,e.muted=!1,e.volume=c?0:d,e.style.opacity="0",e.addEventListener("canplay",function(){e.style.opacity="1"},{once:!0}),e}function T(e,t){var r,i,n=h.get(e);if(n)try{for(var a=C(Array.from(n)),s=a.next();!s.done;s=a.next()){var o=s.value;try{o(t)}catch(e){}}}catch(e){r={error:e}}finally{try{s&&!s.done&&(i=a.return)&&i.call(a)}finally{if(r)throw r.error}}}function E(){var e,t,r;if(!Tu())return console.warn("[IMA] Google IMA SDK is not supported on this browser. Please use HLS ad player instead."),Promise.reject(new Error("Google IMA SDK not supported on this browser"));try{var i=window.frameElement,n=(null===(e=null==i?void 0:i.getAttribute)||void 0===e?void 0:e.call(i,"sandbox"))||"";if(n)new Set(n.split(/\s+/).map(function(e){return e.trim()}).filter(function(e){return e.length>0})).has("allow-scripts")||console.error("StormcloudVideoPlayer: The host page is inside a sandboxed iframe without 'allow-scripts'. Google IMA cannot run ads within sandboxed frames. Remove the sandbox attribute or include 'allow-scripts allow-same-origin'.")}catch(e){}if("undefined"!=typeof window&&(null===(t=window.google)||void 0===t?void 0:t.ima))return Promise.resolve();var a=document.querySelector('script[data-ima="true"]');return a?(null===(r=window.google)||void 0===r?void 0:r.ima)?Promise.resolve():new Promise(function(e,t){var r=setTimeout(function(){t(new Error("IMA SDK load timeout"))},1e4);a.addEventListener("load",function(){clearTimeout(r),e()}),a.addEventListener("error",function(){clearTimeout(r),t(new Error("IMA SDK load failed"))})}):new Promise(function(e,t){var r=document.createElement("script");r.src="https://imasdk.googleapis.com/js/sdkloader/ima3.js",r.async=!0,r.defer=!0,r.setAttribute("data-ima","true"),r.onload=function(){return e()},r.onerror=function(){return t(new Error("IMA SDK load failed"))},document.head.appendChild(r)})}var k,S,b,A=0;function L(t,r){var i=new t.ima.AdsRequest;console.log("[IMA] 📡 Requesting VAST from URL (letting IMA fetch fresh)"),i.adTagUrl=r;var a=e.offsetWidth||e.clientWidth||640,s=e.offsetHeight||e.clientHeight||360;if(i.linearAdSlotWidth=a,i.linearAdSlotHeight=s,i.nonLinearAdSlotWidth=a,i.nonLinearAdSlotHeight=s,"function"==typeof i.setAdWillAutoPlay)try{var o=!e.paused||e.autoplay;i.setAdWillAutoPlay(o)}catch(e){console.warn("[IMA] Failed to call setAdWillAutoPlay:",e)}if("function"==typeof i.setAdWillPlayMuted)try{var l=e.muted||0===e.volume;i.setAdWillPlayMuted(l)}catch(e){console.warn("[IMA] Failed to call setAdWillPlayMuted:",e)}i.vastLoadTimeout=1e4,n.requestAds(i)}function R(){var t;if(!s){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="transparent",r.style.transition="opacity 0.3s ease-in-out, background-color 0.3s ease-in-out",r.style.opacity="0",null===(t=e.parentElement)||void 0===t||t.appendChild(r),s=r}}function I(){if(i){try{i.destroy()}catch(e){}i=void 0}r&&(r.style.opacity="0")}return{initialize:function(){E().then(function(){var e,t=window.google;if(R(),!a&&s){r||(r=y(),s.appendChild(r)),a=new t.ima.AdDisplayContainer(s,r);try{null===(e=a.initialize)||void 0===e||e.call(a)}catch(e){}}}).catch(function(){})},requestAds:function(u){return D(this,void 0,void 0,function(){var h,f,v,R,w,P,D,C;return x(this,function(x){switch(x.label){case 0:if(!u||""===u.trim())return P=new Error("VAST tag URL is empty or undefined"),console.warn("[IMA] ❌",P.message),[2,Promise.reject(P)];try{new URL(u)}catch(e){return P=new Error("Invalid VAST tag URL format: ".concat(u)),console.warn("[IMA] ❌",P.message),[2,Promise.reject(P)]}if(l)return console.warn("[IMA] ⚠️ Cannot request new ads while an ad is playing. Call stop() first."),[2,Promise.reject(new Error("Ad already playing - cannot request new ads"))];I(),b=void 0,S=void 0,k=new Promise(function(e,t){S=e,b=t,h=t,setTimeout(function(){b&&(b(new Error("Ad request timeout")),b=void 0,S=void 0)},1e4)}),x.label=1;case 1:return x.trys.push([1,3,,4]),[4,E()];case 2:if(x.sent(),f=window.google,o=u,A=0,!a){if((v=document.createElement("div")).style.position="absolute",v.style.left="0",v.style.top="0",v.style.right="0",v.style.bottom="0",v.style.display="none",v.style.alignItems="center",v.style.justifyContent="center",v.style.pointerEvents="none",v.style.zIndex="10",v.style.backgroundColor="transparent",v.style.transition="opacity 0.3s ease-in-out, background-color 0.3s ease-in-out",v.style.opacity="0",!e.parentElement)throw new Error("Video element has no parent for ad container");e.parentElement.appendChild(v),s=v,r||(r=y(),s.appendChild(r)),a=new f.ima.AdDisplayContainer(v,r)}return R=e.offsetWidth||e.clientWidth,w=e.offsetHeight||e.clientHeight,R&&w&&0!==R&&0!==w?(n||(D=new f.ima.AdsLoader(a),(n=D).addEventListener(f.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,function(n){try{var a=new f.ima.AdsRenderingSettings;a.enablePreloading=!0,i=n.getAdsManager(e,a);var u=f.ima.AdEvent.Type,h=f.ima.AdErrorEvent.Type;i.addEventListener(h.AD_ERROR,function(r){var i,n,a=r.getError();if(console.error("[DEBUG-ERROR] ❌ AD_ERROR:",null===(i=a.getMessage)||void 0===i?void 0:i.call(a)),I(),l=!1,g(!1),s&&(s.style.opacity="0",s.style.backgroundColor="transparent",setTimeout(function(){s&&(s.style.pointerEvents="none",s.style.display="none")},300)),m(),b&&(b(new Error("Ad playback error")),b=void 0,S=void 0),o&&A<2){var u=500*Math.pow(2,A++);window.setTimeout(function(){try{L(f,o)}catch(e){}},u)}else T("ad_error"),(null==t?void 0:t.continueLiveStreamDuringAds)||e.paused&&(null===(n=e.play())||void 0===n||n.catch(function(){}))}),i.addEventListener(u.CONTENT_PAUSE_REQUESTED,function(){(null==t?void 0:t.continueLiveStreamDuringAds)||e.pause(),l=!0,g(!0),T("content_pause")}),i.addEventListener(u.STARTED,function(){g(!0),p(),r&&(r.volume=c?0:d,r.muted=c),s&&(s.style.pointerEvents="auto",s.style.display="flex",s.style.backgroundColor="#000",s.offsetHeight,s.style.opacity="1")}),i.addEventListener(u.CONTENT_RESUME_REQUESTED,function(){l=!1,g(!1),T("content_resume")}),i.addEventListener(u.ALL_ADS_COMPLETED,function(){l=!1,g(!1),s&&(s.style.opacity="0",s.style.backgroundColor="transparent",setTimeout(function(){s&&(s.style.pointerEvents="none",s.style.display="none")},300)),m(),!(null==t?void 0:t.continueLiveStreamDuringAds)&&e.paused&&e.play().catch(function(){}),T("all_ads_completed")}),S&&(S(),S=void 0,b=void 0)}catch(r){console.error("[IMA] Error setting up ads manager:",r),l=!1,g(!1),s&&(s.style.opacity="0",s.style.backgroundColor="transparent",setTimeout(function(){s&&(s.style.pointerEvents="none",s.style.display="none")},300)),m(),(null==t?void 0:t.continueLiveStreamDuringAds)||e.paused&&e.play().catch(function(){}),b&&(b(new Error("Failed to setup ads manager")),b=void 0,S=void 0),T("ad_error")}},!1),n.addEventListener(f.ima.AdErrorEvent.Type.AD_ERROR,function(r){var i,n=r.getError();console.error("[DEBUG-ERROR] ❌ ADS_LOADER ERROR:",null===(i=n.getMessage)||void 0===i?void 0:i.call(n)),l=!1,g(!1),s&&(s.style.opacity="0",s.style.backgroundColor="transparent",setTimeout(function(){s&&(s.style.pointerEvents="none",s.style.display="none")},300)),m(),(null==t?void 0:t.continueLiveStreamDuringAds)||e.paused&&e.play().catch(function(){}),b&&(b(new Error("Ads loader error")),b=void 0,S=void 0),T("ad_error")},!1)),L(f,u),[2,k]):(P=new Error("Invalid video dimensions: ".concat(R,"x").concat(w,". Cannot initialize ads.")),console.warn("[IMA]",P.message),null==h||h(P),b=void 0,S=void 0,[2,Promise.reject(P)]);case 3:return C=x.sent(),console.error("[IMA] Failed to request ads:",C),null==h||h(C),b=void 0,S=void 0,[2,Promise.reject(C)];case 4:return[2]}})})},preloadAds:function(e){return D(this,void 0,void 0,function(){var t,r;return x(this,function(i){return e&&""!==e.trim()?f.has(e)?[2,Promise.resolve()]:(t=v.get(e))?[2,t]:(r=function(e){return D(this,void 0,void 0,function(){var t;return x(this,function(r){switch(r.label){case 0:return[4,fetch(e,{mode:"cors"})];case 1:if(!(t=r.sent()).ok)throw new Error("Failed to preload VAST: ".concat(t.status));return[2,t.text()]}})})}(e).then(function(t){f.set(e,t)}).catch(function(){f.delete(e)}).finally(function(){v.delete(e)}),v.set(e,r),[2,r]):[2,Promise.resolve()]})})},hasPreloadedAd:function(e){return f.has(e)},play:function(){return D(this,void 0,void 0,function(){var n,s,o,u,h;return x(this,function(f){if(!(null===(u=window.google)||void 0===u?void 0:u.ima)||!a)return[2,Promise.reject(new Error("IMA SDK not available"))];if(!i)return[2,Promise.reject(new Error("No ads manager"))];try{n=e.clientWidth||640,s=e.clientHeight||360,i.init(n,s,window.google.ima.ViewMode.NORMAL),l=!0,o=c?0:d,r&&(r.volume=o,r.muted=c);try{i.setVolume(o)}catch(e){}return i.start(),[2,Promise.resolve()]}catch(r){return console.error("[IMA] ❌ Error starting ad:",r),l=!1,g(!1),(null==t?void 0:t.continueLiveStreamDuringAds)||null===(h=e.play())||void 0===h||h.catch(function(){}),[2,Promise.reject(r)]}return[2]})})},stop:function(){return D(this,void 0,void 0,function(){var e;return x(this,function(t){l=!1,g(!1),s&&(s.style.opacity="0",s.style.backgroundColor="transparent",setTimeout(function(){s&&(s.style.pointerEvents="none",s.style.display="none")},300)),m();try{null===(e=null==i?void 0:i.stop)||void 0===e||e.call(i)}catch(e){}return I(),[2]})})},destroy:function(){var e;I(),l=!1,g(!1),s&&(s.style.opacity="0",s.style.backgroundColor="transparent",setTimeout(function(){s&&(s.style.pointerEvents="none",s.style.display="none",s.parentElement&&s.parentElement.removeChild(s),s=void 0,r=void 0)},300)),m();try{null===(e=null==n?void 0:n.destroy)||void 0===e||e.call(n)}catch(e){}a=void 0,n=void 0,u=!1,f.clear(),v.clear()},isAdPlaying:function(){return l},resize:function(e,t){var r;if(i&&(null===(r=window.google)||void 0===r?void 0:r.ima))try{console.log("[IMA] Resizing ads manager to ".concat(e,"x").concat(t)),i.resize(e,t,window.google.ima.ViewMode.NORMAL)}catch(e){console.warn("[IMA] Error resizing ads manager:",e)}else console.warn("[IMA] Cannot resize: No ads manager or IMA SDK available")},on:function(e,t){h.has(e)||h.set(e,new Set),h.get(e).add(t)},off:function(e,t){var r;null===(r=h.get(e))||void 0===r||r.delete(t)},updateOriginalMutedState:function(e,t){var r="number"!=typeof t||Number.isNaN(t)?d:Math.max(0,Math.min(1,t));c=e,d=r},getOriginalMutedState:function(){return c},getOriginalVolume:function(){return d},setAdVolume:function(e){var t=Math.max(0,Math.min(1,e));if(r&&l&&(r.volume=t,r.muted=0===t),i&&l)try{i.setVolume(t)}catch(e){}},getAdVolume:function(){if(r&&l)return r.volume;if(i&&l)try{return i.getVolume()}catch(e){return console.warn("[IMA] Failed to get ad volume:",e),1}return 1},showPlaceholder:function(){R(),p(),s&&(s.style.display="flex",s.style.backgroundColor="#000",s.offsetHeight,s.style.opacity="1",s.style.pointerEvents="auto")},hidePlaceholder:function(){s&&(s.style.opacity="0",s.style.backgroundColor="transparent",setTimeout(function(){s&&(s.style.display="none",s.style.pointerEvents="none")},300)),l||m()}}}function bu(e,t){var r,i,n,a,s,o=!1,l=!1,u=Math.max(0,Math.min(1,e.volume||1)),c=new Map,d=null==t?void 0:t.licenseKey,h=null==t?void 0:t.mainHlsInstance,f=new Map,v=new Map,g=!1,p=[],m={impression:!1,start:!1,firstQuartile:!1,midpoint:!1,thirdQuartile:!1,complete:!1};function y(e,t){var r,i,n=c.get(e);if(n)try{for(var a=C(Array.from(n)),s=a.next();!s.done;s=a.next()){var o=s.value;try{o(t)}catch(t){console.warn("[HlsAdPlayer] Error in event listener for ".concat(e,":"),t)}}}catch(e){r={error:e}}finally{try{s&&!s.done&&(i=a.return)&&i.call(a)}finally{if(r)throw r.error}}}function T(e){e&&0!==e.length&&e.forEach(function(e){try{var t=e;s&&(t="".concat(t).concat(t.includes("?")?"&":"?","session_id=").concat(s)),d&&(t="".concat(t).concat(t.includes("?")?"&":"?","license_key=").concat(d)),new Image(1,1).src=t,console.log("[HlsAdPlayer] Fired tracking pixel: ".concat(t))}catch(e){console.warn("[HlsAdPlayer] Error firing tracking pixel:",e)}})}function E(e){if(0===e.length)throw new Error("No media files available");var t=e[0];if(!t)throw new Error("No media files available");if(1===e.length)return t;var r=function(){if(!h||!h.levels)return null;var e=h.currentLevel;if(-1===e||!h.levels[e]){var t=h.loadLevel;if(-1!==t&&h.levels[t]){var r=h.levels[t];return{width:r.width||1920,height:r.height||1080,bitrate:r.bitrate||5e6}}return null}var i=h.levels[e];return{width:i.width||1920,height:i.height||1080,bitrate:i.bitrate||5e6}}();if(!r)return console.log("[HlsAdPlayer] No main stream quality info, using first media file"),t;console.log("[HlsAdPlayer] Main stream quality:",r);var i=e.map(function(e){var t=Math.abs(e.width-r.width)+Math.abs(e.height-r.height),i=1e3*(e.bitrate||5e3),n=Math.abs(i-r.bitrate);return{file:e,score:2*t+n/1e3,resolutionDiff:t,bitrateDiff:n}});i.sort(function(e,t){return e.score-t.score});var n=i[0];return n?(console.log("[HlsAdPlayer] Selected media file:",{url:n.file.url,resolution:"".concat(n.file.width,"x").concat(n.file.height),bitrate:n.file.bitrate,score:n.score,resolutionDiff:n.resolutionDiff,bitrateDiff:n.bitrateDiff}),n.file):(console.log("[HlsAdPlayer] No best match found, using first media file"),t)}function k(e){var t,r,i,n;try{var a=(new DOMParser).parseFromString(e,"text/xml"),s=a.querySelector("parsererror");if(s)return console.error("[HlsAdPlayer] XML parsing error (malformed VAST XML):",s.textContent),null;var o=a.querySelector("Ad");if(!o)return console.warn("[HlsAdPlayer] No Ad element found in VAST XML"),null;var l=o.getAttribute("id")||"unknown",u=(null===(t=a.querySelector("AdTitle"))||void 0===t?void 0:t.textContent)||"Ad",c="empty"===l||u.toLowerCase().includes("no ad available")||"no ad available"===u.toLowerCase(),d=((null===(r=a.querySelector("Duration"))||void 0===r?void 0:r.textContent)||"00:00:30").split(":"),h=3600*parseInt(d[0]||"0",10)+60*parseInt(d[1]||"0",10)+parseInt(d[2]||"0",10),f=a.querySelectorAll("MediaFile"),v=[];if(console.log("[HlsAdPlayer] Found ".concat(f.length," MediaFile element(s) in VAST XML")),f.forEach(function(e,t){var r,i=e.getAttribute("type")||"",n=(null===(r=e.textContent)||void 0===r?void 0:r.trim())||"",a=e.getAttribute("width")||"",s=e.getAttribute("height")||"";if(console.log("[HlsAdPlayer] MediaFile ".concat(t,': type="').concat(i,'", url="').concat(n,'", width="').concat(a,'", height="').concat(s,'"')),"application/x-mpegURL"===i||i.includes("m3u8")){if(!n)return void console.warn("[HlsAdPlayer] MediaFile ".concat(t," has HLS type but empty URL"));var o=e.getAttribute("bitrate"),l=o?parseInt(o,10):void 0;v.push({url:n,type:i,width:parseInt(a||"1920",10),height:parseInt(s||"1080",10),bitrate:l&&l>0?l:void 0}),console.log("[HlsAdPlayer] Added HLS MediaFile: ".concat(n))}else console.log("[HlsAdPlayer] MediaFile ".concat(t,' ignored (type="').concat(i,'" is not HLS)'))}),0===v.length)return c?console.warn("[HlsAdPlayer] No ads available (VAST response indicates no ads)"):console.warn("[HlsAdPlayer] No HLS media files found in VAST XML"),null;var g={impression:[],start:[],firstQuartile:[],midpoint:[],thirdQuartile:[],complete:[],mute:[],unmute:[],pause:[],resume:[],fullscreen:[],exitFullscreen:[],skip:[],error:[]};a.querySelectorAll("Impression").forEach(function(e){var t,r=null===(t=e.textContent)||void 0===t?void 0:t.trim();r&&g.impression.push(r)}),a.querySelectorAll("Tracking").forEach(function(e){var t,r=e.getAttribute("event"),i=null===(t=e.textContent)||void 0===t?void 0:t.trim();if(r&&i){var n=r;g[n]&&g[n].push(i)}});var p=null===(n=null===(i=a.querySelector("ClickThrough"))||void 0===i?void 0:i.textContent)||void 0===n?void 0:n.trim();return{id:l,title:u,duration:h,mediaFiles:v,trackingUrls:g,clickThrough:p}}catch(e){return console.error("[HlsAdPlayer] Error parsing VAST XML:",e),null}}function S(e){return D(this,void 0,void 0,function(){var t,r;return x(this,function(i){switch(i.label){case 0:return[4,fetch(e)];case 1:if(!(t=i.sent()).ok)throw new Error("Failed to fetch VAST: ".concat(t.statusText));return[4,t.text()];case 2:return r=i.sent(),console.log("[HlsAdPlayer] VAST XML received"),console.log("[HlsAdPlayer] VAST XML content (first 2000 chars):",r.substring(0,2e3)),[2,k(r)]}})})}function b(){r&&a&&(r.addEventListener("timeupdate",function(){if(a&&r){var e=r.currentTime/a.duration;e>=.25&&!m.firstQuartile&&(m.firstQuartile=!0,T(a.trackingUrls.firstQuartile)),e>=.5&&!m.midpoint&&(m.midpoint=!0,T(a.trackingUrls.midpoint)),e>=.75&&!m.thirdQuartile&&(m.thirdQuartile=!0,T(a.trackingUrls.thirdQuartile))}}),r.addEventListener("playing",function(){a&&!m.start&&(m.start=!0,T(a.trackingUrls.start),console.log("[HlsAdPlayer] Ad started playing"))}),r.addEventListener("ended",function(){a&&!m.complete&&(m.complete=!0,T(a.trackingUrls.complete),console.log("[HlsAdPlayer] Ad completed"),function(){console.log("[HlsAdPlayer] Handling ad completion"),o=!1,A(!1),y("content_resume");var t=window.setTimeout(function(){if(g)console.log("[HlsAdPlayer] Player destroyed, skipping post-completion check");else{"true"===e.dataset.stormcloudAdPlaying&&(console.log("[HlsAdPlayer] Still in ad pod - keeping ad container visible (black screen)"),n&&(n.style.display="flex",n.style.pointerEvents="auto"));var r=p.indexOf(t);-1!==r&&p.splice(r,1)}},50);p.push(t)}())}),r.addEventListener("error",function(e){console.error("[HlsAdPlayer] Ad video error:",e),a&&T(a.trackingUrls.error),L()}),r.addEventListener("volumechange",function(){a&&(r.muted?T(a.trackingUrls.mute):T(a.trackingUrls.unmute))}),r.addEventListener("pause",function(){a&&!r.ended&&T(a.trackingUrls.pause)}),r.addEventListener("play",function(){a&&r.currentTime>0&&T(a.trackingUrls.resume)}))}function A(t){t?e.dataset.stormcloudAdPlaying="true":delete e.dataset.stormcloudAdPlaying}function L(){console.log("[HlsAdPlayer] Handling ad error"),o=!1,A(!1);var r=e.muted;e.muted=l,e.volume=l?0:u,console.log("[HlsAdPlayer] Restored mute state: ".concat(r," -> ").concat(l)),n&&(n.style.display="none",n.style.pointerEvents="none"),(null==t?void 0:t.continueLiveStreamDuringAds)||e.paused&&e.play().catch(function(){}),y("ad_error")}return{initialize:function(){var t;if(console.log("[HlsAdPlayer] Initializing"),!n){var r=document.createElement("div");r.style.position="absolute",r.style.left="0",r.style.top="0",r.style.right="0",r.style.bottom="0",r.style.display="none",r.style.alignItems="center",r.style.justifyContent="center",r.style.pointerEvents="none",r.style.zIndex="10",r.style.backgroundColor="#000",null===(t=e.parentElement)||void 0===t||t.appendChild(r),n=r}},requestAds:function(e){return D(this,void 0,void 0,function(){var t,r;return x(this,function(i){switch(i.label){case 0:if(console.log("[HlsAdPlayer] Requesting ads:",e),o)return console.warn("[HlsAdPlayer] Cannot request new ads while an ad is playing"),[2,Promise.reject(new Error("Ad already playing"))];i.label=1;case 1:return i.trys.push([1,5,,6]),s="session-".concat(Date.now(),"-").concat(Math.random().toString(36).substr(2,9)),t=void 0,f.has(e)?(t=f.get(e),f.delete(e),console.log("[HlsAdPlayer] Using preloaded VAST response:",e),[3,4]):[3,2];case 2:return[4,S(e)];case 3:t=i.sent(),i.label=4;case 4:return t?(a=t,console.log("[HlsAdPlayer] Ad parsed: ".concat(t.title,", duration: ").concat(t.duration,"s")),T(t.trackingUrls.impression),m.impression=!0,[2,Promise.resolve()]):(console.warn("[HlsAdPlayer] No ads available from VAST response"),y("ad_error"),[2,Promise.resolve()]);case 5:return r=i.sent(),console.error("[HlsAdPlayer] Error requesting ads:",r),y("ad_error"),[2,Promise.reject(r)];case 6:return[2]}})})},preloadAds:function(e){return D(this,void 0,void 0,function(){var t,r;return x(this,function(i){return e&&""!==e.trim()?f.has(e)?[2,Promise.resolve()]:(t=v.get(e))?[2,t]:(r=S(e).then(function(t){t&&(f.set(e,t),console.log("[HlsAdPlayer] Cached VAST response for preloading:",e))}).catch(function(t){console.warn("[HlsAdPlayer] Failed to preload VAST response:",t),f.delete(e)}).finally(function(){v.delete(e)}),v.set(e,r),[2,r]):[2,Promise.resolve()]})})},hasPreloadedAd:function(e){return f.has(e)},play:function(){return D(this,void 0,void 0,function(){var s,c,d;return x(this,function(h){if(!a)return console.warn("[HlsAdPlayer] Cannot play: No ad loaded (no ads available)"),[2,Promise.reject(new Error("No ad loaded"))];console.log("[HlsAdPlayer] Starting ad playback");try{if(r||((f=document.createElement("video")).style.position="absolute",f.style.left="0",f.style.top="0",f.style.width="100%",f.style.height="100%",f.style.objectFit="contain",f.style.backgroundColor="#000",f.playsInline=!0,f.muted=!1,f.volume=1,console.log("[HlsAdPlayer] Created ad video element with volume ".concat(f.volume)),r=f,null==n||n.appendChild(r),b()),m={impression:m.impression,start:!1,firstQuartile:!1,midpoint:!1,thirdQuartile:!1,complete:!1},s=e.volume,u=Math.max(0,Math.min(1,s||u)),(null==t?void 0:t.continueLiveStreamDuringAds)?console.log("[HlsAdPlayer] Content continues (Live mode)"):(e.pause(),console.log("[HlsAdPlayer] Content paused (VOD mode)")),console.log("[HlsAdPlayer] FORCE MUTING main video"),e.muted=!0,e.volume=0,o=!0,A(!0),r&&(c=l?0:u,r.volume=Math.max(0,Math.min(1,c)),r.muted=!1,console.log("[HlsAdPlayer] Set ad video volume to ".concat(r.volume,", muted: ").concat(r.muted,", originalMutedState: ").concat(l,", contentVolume: ").concat(s))),n&&(n.style.display="flex",n.style.pointerEvents="auto"),y("content_pause"),!(d=E(a.mediaFiles)))throw new Error("No media file available for ad");if(console.log("[HlsAdPlayer] Loading ad from: ".concat(d.url)),mu.isSupported())i&&i.destroy(),(i=new mu({enableWorker:!0,lowLatencyMode:!1})).loadSource(d.url),i.attachMedia(r),i.on(mu.Events.MANIFEST_PARSED,function(){console.log("[HlsAdPlayer] HLS manifest parsed, starting playback"),r.play().catch(function(e){console.error("[HlsAdPlayer] Error starting ad playback:",e),L()})}),i.on(mu.Events.ERROR,function(e,t){console.error("[HlsAdPlayer] HLS error:",t),t.fatal&&L()});else{if(!r.canPlayType("application/vnd.apple.mpegurl"))throw new Error("HLS not supported");r.src=d.url,r.play().catch(function(e){console.error("[HlsAdPlayer] Error starting ad playback:",e),L()})}return[2,Promise.resolve()]}catch(e){return console.error("[HlsAdPlayer] Error playing ad:",e),L(),[2,Promise.reject(e)]}var f;return[2]})})},stop:function(){return D(this,void 0,void 0,function(){return x(this,function(e){return console.log("[HlsAdPlayer] Stopping ad"),o=!1,A(!1),n&&(n.style.display="none",n.style.pointerEvents="none"),i&&(i.destroy(),i=void 0),r&&(r.pause(),r.src=""),a=void 0,[2]})})},destroy:function(){var t,s;console.log("[HlsAdPlayer] Destroying"),g=!0;try{for(var d=C(p),h=d.next();!h.done;h=d.next()){var m=h.value;clearTimeout(m)}}catch(e){t={error:e}}finally{try{h&&!h.done&&(s=d.return)&&s.call(d)}finally{if(t)throw t.error}}p=[],o=!1,A(!1),e.muted=l,e.volume=l?0:u,i&&(i.destroy(),i=void 0),r&&(r.pause(),r.src="",r.remove(),r=void 0),(null==n?void 0:n.parentElement)&&n.parentElement.removeChild(n),n=void 0,a=void 0,c.clear(),f.clear(),v.clear()},isAdPlaying:function(){return o},resize:function(e,t){console.log("[HlsAdPlayer] Resizing to ".concat(e,"x").concat(t)),n&&(n.style.width="".concat(e,"px"),n.style.height="".concat(t,"px")),r&&(r.style.width="".concat(e,"px"),r.style.height="".concat(t,"px"))},on:function(e,t){c.has(e)||c.set(e,new Set),c.get(e).add(t)},off:function(e,t){var r;null===(r=c.get(e))||void 0===r||r.delete(t)},updateOriginalMutedState:function(e,t){var r="number"!=typeof t||Number.isNaN(t)?u:Math.max(0,Math.min(1,t));console.log("[HlsAdPlayer] updateOriginalMutedState called: { muted: ".concat(l," -> ").concat(e,", volume: ").concat(u," -> ").concat(r," }")),l=e,u=r},getOriginalMutedState:function(){return l},getOriginalVolume:function(){return u},setAdVolume:function(e){r&&o&&(r.volume=Math.max(0,Math.min(1,e)))},getAdVolume:function(){return r&&o?r.volume:1},showPlaceholder:function(){var t;if(e.style.opacity="0",e.style.visibility="hidden",!n){var r=document.createElement("div");r.style.position="absolute",r.style.left="0",r.style.top="0",r.style.right="0",r.style.bottom="0",r.style.display="none",r.style.alignItems="center",r.style.justifyContent="center",r.style.pointerEvents="none",r.style.zIndex="10",r.style.backgroundColor="#000",null===(t=e.parentElement)||void 0===t||t.appendChild(r),n=r}n&&(n.style.display="flex",n.style.pointerEvents="auto")},hidePlaceholder:function(){n&&(n.style.display="none",n.style.pointerEvents="none"),o||(e.style.visibility="visible",e.style.opacity="1")}}}mu.defaultConfig=void 0;var Au=null;function Lu(){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 T=a.match(/Web0S\/([^\s]+)/);g=T?"webOS ".concat(T[1]):"webOS TV"}else if(a.includes("Tizen")){f="Samsung",v="Tizen",p=!0,h="tv";var E=a.match(/Tizen\/([^\s]+)/),k=a.match(/(?:Smart-TV|SMART-TV|TV)/i)?"Smart TV":"";g=E?"Tizen ".concat(E[1]," ").concat(k).trim():"Tizen TV"}else a.includes("Philips")?(f="Philips",v="Saphi",p=!0,h="tv"):a.includes("Sharp")||a.includes("AQUOS")?(f="Sharp",v="Android TV",p=!0,h="tv"):a.includes("Android")&&(a.includes("Sony")||o.includes("Sony"))?(f="Sony",v="Android TV",p=!0,h="tv"):a.includes("Android")&&(a.includes("NetCast")||a.includes("LG"))?(f="LG",v="Android TV",p=!0,h="tv"):a.includes(" Roku")||a.includes("Roku/")?(f="Roku",v="Roku OS",p=!0,h="tv"):a.includes("AppleTV")&&(f="Apple",v="tvOS",p=!0,h="tv");if(a.includes("Android")){m=!0,v="Android",h=/Mobile/.test(a)?"mobile":"tablet",a.includes("Android")&&(0===l||a.includes("Google TV")||a.includes("XiaoMi"))&&(h="tv",p=!0,f="Unknown"===f?"Android TV":f);var S=a.match(/\(([^)]*Android[^)]*)\)/);S&&S[1]&&(g=S[1])}return/iPad|iPhone|iPod/.test(a)&&(v="iOS",h="mobile",f="Apple",navigator.maxTouchPoints>1&&/iPad/.test(a)&&(h="tablet")),m||p||/Mobile/.test(a)||(a.includes("Windows")?(v="Windows",h="desktop"):a.includes("Mac")&&!/iPhone/.test(a)?(v="macOS",h="desktop",l>1&&(h="tablet")):a.includes("Linux")&&(v="Linux",h="desktop")),"Unknown"===f&&((o.includes("Google")||a.includes("Chrome"))&&(f="Google"),o.includes("Apple")&&(f="Apple"),(o.includes("Samsung")||a.includes("SM-"))&&(f="Samsung")),y=/wv|WebView|Linux; U;/.test(a),0===(null===window||void 0===window?void 0:window.outerHeight)&&0===(null===window||void 0===window?void 0:window.outerWidth)&&(y=!0),n=window.matchMedia("(display-mode: standalone)").matches||!0===window.navigator.standalone||void 0!==(null===(r=null===(t=window.screen)||void 0===t?void 0:t.orientation)||void 0===r?void 0:r.angle),{brand:f,os:v,model:g||a.substring(0,50)+"...",deviceType:h,isSmartTV:p,isAndroid:m,isWebView:y,isWebApp:n,domain:window.location.hostname,origin:window.location.origin,path:window.location.pathname,userAgent:a,vendor:o,platform:s,screen:d,hardwareConcurrency:c,deviceMemory:u,maxTouchPoints:l,language:navigator.language,languages:(null===(i=navigator.languages)||void 0===i?void 0:i.join(","))||"",cookieEnabled:navigator.cookieEnabled,doNotTrack:navigator.doNotTrack||"",referrer:document.referrer,visibilityState:document.visibilityState}}function Ru(e){return D(this,void 0,void 0,function(){var t,r,i,n,a,s,o,l,u,c,d,h,f;return x(this,function(v){switch(v.label){case 0:if(Au)return[2,Au];if(t=JSON.stringify(e),"undefined"==typeof crypto||!crypto.subtle||!crypto.subtle.digest)return[3,5];v.label=1;case 1:return v.trys.push([1,4,,5]),[4,crypto.subtle.digest("SHA-256",new Uint8Array([1,2,3]))];case 2:if(v.sent(),r=void 0,"undefined"!=typeof TextEncoder)r=(new TextEncoder).encode(t);else{for(i=unescape(encodeURIComponent(t)),n=new Uint8Array(i.length),u=0;u<i.length;u++)n[u]=i.charCodeAt(u);r=n}return[4,crypto.subtle.digest("SHA-256",r)];case 3:return a=v.sent(),s=Array.from(new Uint8Array(a)),o=s.map(function(e){return e.toString(16).padStart(2,"0")}).join(""),Au=o,[2,o];case 4:return v.sent(),console.warn("[StormcloudVideoPlayer] crypto.subtle.digest not supported, using fallback hash"),[3,5];case 5:for(l=0,u=0;u<t.length;u++)c=t.charCodeAt(u),l=(l<<5)-l+c,l&=l;return d=Math.abs(l).toString(16).padStart(8,"0"),h=Date.now().toString(16).padStart(12,"0"),f=Math.random().toString(16).substring(2,14).padStart(12,"0"),[2,Au=(d+h+f).padEnd(64,"0")]}})})}function Iu(e){return D(this,void 0,void 0,function(){var t,r,i,n,a,s;return x(this,function(o){switch(o.label){case 0:return o.trys.push([0,4,,5]),[4,Ru(t=Lu())];case 1:return r=o.sent(),i=w({browserId:r},t),n={"Content-Type":"application/json"},e&&(n.Authorization="Bearer ".concat(e)),[4,fetch("https://adstorm.co/api-adstorm-dev/adstorm/player-tracking/track",{method:"POST",headers:n,body:JSON.stringify(i)})];case 2:if(!(a=o.sent()).ok)throw new Error("HTTP error! status: ".concat(a.status));return[4,a.json()];case 3:return o.sent(),[3,5];case 4:return s=o.sent(),console.error("[StormcloudVideoPlayer] Error sending initial tracking data:",s),[3,5];case 5:return[2]}})})}function wu(e){return D(this,void 0,void 0,function(){var t,r,i,n,a;return x(this,function(s){switch(s.label){case 0:return s.trys.push([0,4,,5]),[4,Ru(Lu())];case 1:return t=s.sent(),r={browserId:t,timestamp:(new Date).toISOString()},i={"Content-Type":"application/json"},e&&(i.Authorization="Bearer ".concat(e)),[4,fetch("https://adstorm.co/api-adstorm-dev/adstorm/player-tracking/heartbeat",{method:"POST",headers:i,body:JSON.stringify(r)})];case 2:if(!(n=s.sent()).ok)throw new Error("HTTP error! status: ".concat(n.status));return[4,n.json()];case 3:return s.sent(),[3,5];case 4:return a=s.sent(),console.error("[StormcloudVideoPlayer] Error sending heartbeat:",a),[3,5];case 5:return[2]}})})}function Pu(){"function"!=typeof Object.assign&&(Object.assign=function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(null==e)throw new TypeError("Cannot convert undefined or null to object");for(var i=Object(e),n=0;n<t.length;n++){var a=t[n];if(null!=a)for(var s in a)Object.prototype.hasOwnProperty.call(a,s)&&(i[s]=a[s])}return i}),Array.from||(Array.from=function(e,t,r){var i=Object(e);if(null==e)throw new TypeError("Array.from requires an array-like object");for(var n=i.length>>>0,a=new Array(n),s=0;s<n;s++)a[s]=t?t.call(r,i[s],s):i[s];return a}),String.prototype.startsWith||(String.prototype.startsWith=function(e,t){return t=!t||t<0?0:+t,this.substring(t,t+e.length)===e}),String.prototype.endsWith||(String.prototype.endsWith=function(e,t){return(void 0===t||t>this.length)&&(t=this.length),this.substring(t-e.length,t)===e}),String.prototype.includes||(String.prototype.includes=function(e,t){return"number"!=typeof t&&(t=0),!(t+e.length>this.length)&&-1!==this.indexOf(e,t)}),function(){if("undefined"==typeof URLSearchParams){var e=function(){function e(t){var r=this;this.params=new Map,"string"==typeof t?this.parseQueryString(t):t instanceof e&&t.forEach(function(e,t){r.append(t,e)})}return e.prototype.parseQueryString=function(e){var t=this,r=e.startsWith("?")?e.slice(1):e;r&&r.split("&").forEach(function(e){var r=_(e.split("="),2),i=r[0],n=r[1];if(i){var a=t.safeDecodeURIComponent(i),s=n?t.safeDecodeURIComponent(n):"";t.append(a,s)}})},e.prototype.safeDecodeURIComponent=function(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch(t){return e}},e.prototype.append=function(e,t){var r=this.params.get(e)||[];r.push(String(t)),this.params.set(e,r)},e.prototype.delete=function(e){this.params.delete(e)},e.prototype.get=function(e){var t=this.params.get(e);return t&&t.length>0&&void 0!==t[0]?t[0]:null},e.prototype.getAll=function(e){return this.params.get(e)||[]},e.prototype.has=function(e){return this.params.has(e)},e.prototype.set=function(e,t){this.params.set(e,[String(t)])},e.prototype.forEach=function(e){var t=this;this.params.forEach(function(r,i){r.forEach(function(r){e(r,i,t)})})},e.prototype.toString=function(){var e=[];return this.params.forEach(function(t,r){t.forEach(function(t){e.push("".concat(encodeURIComponent(r),"=").concat(encodeURIComponent(t)))})}),e.join("&")},e}();window.URLSearchParams=e}}(),function(){if("undefined"==typeof TextEncoder){var e=function(){function e(){this.encoding="utf-8"}return e.prototype.encode=function(e){for(var t=[],r=0;r<e.length;r++){var i=e.charCodeAt(r);i<128?t.push(i):i<2048?t.push(192|i>>6,128|63&i):i<55296||i>=57344?t.push(224|i>>12,128|i>>6&63,128|63&i):(r++,i=65536+((1023&i)<<10|1023&e.charCodeAt(r)),t.push(240|i>>18,128|i>>12&63,128|i>>6&63,128|63&i))}return new Uint8Array(t)},e}();window.TextEncoder=e}}(),"undefined"==typeof Promise||Promise.prototype.finally||(Promise.prototype.finally=function(e){var t=this.constructor;return this.then(function(r){return t.resolve(e()).then(function(){return r})},function(r){return t.resolve(e()).then(function(){throw r})})})}var Du=function(){function e(e){this.attached=!1,this.inAdBreak=!1,this.ptsDriftEmaMs=0,this.adPodQueue=[],this.lastHeartbeatTime=0,this.currentAdIndex=0,this.totalAdsInBreak=0,this.showAds=!1,this.isLiveStream=!1,this.nativeHlsMode=!1,this.videoSrcProtection=null,this.bufferedSegmentsCount=0,this.shouldAutoplayAfterBuffering=!1,this.hasInitialBufferCompleted=!1,this.adPodAllUrls=[],this.preloadingAdUrls=new Set,this.vastToMediaUrlMap=new Map,this.preloadedMediaUrls=new Set,this.preloadingMediaUrls=new Set,this.adRequestTokenCounter=0,this.activeAdRequestToken=null,this.adRequestWatchdogToken=null,this.adFailsafeToken=null,this.fetchedAdDurations=new Map,this.targetAdBreakDurationMs=null,this.isAdaptiveMode=!1,this.failedVastUrls=new Set,this.continuousFetchingActive=!1,this.adRequestQueue=[],this.successfulAdRequests=[],this.maxPlaceholderDurationMs=5e3,this.placeholderStartTimeMs=null,this.isShowingPlaceholder=!1,this.consecutiveEmptyResponses=0,this.totalAdRequestsInBreak=0,this.lastEmptyResponseTimeMs=0,this.maxTotalAdRequestsPerBreak=20,this.maxConsecutiveEmptyResponses=5,this.baseEmptyResponseDelayMs=2e3,this.maxEmptyResponseDelayMs=3e4,Pu();var t=ku();this.config=w(w({},e),t),this.video=e.videoElement,Eu(e.debugAdTiming),this.ima=this.createAdPlayer(!1)}return e.prototype.createAdPlayer=function(e){var t=this.config.vastMode||"default",r=this.config.adPlayerType||("adstorm"===t?"hls":"ima");return"ima"!==r||Tu()||(this.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Google IMA SDK not supported on this browser, falling back to HLS ad player"),r="hls"),"hls"===r?(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Creating HLS ad player (AdStorm mode)"),bu(this.video,w(w({continueLiveStreamDuringAds:e},this.config.licenseKey?{licenseKey:this.config.licenseKey}:{}),this.hls?{mainHlsInstance:this.hls}:{}))):(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Creating Google IMA ad player (Default mode)"),Su(this.video,{continueLiveStreamDuringAds:e}))},e.prototype.load=function(){return D(this,void 0,void 0,function(){var e,t,r,i=this;return x(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.fetchAdConfiguration()];case 2:return n.sent(),[3,4];case 3:return e=n.sent(),this.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Failed to fetch ad configuration:",e),[3,4];case 4:return this.initializeTracking(),this.shouldUseNativeHls()?(this.nativeHlsMode=!0,this.videoSrcProtection=this.config.src,this.video.src=this.config.src,this.isLiveStream=null!==(t=this.config.lowLatencyMode)&&void 0!==t&&t,this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Using native HLS playback - VOD mode:",{isLive:this.isLiveStream,allowNativeHls:this.config.allowNativeHls,adBehavior:"vod (main video pauses during ads)"}),this.ima.destroy(),this.ima=this.createAdPlayer(!1),this.ima.initialize(),this.config.autoplay?[4,null===(r=this.video.play())||void 0===r?void 0:r.catch(function(){})]:[3,6]):[3,7];case 5:n.sent(),n.label=6;case 6:return[2];case 7:return this.hls=new mu(w(w({enableWorker:!0,backBufferLength:30,liveDurationInfinity:!0,lowLatencyMode:!!this.config.lowLatencyMode,maxLiveSyncPlaybackRate:this.config.lowLatencyMode?1.5:1},this.config.lowLatencyMode?{liveSyncDuration:2}:{}),{maxBufferLength:30,maxMaxBufferLength:600,maxBufferSize:6e7,maxBufferHole:.5,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,startPosition:-1})),this.hls.on(mu.Events.MEDIA_ATTACHED,function(){var e;null===(e=i.hls)||void 0===e||e.loadSource(i.config.src)}),this.hls.on(mu.Events.MANIFEST_PARSED,function(e,t){return D(i,void 0,void 0,function(){var e,t,r,i,n,a,s;return x(this,function(o){switch(o.label){case 0:return this.isLiveStream=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,this.config.debugAdTiming&&(e=this.shouldContinueLiveStreamDuringAds()?"live (main video continues muted during ads)":"vod (main video pauses during ads)",console.log("[StormcloudVideoPlayer] Stream type detected:",{isLive:this.isLiveStream,allowNativeHls:this.config.allowNativeHls,adBehavior:e})),this.ima.destroy(),this.ima=this.createAdPlayer(this.shouldContinueLiveStreamDuringAds()),this.ima.initialize(),this.bufferedSegmentsCount=0,this.hasInitialBufferCompleted=!1,this.shouldAutoplayAfterBuffering=!!this.config.autoplay,t=null!==(a=this.config.minSegmentsBeforePlay)&&void 0!==a?a:2,this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Waiting for",t,"segments to buffer before playback"),0!==t&&this.config.autoplay?[3,2]:(this.hasInitialBufferCompleted=!0,this.config.autoplay?[4,null===(s=this.video.play())||void 0===s?void 0:s.catch(function(){})]:[3,2]);case 1:o.sent(),o.label=2;case 2:return[2]}})})}),this.hls.on(mu.Events.LEVEL_LOADED,function(e,t){var r,n,a,s;if(!i.inAdBreak){var o=null==t?void 0:t.details;if(o&&o.fragments&&0!==o.fragments.length)for(var l=Math.min(5,o.fragments.length),u=0;u<l;u++){var c=o.fragments[u],d=null==c?void 0:c.tagList;if(Array.isArray(d))try{for(var h=(r=void 0,C(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")?i.parseAttributeList(p):{};if(g.includes("EXT-X-CUE-OUT")||"SCTE35-OUT"in y||void 0!==y["SCTE35-OUT"]){i.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] 🎯 EARLY SCTE-35 DETECTION: Ad break marker found in fragment",u,"- triggering ad handling immediately");var T=i.parseCueOutDuration(p),E=w(w({type:"start"},void 0!==T?{durationSeconds:T}:{}),{raw:{tag:g,value:p,earlyDetection:!0}});return i.inAdBreak=!0,i.expectedAdBreakDurationMs=T?1e3*T:void 0,i.currentAdBreakStartWallClockMs=Date.now(),i.clearAdStartTimer(),i.handleAdStart(E),void(null!=i.expectedAdBreakDurationMs&&i.scheduleAdStopCountdown(i.expectedAdBreakDurationMs))}}}}catch(e){r={error:e}}finally{try{f&&!f.done&&(n=h.return)&&n.call(h)}finally{if(r)throw r.error}}}}}),this.hls.on(mu.Events.FRAG_BUFFERED,function(e,t){return D(i,void 0,void 0,function(){var e,t,r,i=this;return x(this,function(n){switch(n.label){case 0:return this.hasInitialBufferCompleted?[2]:(this.bufferedSegmentsCount++,e=null!==(t=this.config.minSegmentsBeforePlay)&&void 0!==t?t:2,this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Buffered segment ".concat(this.bufferedSegmentsCount,"/").concat(e)),this.bufferedSegmentsCount>=e?(this.hasInitialBufferCompleted=!0,this.shouldAutoplayAfterBuffering?(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Initial buffer complete (".concat(this.bufferedSegmentsCount," segments). Starting playback.")),[4,null===(r=this.video.play())||void 0===r?void 0:r.catch(function(e){i.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Autoplay failed:",e)})]):[3,2]):[3,2]);case 1:n.sent(),n.label=2;case 2:return[2]}})})}),this.hls.on(mu.Events.FRAG_PARSING_METADATA,function(e,t){((null==t?void 0:t.samples)||[]).map(function(e){return{key:"ID3",value:null==e?void 0:e.data,ptsSeconds:null==e?void 0:e.pts}}).forEach(function(e){return i.onId3Tag(e)})}),this.hls.on(mu.Events.FRAG_CHANGED,function(e,t){var r,n,a,s,o,l=null==t?void 0:t.frag,u=null==l?void 0:l.tagList;if(Array.isArray(u))try{for(var c=C(u),d=c.next();!d.done;d=c.next()){var h=d.value,f="",v="";if(Array.isArray(h))f=String(null!==(a=h[0])&&void 0!==a?a:""),v=String(null!==(s=h[1])&&void 0!==s?s:"");else if("string"==typeof h){var g=h.indexOf(":");g>=0?(f=h.substring(0,g),v=h.substring(g+1)):(f=h,v="")}if(f)if(f.includes("EXT-X-CUE-OUT")){var p=i.parseCueOutDuration(v),m=w(w({type:"start"},void 0!==p?{durationSeconds:p}:{}),{raw:{tag:f,value:v}});i.onScte35Marker(m)}else if(f.includes("EXT-X-CUE-OUT-CONT")){var y=i.parseCueOutCont(v);m=w(w(w({type:"progress"},void 0!==(null==y?void 0:y.duration)?{durationSeconds:y.duration}:{}),void 0!==(null==y?void 0:y.elapsed)?{ptsSeconds:y.elapsed}:{}),{raw:{tag:f,value:v}});i.onScte35Marker(m)}else if(f.includes("EXT-X-CUE-IN"))i.onScte35Marker({type:"end",raw:{tag:f,value:v}});else if(f.includes("EXT-X-DATERANGE")){var T=i.parseAttributeList(v),E="SCTE35-OUT"in T||void 0!==T["SCTE35-OUT"],k="SCTE35-IN"in T||void 0!==T["SCTE35-IN"],S=String(null!==(o=T.CLASS)&&void 0!==o?o:""),b=i.toNumber(T.DURATION);if(E||/com\.apple\.hls\.cue/i.test(S)){m=w(w({type:"start"},void 0!==b?{durationSeconds:b}:{}),{raw:{tag:f,value:v,attrs:T}});i.onScte35Marker(m)}k&&i.onScte35Marker({type:"end",raw:{tag:f,value:v,attrs:T}})}}}catch(e){r={error:e}}finally{try{d&&!d.done&&(n=c.return)&&n.call(c)}finally{if(r)throw r.error}}}),this.hls.on(mu.Events.ERROR,function(e,t){var r,n;if(null==t?void 0:t.fatal)switch(t.type){case mu.ErrorTypes.NETWORK_ERROR:null===(r=i.hls)||void 0===r||r.startLoad();break;case mu.ErrorTypes.MEDIA_ERROR:null===(n=i.hls)||void 0===n||n.recoverMediaError();break;default:i.destroy()}}),this.hls.attachMedia(this.video),[2]}})})},e.prototype.attach=function(){var e=this;this.attached||(this.attached=!0,this.video.autoplay=!!this.config.autoplay,this.video.muted=!!this.config.muted,this.ima.initialize(),this.ima.updateOriginalMutedState(this.video.muted,this.video.volume),this.ima.on("all_ads_completed",function(){var t=e.getRemainingAdMs();e.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] IMA all_ads_completed event received - remaining=".concat(t,"ms, queued ads=").concat(e.adRequestQueue.length)),e.inAdBreak&&(t>500?e.tryNextAvailableAd():e.handleAdPodComplete())}),this.ima.on("ad_error",function(t){var r=e.getRemainingAdMs();if(console.error("[AD-ERROR] Ad playback failed",t||""),e.inAdBreak)if(r>500&&e.adPodQueue.length>0){var i=e.findNextPreloadedAd();i?(e.currentAdIndex++,e.playSingleAd(i).catch(function(){e.handleAdFailure()})):e.handleAdFailure()}else e.handleAdFailure();else e.handleAdFailure()}),this.ima.on("content_pause",function(){e.clearAdFailsafeTimer(),e.clearAdRequestWatchdog(),e.activeAdRequestToken=null,e.showAds=!0}),this.ima.on("content_resume",function(){if(e.clearAdFailsafeTimer(),e.clearAdRequestWatchdog(),e.activeAdRequestToken=null,e.showAds=!1,e.inAdBreak){var t=e.getRemainingAdMs();e.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] content_resume event: remaining=".concat(t,"ms, queued ads=").concat(e.adRequestQueue.length)),t>500?e.tryNextAvailableAd():e.handleAdPodComplete()}}),this.timeUpdateHandler=function(){e.onTimeUpdate(e.video.currentTime)},this.video.addEventListener("timeupdate",this.timeUpdateHandler),this.emptiedHandler=function(){if(e.nativeHlsMode&&e.videoSrcProtection&&!e.ima.isAdPlaying()){e.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Video src was cleared, restoring:",e.videoSrcProtection);var t=e.video.currentTime,r=e.video.paused;e.video.src=e.videoSrcProtection,e.video.currentTime=t,r||e.video.play().catch(function(){})}},this.video.addEventListener("emptied",this.emptiedHandler))},e.prototype.shouldUseNativeHls=function(){if("other"===this.getStreamType())return!0;var e=this.video.canPlayType("application/vnd.apple.mpegurl");return!(!this.config.allowNativeHls||!e)},e.prototype.onId3Tag=function(e){"number"==typeof e.ptsSeconds&&this.updatePtsDrift(e.ptsSeconds);var t=this.parseScte35FromId3(e);t&&this.onScte35Marker(t)},e.prototype.parseScte35FromId3=function(e){var t,r,i,n,a=this.decodeId3ValueToText(e.value);if(a){var s=a.match(/EXT-X-CUE-OUT(?::([^\r\n]*))?/i)||a.match(/CUE-OUT(?::([^\r\n]*))?/i);if(s){var o=(null!==(t=s[1])&&void 0!==t?t:"").trim(),l=this.parseCueOutDuration(o);return w(w(w({type:"start"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),void 0!==l?{durationSeconds:l}:{}),{raw:{id3:a}})}var u=a.match(/EXT-X-CUE-OUT-CONT:([^\r\n]*)/i);if(u){o=(null!==(r=u[1])&&void 0!==r?r:"").trim();var c=this.parseCueOutCont(o);return w(w(w({type:"progress"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),void 0!==(null==c?void 0:c.duration)?{durationSeconds:c.duration}:{}),{raw:{id3:a}})}if(a.match(/EXT-X-CUE-IN\b/i)||a.match(/CUE-IN\b/i))return w(w({type:"end"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),{raw:{id3:a}});var d=a.match(/EXT-X-DATERANGE:([^\r\n]*)/i);if(d){var h=this.parseAttributeList(null!==(i=d[1])&&void 0!==i?i:""),f="SCTE35-OUT"in h||void 0!==h["SCTE35-OUT"],v="SCTE35-IN"in h||void 0!==h["SCTE35-IN"],g=String(null!==(n=h.CLASS)&&void 0!==n?n:""),p=this.toNumber(h.DURATION);if(f||/com\.apple\.hls\.cue/i.test(g))return w(w(w({type:"start"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),void 0!==p?{durationSeconds:p}:{}),{raw:{id3:a,attrs:h}});if(v)return w(w({type:"end"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),{raw:{id3:a,attrs:h}})}if(/SCTE35-OUT/i.test(a))return w(w({type:"start"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),{raw:{id3:a}});if(/SCTE35-IN/i.test(a))return w(w({type:"end"},void 0!==e.ptsSeconds?{ptsSeconds:e.ptsSeconds}:{}),{raw:{id3:a}});if(e.value instanceof Uint8Array){var m=this.parseScte35Binary(e.value);if(m)return m}}},e.prototype.decodeId3ValueToText=function(e){try{if("string"==typeof e)return e;var t=new TextDecoder("utf-8",{fatal:!1}).decode(e);if(t&&/[\x20-\x7E]/.test(t))return t;for(var r="",i=0;i<e.length;i++)r+=String.fromCharCode(e[i]);return r}catch(e){return}},e.prototype.onScte35Marker=function(e){var t,r;if(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] SCTE-35 marker detected:",{type:e.type,ptsSeconds:e.ptsSeconds,durationSeconds:e.durationSeconds,currentTime:this.video.currentTime,raw:e.raw}),"start"!==e.type){if("progress"===e.type&&this.inAdBreak){if(null!=e.durationSeconds&&(this.expectedAdBreakDurationMs=1e3*e.durationSeconds),null!=this.expectedAdBreakDurationMs&&null!=this.currentAdBreakStartWallClockMs){var i=Date.now()-this.currentAdBreakStartWallClockMs,n=Math.max(0,this.expectedAdBreakDurationMs-i);this.scheduleAdStopCountdown(n)}if(!this.ima.isAdPlaying()&&null===this.activeAdRequestToken){var a=this.findCurrentOrNextBreak(1e3*this.video.currentTime),s=this.selectVastTagsForBreak(a)||(this.apiVastTagUrl?[this.apiVastTagUrl]:void 0);if(s&&s.length>0){var o=s[0],l=s.slice(1);this.adPodQueue=l,this.playSingleAd(o).catch(function(){})}}}else if("end"===e.type)return this.inAdBreak=!1,this.expectedAdBreakDurationMs=void 0,this.currentAdBreakStartWallClockMs=void 0,this.clearAdStartTimer(),this.clearAdStopTimer(),this.ima.isAdPlaying()&&this.ima.stop().catch(function(){}),void this.handleAdPodComplete()}else{if(this.inAdBreak)return;this.inAdBreak=!0;var u=null!=e.durationSeconds?1e3*e.durationSeconds:void 0;this.expectedAdBreakDurationMs=u,this.currentAdBreakStartWallClockMs=Date.now();var c=this.isManifestBasedMarker(e),d=null===(t=this.config.immediateManifestAds)||void 0===t||t;if(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Ad start decision:",{isManifestMarker:c,forceImmediate:d,hasPts:"number"==typeof e.ptsSeconds}),c&&d)this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Starting ad immediately (manifest-based)"),this.clearAdStartTimer(),this.handleAdStart(e);else if("number"==typeof e.ptsSeconds){var h=null!==(r=this.config.driftToleranceMs)&&void 0!==r?r:1e3,f=1e3*this.video.currentTime,v=f-this.ptsDriftEmaMs,g=Math.floor(1e3*e.ptsSeconds-v);this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] PTS-based timing calculation:",{nowMs:f,estCurrentPtsMs:v,markerPtsMs:1e3*e.ptsSeconds,deltaMs:g,tolerance:h}),g>h?(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Scheduling ad start in ".concat(g,"ms")),this.scheduleAdStartIn(g)):(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Starting ad immediately (within tolerance)"),this.clearAdStartTimer(),this.handleAdStart(e))}else this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Starting ad immediately (fallback)"),this.clearAdStartTimer(),this.handleAdStart(e);null!=this.expectedAdBreakDurationMs&&this.scheduleAdStopCountdown(this.expectedAdBreakDurationMs)}},e.prototype.parseCueOutDuration=function(e){var t=parseFloat(e.trim());if(!Number.isNaN(t))return t;var 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}},e.prototype.parseCueOutCont=function(e){var t=e.match(/Elapsed\s*=\s*([0-9.]+)/i),r=e.match(/Duration\s*=\s*([0-9.]+)/i),i={};if(t&&null!=t[1]){var n=parseFloat(t[1]);Number.isNaN(n)||(i.elapsed=n)}if(r&&null!=r[1]){var a=parseFloat(r[1]);Number.isNaN(a)||(i.duration=a)}if("elapsed"in i||"duration"in i)return i},e.prototype.parseAttributeList=function(e){for(var t,r,i,n,a={},s=/([A-Z0-9-]+)=(("[^"]*")|([^",]*))(?:,|$)/gi;null!==(n=s.exec(e));){var o=null!==(t=n[1])&&void 0!==t?t:"",l=null!==(i=null!==(r=n[3])&&void 0!==r?r:n[4])&&void 0!==i?i:"";l.startsWith('"')&&l.endsWith('"')&&(l=l.slice(1,-1)),o&&(a[o]=l)}return a},e.prototype.toNumber=function(e){if(null!=e){var t="string"==typeof e?parseFloat(e):Number(e);return Number.isNaN(t)?void 0:t}},e.prototype.isManifestBasedMarker=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.prototype.parseScte35Binary=function(e){var t=new(function(){function e(e){this.buf=e,this.bytePos=0,this.bitPos=0}return e.prototype.readBits=function(e){for(var t=0;e>0;){if(this.bytePos>=this.buf.length)return t;var 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)},e}())(e);if(252===t.readBits(8)){t.readBits(1),t.readBits(1),t.readBits(2);t.readBits(12);t.readBits(8),t.readBits(1),t.readBits(6);t.readBits(1),t.readBits(32);t.readBits(8),t.readBits(12);t.readBits(12);if(5===t.readBits(8)){t.readBits(32);var r=1===t.readBits(1);if(t.readBits(7),!r){var i=1===t.readBits(1),n=1===t.readBits(1),a=1===t.readBits(1),s=1===t.readBits(1);if(t.readBits(4),n&&!s)1===t.readBits(1)?(t.readBits(6),t.readBits(33)):t.readBits(7);else if(!n)for(var o=t.readBits(8),l=0;l<o;l++){if(t.readBits(8),!s)1===t.readBits(1)?(t.readBits(6),t.readBits(33)):t.readBits(7)}var u=void 0;if(a)t.readBits(6),t.readBits(1),u=(4294967296*t.readBits(1)+t.readBits(32))/9e4;if(t.readBits(16),t.readBits(8),t.readBits(8),i)return w(w({type:"start"},void 0!==u?{durationSeconds:u}:{}),{raw:{splice_command_type:5}})}}}},e.prototype.initializeTracking=function(){var e=this;Iu(this.config.licenseKey).then(function(){e.heartbeatInterval=window.setInterval(function(){e.sendHeartbeatIfNeeded()},5e3)}).catch(function(t){e.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Failed to send initial tracking:",t),e.heartbeatInterval=window.setInterval(function(){e.sendHeartbeatIfNeeded()},5e3)})},e.prototype.sendHeartbeatIfNeeded=function(){var e=this,t=Date.now();(!this.lastHeartbeatTime||t-this.lastHeartbeatTime>3e4)&&(this.lastHeartbeatTime=t,wu(this.config.licenseKey).catch(function(t){e.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Failed to send heartbeat:",t)}))},e.prototype.fetchAdConfiguration=function(){return D(this,void 0,void 0,function(){var e,t,r,i,n,a,s,o,l,u,c,d,h,f,v;return x(this,function(g){switch(g.label){case 0:return e=this.config.vastMode||"default",this.config.debugAdTiming&&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.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Using AdStorm VAST endpoint (adstorm mode):",t),[2]):(this.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] AdStorm mode requires a license key"),[2]):this.config.vastTagUrl?(this.apiVastTagUrl=this.config.vastTagUrl,this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Using custom VAST tag URL:",this.apiVastTagUrl),[2]):(r="https://adstorm.co/api-adstorm-dev/adstorm/ads/web",this.config.debugAdTiming&&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 1:return(n=g.sent()).ok?[4,n.json()]:(this.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Failed to fetch ad configuration: ".concat(n.status)),[2]);case 2:return a=g.sent(),(s=null===(c=null===(u=null===(l=a.response)||void 0===l?void 0:l.ima)||void 0===u?void 0:u["publisherdesk.ima"])||void 0===c?void 0:c.payload)?(this.apiVastTagUrl=decodeURIComponent(s),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Extracted VAST tag URL from /ads/web:",this.apiVastTagUrl)):this.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] No VAST tag URL found in /ads/web response"),null!=(o=null===(v=null===(f=null===(h=null===(d=a.response)||void 0===d?void 0:d.options)||void 0===h?void 0:h.vast)||void 0===f?void 0:f.cue_tones)||void 0===v?void 0:v.number_ads)&&o>0&&(this.apiNumberAds=o,this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Number of ads per break from API:",this.apiNumberAds)),[2]}})})},e.prototype.getCurrentAdIndex=function(){return this.currentAdIndex},e.prototype.getTotalAdsInBreak=function(){return this.totalAdsInBreak},e.prototype.generateVastUrlsWithCorrelators=function(e,t){for(var r=[],i=0;i<t;i++)try{var n=new URL(e),a=Date.now(),s=Math.floor(1e6*Math.random()),o="".concat(a).concat(s).concat(i);n.searchParams.set("correlator",o),r.push(n.toString())}catch(t){console.warn("[StormcloudVideoPlayer] Failed to parse VAST URL:",e,t),r.push("".concat(e).concat(e.includes("?")?"&":"?","correlator=").concat(Date.now()).concat(i))}return r},e.prototype.isAdPlaying=function(){return this.inAdBreak&&this.ima.isAdPlaying()},e.prototype.isShowingAds=function(){return this.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.shouldContinueLiveStreamDuringAds=function(){return!this.config.allowNativeHls&&!!this.isLiveStream},e.prototype.handleAdStart=function(e){return D(this,void 0,void 0,function(){var t,r,i,n,a,s,o,l,u;return x(this,function(c){switch(c.label){case 0:if(t=this.findCurrentOrNextBreak(1e3*this.video.currentTime),r=this.selectVastTagsForBreak(t),this.apiVastTagUrl)i=this.apiVastTagUrl;else{if(!(r&&r.length>0&&r[0]))return[2];i=r[0]}if(n=null!=e.durationSeconds?1e3*e.durationSeconds:null==t?void 0:t.durationMs,this.isLiveStream&&null!=n&&n>0?(this.isAdaptiveMode=!0,this.targetAdBreakDurationMs=n,this.fetchedAdDurations.clear(),this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 📺 LIVE MODE: Target duration=".concat(n,"ms | ")+"Will continuously fetch ads during break")):(this.isAdaptiveMode=!1,this.targetAdBreakDurationMs=null,this.fetchedAdDurations.clear(),this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🎬 VOD MODE: Using fixed ad strategy")),this.adPodAllUrls=[],this.preloadingAdUrls.clear(),this.vastToMediaUrlMap.clear(),this.preloadedMediaUrls.clear(),this.preloadingMediaUrls.clear(),this.failedVastUrls.clear(),this.adRequestQueue=[],this.successfulAdRequests=[],this.continuousFetchingActive=!0,this.isShowingPlaceholder=!1,this.placeholderStartTimeMs=null,this.consecutiveEmptyResponses=0,this.totalAdRequestsInBreak=0,this.lastEmptyResponseTimeMs=0,a=this.video.muted,s=this.video.volume,this.ima.updateOriginalMutedState(a,s),this.inAdBreak=!0,this.currentAdIndex=0,this.totalAdsInBreak=1,this.adPodQueue=[],this.showAds=!0,this.ima.showPlaceholder(),null==this.expectedAdBreakDurationMs&&null!=n&&(this.expectedAdBreakDurationMs=n,this.currentAdBreakStartWallClockMs=Date.now(),this.scheduleAdStopCountdown(this.expectedAdBreakDurationMs)),this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🚀 Immediately requesting first ad..."),o=this.generateVastUrlsWithCorrelators(i,1),!(l=o[0]))return this.config.debugAdTiming&&console.warn("[CONTINUOUS-FETCH] ⚠️ Failed to generate first ad URL"),this.handleAdPodComplete(),[2];c.label=1;case 1:return c.trys.push([1,4,,5]),[4,this.ima.requestAds(l)];case 2:return c.sent(),this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ✅ First ad request successful, starting playback"),this.successfulAdRequests.push(l),this.currentAdIndex++,this.startContinuousFetching(i),[4,this.ima.play()];case 3:return c.sent(),[3,5];case 4:return u=c.sent(),this.config.debugAdTiming&&console.warn("[CONTINUOUS-FETCH] ⚠️ First ad request failed:",u),this.failedVastUrls.add(l),this.startContinuousFetching(i),this.tryNextAvailableAd(),[3,5];case 5:return[2]}})})},e.prototype.startContinuousFetching=function(e){this.continuousFetchingActive&&(this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🔄 Starting continuous ad fetching loop"),this.continuousFetchLoop(e))},e.prototype.continuousFetchLoop=function(e){return D(this,void 0,void 0,function(){var t,r,i,n,a;return x(this,function(s){switch(s.label){case 0:t=function(){var t,s,o,l;return x(this,function(u){switch(u.label){case 0:return r.getRemainingAdMs()<=0?(r.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ⏹️ Ad break time expired, stopping fetch loop"),[2,"break"]):r.totalAdRequestsInBreak>=r.maxTotalAdRequestsPerBreak?(r.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🛑 Maximum ad requests reached (".concat(r.maxTotalAdRequestsPerBreak,"), stopping fetch loop to prevent server blocks")),[2,"break"]):r.consecutiveEmptyResponses>=r.maxConsecutiveEmptyResponses?(r.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🛑 Too many consecutive empty responses (".concat(r.maxConsecutiveEmptyResponses,"), stopping fetch loop")),[2,"break"]):r.adRequestQueue.length>=3?(r.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ⏸️ Queue full (".concat(r.adRequestQueue.length,"), pausing fetching...")),[4,new Promise(function(e){return setTimeout(e,2e3)})]):[3,2];case 1:return u.sent(),[2,"continue"];case 2:return(t=r.generateVastUrlsWithCorrelators(e,1)[0])&&!r.failedVastUrls.has(t)?[3,4]:[4,new Promise(function(e){return setTimeout(e,1e3)})];case 3:return u.sent(),[2,"continue"];case 4:r.totalAdRequestsInBreak++,r.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 📡 Attempting to fetch ad (request ".concat(r.totalAdRequestsInBreak,"/").concat(r.maxTotalAdRequestsPerBreak,", queue: ").concat(r.adRequestQueue.length,")...")),u.label=5;case 5:return u.trys.push([5,11,,13]),r.ima.preloadAds?[4,r.ima.preloadAds(t)]:[3,7];case 6:u.sent(),u.label=7;case 7:return null!==(a=null===(n=(i=r.ima).hasPreloadedAd)||void 0===n?void 0:n.call(i,t))&&void 0!==a&&a?[3,9]:(r.consecutiveEmptyResponses++,r.lastEmptyResponseTimeMs=Date.now(),s=Math.min(r.baseEmptyResponseDelayMs*Math.pow(2,r.consecutiveEmptyResponses-1),r.maxEmptyResponseDelayMs),r.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ⚠️ Empty/invalid VAST response (".concat(r.consecutiveEmptyResponses,"/").concat(r.maxConsecutiveEmptyResponses," consecutive), backing off for ").concat(s,"ms")),r.failedVastUrls.add(t),[4,new Promise(function(e){return setTimeout(e,s)})]);case 8:return u.sent(),[2,"continue"];case 9:return r.consecutiveEmptyResponses=0,r.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ✅ Successfully preloaded ad, adding to queue (queue size: ".concat(r.adRequestQueue.length+1,")")),r.adRequestQueue.push(t),r.totalAdsInBreak++,[4,new Promise(function(e){return setTimeout(e,500)})];case 10:return u.sent(),[3,13];case 11:return o=u.sent(),r.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ❌ Ad preload failed:",o.message),r.failedVastUrls.add(t),r.consecutiveEmptyResponses++,l=Math.min(r.baseEmptyResponseDelayMs*Math.pow(2,r.consecutiveEmptyResponses-1),r.maxEmptyResponseDelayMs),[4,new Promise(function(e){return setTimeout(e,l)})];case 12:return u.sent(),[3,13];case 13:return[2]}})},r=this,s.label=1;case 1:return this.continuousFetchingActive&&this.inAdBreak?[5,t()]:[3,3];case 2:return"break"===s.sent()?[3,3]:[3,1];case 3:return this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🛑 Continuous fetch loop ended (total requests: ".concat(this.totalAdRequestsInBreak,", empty responses: ").concat(this.consecutiveEmptyResponses,")")),[2]}})})},e.prototype.stopContinuousFetching=function(){this.continuousFetchingActive=!1,this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🛑 Stopping continuous ad fetching")},e.prototype.tryNextAvailableAd=function(){return D(this,arguments,void 0,function(e){var t,r,i,n,a=this;return void 0===e&&(e=0),x(this,function(s){switch(s.label){case 0:return(t=this.getRemainingAdMs())<=500?(this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ⏹️ No time remaining, ending ad break"),this.handleAdPodComplete(),[2]):this.adRequestQueue.length>0&&(r=this.adRequestQueue.shift())?(this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🎬 Playing next queued ad (".concat(this.currentAdIndex+1,"/").concat(this.totalAdsInBreak,", ").concat(this.adRequestQueue.length," remaining in queue)")),i=this.video.muted,n=this.video.volume,this.ima.updateOriginalMutedState(i,n),this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] 🔊 Updated ad audio state: muted=".concat(i,", volume=").concat(n)),this.currentAdIndex++,this.successfulAdRequests.push(r),[4,this.playSingleAd(r).catch(function(){a.tryNextAvailableAd(0)})]):[3,2];case 1:case 4:return s.sent(),[2];case 2:return this.continuousFetchingActive&&e<5&&t>2e3?(this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ⏳ Queue empty but fetching active, waiting... (retry ".concat(e+1,"/").concat(5,")")),[4,new Promise(function(e){return setTimeout(e,1e3)})]):[3,5];case 3:return s.sent(),[4,this.tryNextAvailableAd(e+1)];case 5:return!this.isShowingPlaceholder&&t>1e3?this.showPlaceholderAndWaitForAds():(this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ⏹️ No more ads available, ending ad break"),this.handleAdPodComplete()),[2]}})})},e.prototype.showPlaceholderAndWaitForAds=function(){return D(this,void 0,void 0,function(){var e,t,r,i,n,a,s,o,l=this;return x(this,function(u){switch(u.label){case 0:if(e=this.getRemainingAdMs(),(t=Math.min(this.maxPlaceholderDurationMs,e))<1e3)return this.handleAdPodComplete(),[2];this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ⬛ Showing black placeholder for ".concat(t,"ms while waiting for ads")),this.isShowingPlaceholder=!0,this.placeholderStartTimeMs=Date.now(),this.ima.showPlaceholder(),r=500,i=Math.floor(t/r),n=0,u.label=1;case 1:return n<i?[4,new Promise(function(e){return setTimeout(e,r)})]:[3,6];case 2:return u.sent(),this.inAdBreak?this.adRequestQueue.length>0?(this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ✅ New ad became available during placeholder"),this.isShowingPlaceholder=!1,this.placeholderStartTimeMs=null,this.ima.hidePlaceholder(),a=this.video.muted,s=this.video.volume,this.ima.updateOriginalMutedState(a,s),(o=this.adRequestQueue.shift())?(this.currentAdIndex++,this.successfulAdRequests.push(o),[4,this.playSingleAd(o).catch(function(){l.tryNextAvailableAd()})]):[3,4]):[3,5]:[2];case 3:u.sent(),u.label=4;case 4:return[2];case 5:return n++,[3,1];case 6:return this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] ⏰ Placeholder timeout reached, no ads fetched"),this.isShowingPlaceholder=!1,this.placeholderStartTimeMs=null,this.ima.hidePlaceholder(),this.handleAdPodComplete(),[2]}})})},e.prototype.findCurrentOrNextBreak=function(e){var t,r,i,n;try{for(var a=C([]),s=a.next();!s.done;s=a.next()){var o=s.value,l=null!==(i=this.config.driftToleranceMs)&&void 0!==i?i:1e3;o.startTimeMs<=e+l&&(null==n||o.startTimeMs>(n.startTimeMs||0))&&(n=o)}}catch(e){t={error:e}}finally{try{s&&!s.done&&(r=a.return)&&r.call(a)}finally{if(t)throw t.error}}return n},e.prototype.onTimeUpdate=function(e){if(!this.ima.isAdPlaying()){var t=1e3*e,r=this.findBreakForTime(t);r&&this.handleMidAdJoin(r,t)}},e.prototype.handleMidAdJoin=function(e,t){return D(this,void 0,void 0,function(){var r,i,n,a,s,o,l;return x(this,function(u){switch(u.label){case 0:return r=null!==(l=e.durationMs)&&void 0!==l?l:0,i=e.startTimeMs+r,r>0&&t>e.startTimeMs&&t<i?(n=i-t,(a=this.selectVastTagsForBreak(e)||(this.apiVastTagUrl?[this.apiVastTagUrl]:void 0))&&a.length>0?(s=a[0],o=a.slice(1),this.adPodQueue=o,this.ima.updateOriginalMutedState(this.video.muted,this.video.volume),[4,this.playSingleAd(s)]):[3,2]):[3,2];case 1:u.sent(),this.inAdBreak=!0,this.expectedAdBreakDurationMs=n,this.currentAdBreakStartWallClockMs=Date.now(),this.scheduleAdStopCountdown(n),u.label=2;case 2:return[2]}})})},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(){var e,t;if(this.inAdBreak){this.adStopTimerId=void 0;var r=this.ima.isAdPlaying(),i=this.adPodQueue.length>0,n=Math.max(250,Math.floor(null!==(e=this.config.adBreakCheckIntervalMs)&&void 0!==e?e:1e3)),a=this.config.maxAdBreakExtensionMs,s="number"==typeof a&&a>0?a:6e4,o=0;null!=this.currentAdBreakStartWallClockMs&&(o=Date.now()-this.currentAdBreakStartWallClockMs);var l=null!==(t=this.expectedAdBreakDurationMs)&&void 0!==t?t:0,u=Math.max(0,o-l);(r||i||this.showAds)&&u<s?this.scheduleAdStopCountdown(n):(r&&this.ima.stop().catch(function(){}),this.handleAdPodComplete())}},e.prototype.scheduleAdStartIn=function(e){var t=this;this.clearAdStartTimer();var r=Math.max(0,Math.floor(e));0!==r?this.adStartTimerId=window.setTimeout(function(){t.handleAdStart({type:"start"}).catch(function(){})},r):this.handleAdStart({type:"start"}).catch(function(){})},e.prototype.clearAdStartTimer=function(){null!=this.adStartTimerId&&(clearTimeout(this.adStartTimerId),this.adStartTimerId=void 0)},e.prototype.updatePtsDrift=function(e){var t=1e3*(this.video.currentTime-e);if(Number.isFinite(t)&&!(Math.abs(t)>6e4)){this.ptsDriftEmaMs=.9*this.ptsDriftEmaMs+.1*t}},e.prototype.playSingleAd=function(e){return D(this,void 0,void 0,function(){var t,r,i;return x(this,function(n){switch(n.label){case 0:if(this.ima.isAdPlaying())return[2];if(this.failedVastUrls.has(e))return console.warn("[AD-ERROR] Skipping already-failed VAST URL:",e.substring(0,60)),this.handleAdFailure(),[2];t=++this.adRequestTokenCounter,this.activeAdRequestToken=t,this.startAdRequestWatchdog(t),n.label=1;case 1:return n.trys.push([1,7,,8]),[4,this.ima.requestAds(e)];case 2:if(n.sent(),this.clearAdRequestWatchdog(),this.activeAdRequestToken!==t)return[2];n.label=3;case 3:return n.trys.push([3,5,,6]),this.startAdFailsafeTimer(t),[4,this.ima.play()];case 4:return n.sent(),[3,6];case 5:return r=n.sent(),console.error("[AD-ERROR] Failed to play ad:",r),this.failedVastUrls.add(e),this.clearAdFailsafeTimer(),this.activeAdRequestToken===t&&(this.activeAdRequestToken=null),this.handleAdFailure(),[2];case 6:return[3,8];case 7:return i=n.sent(),console.error("[AD-ERROR] Ad request failed:",null==i?void 0:i.message),this.failedVastUrls.add(e),this.clearAdRequestWatchdog(),this.clearAdFailsafeTimer(),this.activeAdRequestToken===t&&(this.activeAdRequestToken=null),this.handleAdFailure(),[3,8];case 8:return[2]}})})},e.prototype.handleAdPodComplete=function(){var e;this.clearAdRequestWatchdog(),this.clearAdFailsafeTimer(),this.activeAdRequestToken=null,this.stopContinuousFetching(),this.isShowingPlaceholder&&(this.ima.hidePlaceholder(),this.isShowingPlaceholder=!1,this.placeholderStartTimeMs=null),this.preloadingAdUrls.clear(),this.vastToMediaUrlMap.clear(),this.preloadedMediaUrls.clear(),this.preloadingMediaUrls.clear(),this.adRequestQueue=[],this.successfulAdRequests=[],this.inAdBreak=!1,this.expectedAdBreakDurationMs=void 0,this.currentAdBreakStartWallClockMs=void 0,this.clearAdStartTimer(),this.clearAdStopTimer(),this.adPodQueue=[],this.adPodAllUrls=[],this.showAds=!1,this.currentAdIndex=0,this.totalAdsInBreak=0,this.ima.stop().catch(function(){});var t=this.ima.getOriginalMutedState(),r=this.ima.getOriginalVolume();this.video.muted!==t&&(this.video.muted=t),Math.abs(this.video.volume-r)>.01&&(this.video.volume=r),!this.shouldContinueLiveStreamDuringAds()&&this.video.paused&&(null===(e=this.video.play())||void 0===e||e.catch(function(){}))},e.prototype.handleAdFailure=function(){var e=this.getRemainingAdMs();this.config.debugAdTiming&&console.log("[CONTINUOUS-FETCH] Ad failure: remaining=".concat(e,"ms, queued ads=").concat(this.adRequestQueue.length)),e>500?this.tryNextAvailableAd():(console.error("[AD-ERROR] Ad failed and no time remaining. Failed URLs:",this.failedVastUrls.size),this.handleAdPodComplete())},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.handleAdFailure())},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,imaAdPlaying:r.ima.isAdPlaying()}),r.handleAdFailure())},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.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.logAdState=function(e,t){void 0===t&&(t={}),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer][AdState]",w({event:e,timestamp:(new Date).toISOString(),showAds:this.showAds,adPlaying:this.ima.isAdPlaying(),inAdBreak:this.inAdBreak,activeAdRequestToken:this.activeAdRequestToken},t))},e.prototype.fetchAndParseVastXml=function(e){return D(this,void 0,void 0,function(){var t,r,i;return x(this,function(n){switch(n.label){case 0:return n.trys.push([0,3,,4]),[4,fetch(e,{mode:"cors"})];case 1:if(!(t=n.sent()).ok)throw new Error("Failed to fetch VAST: ".concat(t.status));return[4,t.text()];case 2:return r=n.sent(),[2,this.extractMediaUrlsFromVast(r)];case 3:return i=n.sent(),this.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Failed to fetch/parse VAST XML: ".concat(e),i),[2,[]];case 4:return[2]}})})},e.prototype.extractMediaUrlsFromVast=function(e){var t,r,i,n=[];try{var a=(new DOMParser).parseFromString(e,"text/xml").querySelectorAll("MediaFile");try{for(var s=C(Array.from(a)),o=s.next();!o.done;o=s.next()){var l=null===(i=o.value.textContent)||void 0===i?void 0:i.trim();if(l){var u=l.toLowerCase();(u.endsWith(".mp4")||u.endsWith(".webm")||u.endsWith(".mov")||u.endsWith(".avi")||u.includes(".mp4?")||u.includes(".webm?")||u.includes("/mp4/")||u.includes("type=video"))&&n.push(l)}}}catch(e){t={error:e}}finally{try{o&&!o.done&&(r=s.return)&&r.call(s)}finally{if(t)throw t.error}}this.config.debugAdTiming&&n.length>0&&console.log("[StormcloudVideoPlayer] Extracted ".concat(n.length," media URLs from VAST:"),n)}catch(e){this.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Failed to parse VAST XML:",e)}return n},e.prototype.fetchVastDuration=function(e){return D(this,void 0,void 0,function(){var t,r,i,n,a,s,o,l;return x(this,function(u){switch(u.label){case 0:return u.trys.push([0,3,,4]),[4,fetch(e,{mode:"cors"})];case 1:return(t=u.sent()).ok?[4,t.text()]:(this.config.debugAdTiming&&console.warn("[ADAPTIVE-POD] Failed to fetch VAST: ".concat(t.status)),[2,null]);case 2:return r=u.sent(),i=new DOMParser,n=i.parseFromString(r,"text/xml"),(a=null===(l=n.querySelector("Duration"))||void 0===l?void 0:l.textContent)?(s=a.split(":"),[2,3600*parseInt(s[0]||"0",10)+60*parseInt(s[1]||"0",10)+parseInt(s[2]||"0",10)]):(this.config.debugAdTiming&&console.warn("[ADAPTIVE-POD] No Duration element found in VAST"),[2,null]);case 3:return o=u.sent(),this.config.debugAdTiming&&console.warn("[ADAPTIVE-POD] Error fetching VAST duration from ".concat(e,":"),o),[2,null];case 4:return[2]}})})},e.prototype.calculateAdditionalAdsNeeded=function(){var e,t;if(!this.isAdaptiveMode||null===this.targetAdBreakDurationMs)return 0;var r=0;try{for(var i=C(this.fetchedAdDurations.values()),n=i.next();!n.done;n=i.next()){r+=1e3*n.value}}catch(t){e={error:t}}finally{try{n&&!n.done&&(t=i.return)&&t.call(i)}finally{if(e)throw e.error}}var a=this.fetchedAdDurations.size,s=a>0?r/a:3e4,o=this.adPodAllUrls.length-a,l=o*s,u=r+l,c=this.targetAdBreakDurationMs-u;if(c<=0)return this.config.debugAdTiming&&console.log("[ADAPTIVE-POD] ✅ Target duration met: Fetched=".concat(r,"ms + Queued(").concat(o," ads)=").concat(l,"ms = ").concat(u,"ms / Target=").concat(this.targetAdBreakDurationMs,"ms")),0;var d=Math.ceil(c/s);return this.config.debugAdTiming&&console.log("[ADAPTIVE-POD] 📊 Need ".concat(d," more ads | ")+"Fetched: ".concat(r,"ms (").concat(a," ads) | ")+"Queued: ".concat(l,"ms (").concat(o," ads) | ")+"Target: ".concat(this.targetAdBreakDurationMs,"ms | ")+"Remaining: ".concat(c,"ms | ")+"Avg duration: ".concat(s,"ms")),d},e.prototype.addAdaptiveAdsToQueue=function(){return D(this,void 0,void 0,function(){var e,t,r,i;return x(this,function(n){return this.isAdaptiveMode&&this.apiVastTagUrl?((e=this.calculateAdditionalAdsNeeded())<=0||(t=this.generateVastUrlsWithCorrelators(this.apiVastTagUrl,e),this.config.debugAdTiming&&console.log("[ADAPTIVE-POD] 🔄 Adding ".concat(t.length," additional VAST URLs to queue (will be preloaded sequentially)")),(r=this.adPodAllUrls).push.apply(r,M([],_(t),!1)),(i=this.adPodQueue).push.apply(i,M([],_(t),!1)),this.totalAdsInBreak+=t.length),[2]):[2]})})},e.prototype.preloadMediaFile=function(e){return D(this,void 0,void 0,function(){var t,r;return x(this,function(i){switch(i.label){case 0:if(this.preloadedMediaUrls.has(e))return[2];if(this.preloadingMediaUrls.has(e))return[2];this.preloadingMediaUrls.add(e),i.label=1;case 1:return i.trys.push([1,3,4,5]),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Preloading video file: ".concat(e)),[4,fetch(e,{mode:"cors",method:"GET",headers:{Range:"bytes=0-1048576"}})];case 2:return((t=i.sent()).ok||206===t.status)&&(this.preloadedMediaUrls.add(e),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Successfully preloaded video file: ".concat(e))),[3,5];case 3:return r=i.sent(),this.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Failed to preload video file: ".concat(e),r),[3,5];case 4:return this.preloadingMediaUrls.delete(e),[7];case 5:return[2]}})})},e.prototype.preloadAllAdsInBackground=function(){return D(this,void 0,void 0,function(){var e,t,r,i,n,a,s,o,l,u,c,d=this;return x(this,function(h){switch(h.label){case 0:if(0===this.adPodAllUrls.length)return[2];if(!this.isAdaptiveMode)return[3,7];this.config.debugAdTiming&&console.log("[ADAPTIVE-POD] 🔄 Starting sequential preload of remaining ads"),e=new Set;try{for(t=C(this.adPodAllUrls),r=t.next();!r.done;r=t.next())i=r.value,((null===(c=(u=this.ima).hasPreloadedAd)||void 0===c?void 0:c.call(u,i))||this.fetchedAdDurations.has(i))&&e.add(i)}catch(e){o={error:e}}finally{try{r&&!r.done&&(l=t.return)&&l.call(t)}finally{if(o)throw o.error}}this.config.debugAdTiming&&e.size>0&&console.log("[ADAPTIVE-POD] 📦 Skipping ".concat(e.size," already-preloaded ads")),h.label=1;case 1:if(n=this.adPodAllUrls.find(function(t){return!e.has(t)}),!n)return this.config.debugAdTiming&&console.log("[ADAPTIVE-POD] ✅ All queued ads processed (".concat(e.size," total)")),[3,6];e.add(n),this.config.debugAdTiming&&console.log("[ADAPTIVE-POD] 📥 Preloading ad ".concat(e.size,"/").concat(this.adPodAllUrls.length,"...")),h.label=2;case 2:return h.trys.push([2,4,,5]),[4,this.preloadSingleAd(n)];case 3:return h.sent(),[3,5];case 4:return a=h.sent(),this.config.debugAdTiming&&console.warn("[ADAPTIVE-POD] ⚠️ Preload failed for ad ".concat(e.size,":"),a),[3,5];case 5:return 0===this.calculateAdditionalAdsNeeded()?(this.config.debugAdTiming&&console.log("[ADAPTIVE-POD] ✅ Target duration reached (".concat(e.size," ads preloaded), stopping")),[3,6]):[3,1];case 6:return this.config.debugAdTiming&&console.log("[ADAPTIVE-POD] ✅ Sequential preloading completed (".concat(e.size," ads ready)")),[3,9];case 7:return this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Starting parallel preload of ".concat(this.adPodAllUrls.length," ads")),s=this.adPodAllUrls.map(function(e){return d.preloadSingleAd(e).catch(function(t){d.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Preload failed for ".concat(e,":"),t)})}),[4,Promise.all(s)];case 8:h.sent(),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Background preloading completed for all ads"),h.label=9;case 9:return[2]}})})},e.prototype.preloadSingleAd=function(e){return D(this,void 0,void 0,function(){var t,r,i,n,a=this;return x(this,function(s){switch(s.label){case 0:if(!e)return[2];s.label=1;case 1:return s.trys.push([1,11,,12]),!this.isAdaptiveMode||this.fetchedAdDurations.has(e)?[3,4]:[4,this.fetchVastDuration(e)];case 2:return null===(t=s.sent())?[3,4]:(this.fetchedAdDurations.set(e,t),this.config.debugAdTiming&&console.log("[ADAPTIVE-POD] ✓ Fetched ad duration: ".concat(t,"s (").concat(this.fetchedAdDurations.size," ads fetched so far)")),[4,this.addAdaptiveAdsToQueue()]);case 3:s.sent(),s.label=4;case 4:return!this.ima.preloadAds||this.ima.hasPreloadedAd(e)||this.preloadingAdUrls.has(e)?[3,6]:(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Preloading VAST: ".concat(e)),this.preloadingAdUrls.add(e),[4,this.ima.preloadAds(e).then(function(){a.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] IMA VAST preload complete: ".concat(e))}).catch(function(t){a.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] IMA VAST preload failed: ".concat(e),t)}).finally(function(){a.preloadingAdUrls.delete(e)})]);case 5:s.sent(),s.label=6;case 6:return(r=this.vastToMediaUrlMap.get(e))?[3,8]:(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Fetching and parsing VAST to extract media URLs: ".concat(e)),[4,this.fetchAndParseVastXml(e)]);case 7:r=s.sent(),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Extracted ".concat(r.length," media URLs:"),r),r.length>0&&this.vastToMediaUrlMap.set(e,r),s.label=8;case 8:return r&&r.length>0?!(i=r[0])||this.preloadedMediaUrls.has(i)?[3,10]:[4,this.preloadMediaFile(i)]:[3,10];case 9:s.sent(),s.label=10;case 10:return[3,12];case 11:return n=s.sent(),this.config.debugAdTiming&&console.warn("[StormcloudVideoPlayer] Failed to preload ad: ".concat(e),n),[3,12];case 12:return[2]}})})},e.prototype.findNextPreloadedAd=function(){for(var e,t,r,i=0;i<this.adPodQueue.length;i++){var n=this.adPodQueue[i];if(n)if(this.failedVastUrls.has(n))console.warn("[AD-ERROR] Skipping failed URL in queue");else{var a=null!==(r=null===(t=(e=this.ima).hasPreloadedAd)||void 0===t?void 0:t.call(e,n))&&void 0!==r&&r,s=this.vastToMediaUrlMap.get(n),o=!!(s&&s.length>0)&&this.preloadedMediaUrls.has(s[0]);if(a||o)return this.adPodQueue.splice(0,i+1),n}}},e.prototype.getRemainingAdMs=function(){if(null==this.expectedAdBreakDurationMs||null==this.currentAdBreakStartWallClockMs)return 0;var e=Date.now()-this.currentAdBreakStartWallClockMs;return Math.max(0,this.expectedAdBreakDurationMs-e)},e.prototype.findBreakForTime=function(e){var t,r;try{for(var i=C([]),n=i.next();!n.done;n=i.next()){var a=n.value,s=(a.startTimeMs||0)+(a.durationMs||0);if(e>=(a.startTimeMs||0)&&(!a.durationMs||e<s))return a}}catch(e){t={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}},e.prototype.toggleMute=function(){if(this.ima.isAdPlaying()){var e=!this.isMuted();this.ima.updateOriginalMutedState(e,this.video.volume),this.ima.setAdVolume(e?0:1),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Mute toggle during ad - immediately applied:",e)}else this.video.muted=!this.video.muted,this.ima.updateOriginalMutedState(this.video.muted,this.video.volume),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Muted:",this.video.muted)},e.prototype.toggleFullscreen=function(){var e=this;return new Promise(function(t,r){if(document.fullscreenElement)document.exitFullscreen().then(function(){e.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Exited fullscreen"),t()}).catch(function(t){e.config.debugAdTiming&&console.error("[StormcloudVideoPlayer] Exit fullscreen error:",t),r(t)});else{var i=e.video.parentElement;if(!i)return void r(new Error("No parent container found for fullscreen"));i.requestFullscreen().then(function(){e.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Entered fullscreen"),t()}).catch(function(t){e.config.debugAdTiming&&console.error("[StormcloudVideoPlayer] Fullscreen error:",t),r(t)})}})},e.prototype.isMuted=function(){return this.ima.isAdPlaying()?(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] isMuted() override during ad playback -> false"),!1):this.video.muted},e.prototype.setMuted=function(e){var t=this.ima.isAdPlaying();if(t&&e===this.video.muted)this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] setMuted reflective update during ad ignored",{muted:e});else{if(this.video.muted=e,t)return this.ima.updateOriginalMutedState(e,this.video.volume),this.ima.setAdVolume(e?0:1),void(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] setMuted applied during ad",{muted:e}));this.ima.updateOriginalMutedState(e,this.video.volume),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] setMuted called:",e)}},e.prototype.setVolume=function(e){var t=Math.max(0,Math.min(1,e));this.ima.isAdPlaying()?(this.ima.setAdVolume(t),this.ima.updateOriginalMutedState(0===t,t),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] setVolume applied during ad",{volume:t})):(this.video.volume=t,this.video.muted=0===t,this.ima.updateOriginalMutedState(0===t,t),this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] setVolume called:",t))},e.prototype.isFullscreen=function(){return!!document.fullscreenElement},e.prototype.isLive=function(){return this.isLiveStream},Object.defineProperty(e.prototype,"videoElement",{get:function(){return this.video},enumerable:!1,configurable:!0}),e.prototype.resize=function(){if(this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Resizing player"),this.ima&&this.ima.isAdPlaying()){var e=this.video.clientWidth||640,t=this.video.clientHeight||360;this.config.debugAdTiming&&console.log("[StormcloudVideoPlayer] Resizing ads manager to ".concat(e,"x").concat(t)),this.ima.resize(e,t)}},e.prototype.destroy=function(){var e,t;this.stopContinuousFetching(),this.clearAdStartTimer(),this.clearAdStopTimer(),this.clearAdFailsafeTimer(),this.clearAdRequestWatchdog(),this.timeUpdateHandler&&(this.video.removeEventListener("timeupdate",this.timeUpdateHandler),delete this.timeUpdateHandler),this.emptiedHandler&&(this.video.removeEventListener("emptied",this.emptiedHandler),delete this.emptiedHandler),this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=void 0),null===(e=this.hls)||void 0===e||e.destroy(),null===(t=this.ima)||void 0===t||t.destroy(),this.preloadingAdUrls.clear(),this.vastToMediaUrlMap.clear(),this.preloadedMediaUrls.clear(),this.preloadingMediaUrls.clear(),this.adPodAllUrls=[],this.adRequestQueue=[],this.successfulAdRequests=[]},e}(),xu={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},Cu=z.createContext&&z.createContext(xu),_u=["attr","size","title"];function Mu(e,t){if(null==e)return{};var r,i,n=function(e,t){if(null==e)return{};var r={};for(var i in e)if(Object.prototype.hasOwnProperty.call(e,i)){if(t.indexOf(i)>=0)continue;r[i]=e[i]}return r}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)r=a[i],t.indexOf(r)>=0||Object.prototype.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function Ou(){return Ou=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(e[i]=r[i])}return e},Ou.apply(this,arguments)}function Fu(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 Uu(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Fu(Object(r),!0).forEach(function(t){Nu(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Fu(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function Nu(e,t,r){var i;return i=function(e,t){if("object"!=S(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var i=r.call(e,t||"default");if("object"!=S(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(t,"string"),(t="symbol"==S(i)?i:i+"")in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Bu(e){return e&&e.map(function(e,t){return z.createElement(e.tag,Uu({key:t},e.attr),Bu(e.child))})}function Vu(e){return function(t){return z.createElement(Gu,Ou({attr:Uu({},e.attr)},t),Bu(e.child))}}function Gu(e){var t=function(t){var r,i=e.attr,n=e.size,a=e.title,s=Mu(e,_u),o=n||t.size||"1em";return t.className&&(r=t.className),e.className&&(r=(r?r+" ":"")+e.className),z.createElement("svg",Ou({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},t.attr,i,s,{className:r,style:Uu(Uu({color:e.color||t.color},t.style),e.style),height:o,width:o,xmlns:"http://www.w3.org/2000/svg"}),a&&z.createElement("title",null,a),e.children)};return void 0!==Cu?z.createElement(Cu.Consumer,null,function(e){return t(e)}):t(xu)}function Hu(e){return Vu({tag:"svg",attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M436 192H312c-13.3 0-24-10.7-24-24V44c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v84h84c6.6 0 12 5.4 12 12v40c0 6.6-5.4 12-12 12zm-276-24V44c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v84H12c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h124c13.3 0 24-10.7 24-24zm0 300V344c0-13.3-10.7-24-24-24H12c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h84v84c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm192 0v-84h84c6.6 0 12-5.4 12-12v-40c0-6.6-5.4-12-12-12H312c-13.3 0-24 10.7-24 24v124c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12z"},child:[]}]})(e)}function Ku(e){return Vu({tag:"svg",attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M0 180V56c0-13.3 10.7-24 24-24h124c6.6 0 12 5.4 12 12v40c0 6.6-5.4 12-12 12H64v84c0 6.6-5.4 12-12 12H12c-6.6 0-12-5.4-12-12zM288 44v40c0 6.6 5.4 12 12 12h84v84c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12V56c0-13.3-10.7-24-24-24H300c-6.6 0-12 5.4-12 12zm148 276h-40c-6.6 0-12 5.4-12 12v84h-84c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h124c13.3 0 24-10.7 24-24V332c0-6.6-5.4-12-12-12zM160 468v-40c0-6.6-5.4-12-12-12H64v-84c0-6.6-5.4-12-12-12H12c-6.6 0-12 5.4-12 12v124c0 13.3 10.7 24 24 24h124c6.6 0 12-5.4 12-12z"},child:[]}]})(e)}function ju(e){return Vu({tag:"svg",attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M144 479H48c-26.5 0-48-21.5-48-48V79c0-26.5 21.5-48 48-48h96c26.5 0 48 21.5 48 48v352c0 26.5-21.5 48-48 48zm304-48V79c0-26.5-21.5-48-48-48h-96c-26.5 0-48 21.5-48 48v352c0 26.5 21.5 48 48 48h96c26.5 0 48-21.5 48-48z"},child:[]}]})(e)}function qu(e){return Vu({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 Wu(e){return Vu({tag:"svg",attr:{viewBox:"0 0 512 512"},child:[{tag:"path",attr:{d:"M304 48c0 26.51-21.49 48-48 48s-48-21.49-48-48 21.49-48 48-48 48 21.49 48 48zm-48 368c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48-21.49-48-48-48zm208-208c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48-21.49-48-48-48zM96 256c0-26.51-21.49-48-48-48S0 229.49 0 256s21.49 48 48 48 48-21.49 48-48zm12.922 99.078c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48c0-26.509-21.491-48-48-48zm294.156 0c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48c0-26.509-21.49-48-48-48zM108.922 60.922c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48-21.491-48-48-48z"},child:[]}]})(e)}function Yu(e){return Vu({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 zu(e){return Vu({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 Xu(e){return Vu({tag:"svg",attr:{viewBox:"0 0 576 512"},child:[{tag:"path",attr:{d:"M215.03 71.05L126.06 160H24c-13.26 0-24 10.74-24 24v144c0 13.25 10.74 24 24 24h102.06l88.97 88.95c15.03 15.03 40.97 4.47 40.97-16.97V88.02c0-21.46-25.96-31.98-40.97-16.97zm233.32-51.08c-11.17-7.33-26.18-4.24-33.51 6.95-7.34 11.17-4.22 26.18 6.95 33.51 66.27 43.49 105.82 116.6 105.82 195.58 0 78.98-39.55 152.09-105.82 195.58-11.17 7.32-14.29 22.34-6.95 33.5 7.04 10.71 21.93 14.56 33.51 6.95C528.27 439.58 576 351.33 576 256S528.27 72.43 448.35 19.97zM480 256c0-63.53-32.06-121.94-85.77-156.24-11.19-7.14-26.03-3.82-33.12 7.46s-3.78 26.21 7.41 33.36C408.27 165.97 432 209.11 432 256s-23.73 90.03-63.48 115.42c-11.19 7.14-14.5 22.07-7.41 33.36 6.51 10.36 21.12 15.14 33.12 7.46C447.94 377.94 480 319.54 480 256zm-141.77-76.87c-11.58-6.33-26.19-2.16-32.61 9.45-6.39 11.61-2.16 26.2 9.45 32.61C327.98 228.28 336 241.63 336 256c0 14.38-8.02 27.72-20.92 34.81-11.61 6.41-15.84 21-9.45 32.61 6.43 11.66 21.05 15.8 32.61 9.45 28.23-15.55 45.77-45 45.77-76.88s-17.54-61.32-45.78-76.86z"},child:[]}]})(e)}var Qu=["src","allowNativeHls","licenseKey","lowLatencyMode","driftToleranceMs","vastMode"],$u=z.memo(function(e){var t=e.src,r=e.autoplay,i=e.muted,n=e.lowLatencyMode,a=e.allowNativeHls,s=e.driftToleranceMs,o=e.immediateManifestAds,l=e.debugAdTiming,u=e.showCustomControls,c=e.hideLoadingIndicator,d=e.onVolumeToggle,h=e.onFullscreenToggle,f=e.onControlClick,v=e.onReady,g=e.wrapperClassName,p=e.wrapperStyle,m=e.className,y=e.style,T=e.controls,E=e.playsInline,k=e.preload,S=e.poster,b=e.children,A=e.licenseKey,L=e.vastMode,R=e.vastTagUrl,I=e.adPlayerType,D=e.minSegmentsBeforePlay,x=P(e,["src","autoplay","muted","lowLatencyMode","allowNativeHls","driftToleranceMs","immediateManifestAds","debugAdTiming","showCustomControls","hideLoadingIndicator","onVolumeToggle","onFullscreenToggle","onControlClick","onReady","wrapperClassName","wrapperStyle","className","style","controls","playsInline","preload","poster","children","licenseKey","vastMode","vastTagUrl","adPlayerType","minSegmentsBeforePlay"]),C=Y.useRef(null),M=Y.useRef(null),O=Y.useRef(null),F=_(z.useState({showAds:!1,currentIndex:0,totalAds:0}),2),U=F[0],N=F[1],B=_(z.useState(!0),2),V=B[0],G=B[1],H=_(z.useState(!1),2),K=H[0],j=H[1],q=_(z.useState(!1),2),X=q[0],Q=q[1],$=_(z.useState(!1),2),J=$[0],Z=$[1],ee=_(z.useState(0),2),te=ee[0],re=ee[1],ie=_(z.useState(0),2),ne=ie[0],ae=ie[1],se=_(z.useState(1),2),oe=se[0],le=se[1],ue=_(z.useState(1),2),ce=ue[0],de=ue[1],he=_(z.useState(!1),2),fe=he[0],ve=he[1],ge=_(z.useState(!1),2),pe=ge[0],me=ge[1],ye=_(z.useState(!0),2),Te=ye[0],Ee=ye[1],ke=_(z.useState(!1),2),Se=ke[0],be=ke[1],Ae=_(z.useState(!1),2),Le=Ae[0],Re=Ae[1],Ie=_(z.useState(!1),2),we=Ie[0],Pe=Ie[1],De=_(z.useState("undefined"!=typeof window?window.innerWidth:1920),2),xe=De[0],Ce=De[1],_e=_(z.useState("undefined"!=typeof window&&window.innerHeight>window.innerWidth),2),Me=_e[0],Oe=_e[1],Fe=xe<480?.7:xe<768?.8:xe<1024?.9:1,Ue=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"))},Ne=function(e){if(M.current&&isFinite(e)){var t=Math.max(0,Math.min(1,e));M.current.setVolume(t)}},Be=(null==t?void 0:t.toLowerCase().includes(".m3u8"))||(null==t?void 0:t.toLowerCase().includes("/hls/")),Ve=u&&(!Be||a),Ge=Y.useMemo(function(){return Qu.map(function(t){return"".concat(t,":").concat(e[t])}).join("|")},[t,a,A,n,s,L]);return Y.useEffect(function(){if("undefined"!=typeof window){var e=C.current;if(e&&t){if(!A)return Pe(!0),Ee(!1),void console.warn("StormcloudVideoPlayer: License key is required but not provided. Please set the licenseKey prop to use the player.");if(Pe(!1),l&&console.log("[StormcloudUI] Initializing player, isLoading=true"),M.current){try{M.current.destroy()}catch(e){}M.current=null}var c={src:t,videoElement:e};void 0!==r&&(c.autoplay=r),void 0!==i&&(c.muted=i),void 0!==n&&(c.lowLatencyMode=n),void 0!==a&&(c.allowNativeHls=a),void 0!==s&&(c.driftToleranceMs=s),void 0!==o&&(c.immediateManifestAds=o),void 0!==l&&(c.debugAdTiming=l),void 0!==u&&(c.showCustomControls=u),void 0!==d&&(c.onVolumeToggle=d),void 0!==h&&(c.onFullscreenToggle=h),void 0!==f&&(c.onControlClick=f),void 0!==A&&(c.licenseKey=A),void 0!==L&&(c.vastMode=L),void 0!==R&&(c.vastTagUrl=R),void 0!==I&&(c.adPlayerType=I),void 0!==D&&(c.minSegmentsBeforePlay=D);var g=new Du(c);return M.current=g,g.load().then(function(){var e=g.shouldShowNativeControls();G(e),l&&console.log("[StormcloudUI] Player loaded successfully, waiting for video ready"),null==v||v(g)}).catch(function(e){console.error("StormcloudVideoPlayer: Failed to load player:",e),Ee(!1),null==v||v(g)}),function(){try{g.destroy()}catch(e){}M.current=null}}}},[Ge]),Y.useEffect(function(){if(M.current)try{void 0!==r&&M.current.videoElement&&(M.current.videoElement.autoplay=r),void 0===i||M.current.isShowingAds()||M.current.setMuted(i)}catch(e){console.warn("Failed to update player properties:",e)}},[r,i]),Y.useEffect(function(){if(M.current){var e=setInterval(function(){var e,t;if(M.current){var r=M.current.isShowingAds(),i="true"===(null===(t=null===(e=C.current)||void 0===e?void 0:e.dataset)||void 0===t?void 0:t.stormcloudAdPlaying),n=r||i,a=M.current.getCurrentAdIndex(),s=M.current.getTotalAdsInBreak();N(function(e){return e.showAds!==n||e.currentIndex!==a||e.totalAds!==s?(n&&!e.showAds&&Re(!1),{showAds:n,currentIndex:a,totalAds:s}):e})}},50);return function(){return clearInterval(e)}}},[]),Y.useEffect(function(){if("undefined"!=typeof window&&M.current){var e=function(){M.current&&C.current&&"function"==typeof M.current.resize&&M.current.resize(),Ce(window.innerWidth),Oe(window.innerHeight>window.innerWidth)};return window.addEventListener("resize",e),function(){return window.removeEventListener("resize",e)}}},[]),Y.useEffect(function(){if(M.current&&C.current){var e=setInterval(function(){var e;if(M.current&&C.current){j(M.current.isMuted()),Z(!C.current.paused);var t=C.current.currentTime;re(isFinite(t)?t:0);var r=C.current.duration;ae(isFinite(r)?r:0);var i=C.current.volume;le(isFinite(i)?Math.max(0,Math.min(1,i)):1);var n=C.current.playbackRate;de(isFinite(n)&&n>0?n:1)}Q(document.fullscreenElement===(null===(e=C.current)||void 0===e?void 0:e.parentElement))},200),t=function(){var e;Q(document.fullscreenElement===(null===(e=C.current)||void 0===e?void 0:e.parentElement))};return document.addEventListener("fullscreenchange",t),function(){clearInterval(e),document.removeEventListener("fullscreenchange",t)}}},[]),Y.useEffect(function(){if(C.current){var e=function(){var e;C.current&&C.current.offsetHeight;l&&console.log("[StormcloudUI] Video event: loadedmetadata, readyState:",null===(e=C.current)||void 0===e?void 0:e.readyState)},t=function(){var e;l&&console.log("[StormcloudUI] Video event: loadeddata, readyState:",null===(e=C.current)||void 0===e?void 0:e.readyState)},r=function(){var e;l&&console.log("[StormcloudUI] Video event: loadstart, readyState:",null===(e=C.current)||void 0===e?void 0:e.readyState)},i=function(){var e;Ee(!1),O.current&&(clearTimeout(O.current),O.current=null),be(!1),l&&console.log("[StormcloudUI] Video event: canplay, readyState:",null===(e=C.current)||void 0===e?void 0:e.readyState,"- clearing loading state, isLoading=false")},n=function(){var e;Ee(!1),O.current&&(clearTimeout(O.current),O.current=null),be(!1),l&&console.log("[StormcloudUI] Video event: canplaythrough, readyState:",null===(e=C.current)||void 0===e?void 0:e.readyState,"- clearing loading state, isLoading=false")},a=function(){var e;O.current&&clearTimeout(O.current),O.current=window.setTimeout(function(){var e;be(!0),l&&console.log("[StormcloudUI] Video buffering detected (after 300ms delay), readyState:",null===(e=C.current)||void 0===e?void 0:e.readyState,"- showing spinner, isBuffering=true")},300),l&&console.log("[StormcloudUI] Video event: waiting, readyState:",null===(e=C.current)||void 0===e?void 0:e.readyState,"- buffering delay started (300ms)")},s=function(){var e;Ee(!1),O.current&&(clearTimeout(O.current),O.current=null),be(!1),Re(!1),l&&console.log("[StormcloudUI] Video event: playing, readyState:",null===(e=C.current)||void 0===e?void 0:e.readyState,"- playback started, isLoading=false, isBuffering=false")},o=function(){var e,t,r,i=(null===(e=M.current)||void 0===e?void 0:e.isShowingAds())||"true"===(null===(r=null===(t=C.current)||void 0===t?void 0:t.dataset)||void 0===r?void 0:r.stormcloudAdPlaying);M.current&&!i?Re(!0):Re(!1)},u=function(){Re(!0)},c=C.current;return c.addEventListener("loadstart",r),c.addEventListener("loadedmetadata",e),c.addEventListener("loadeddata",t),c.addEventListener("canplay",i),c.addEventListener("canplaythrough",n),c.addEventListener("waiting",a),c.addEventListener("playing",s),c.addEventListener("pause",o),c.addEventListener("ended",u),c.paused&&Re(!0),function(){O.current&&(clearTimeout(O.current),O.current=null),c.removeEventListener("loadstart",r),c.removeEventListener("loadedmetadata",e),c.removeEventListener("loadeddata",t),c.removeEventListener("canplay",i),c.removeEventListener("canplaythrough",n),c.removeEventListener("waiting",a),c.removeEventListener("playing",s),c.removeEventListener("pause",o),c.removeEventListener("ended",u)}}},[l]),W.jsxs(W.Fragment,{children:[W.jsx("style",{children:"\n @keyframes spin {\n from {\n transform: rotate(0deg);\n }\n to {\n transform: rotate(360deg);\n }\n }\n \n .stormcloud-loading-hidden .stormcloud-loading-indicator {\n display: none !important;\n }\n \n .stormcloud-video-wrapper:fullscreen {\n border-radius: 0 !important;\n box-shadow: none !important;\n width: 100vw !important;\n height: 100vh !important;\n max-width: 100vw !important;\n max-height: 100vh !important;\n position: fixed !important;\n top: 0 !important;\n left: 0 !important;\n z-index: 999999 !important;\n background: #000 !important;\n display: flex !important;\n align-items: center !important;\n justify-content: center !important;\n }\n \n .stormcloud-video-wrapper:has(*:fullscreen) {\n border-radius: 0 !important;\n box-shadow: none !important;\n width: 100vw !important;\n height: 100vh !important;\n max-width: 100vw !important;\n max-height: 100vh !important;\n position: fixed !important;\n top: 0 !important;\n left: 0 !important;\n z-index: 999999 !important;\n background: #000 !important;\n display: flex !important;\n align-items: center !important;\n justify-content: center !important;\n }\n \n *:fullscreen {\n width: 100vw !important;\n height: 100vh !important;\n max-width: 100vw !important;\n max-height: 100vh !important;\n position: fixed !important;\n top: 0 !important;\n left: 0 !important;\n z-index: 999999 !important;\n background: #000 !important;\n }\n "}),W.jsxs("div",{className:"stormcloud-video-wrapper ".concat(g||""),style:w({display:"flex",alignItems:"center",justifyContent:"center",position:X?"fixed":"relative",top:X?0:void 0,left:X?0:void 0,overflow:"hidden",width:X?"100vw":"100%",height:X?"100vh":"auto",minHeight:X?"100vh":"auto",maxWidth:X?"100vw":"100%",maxHeight:X?"100vh":"none",zIndex:X?999999:void 0,backgroundColor:X?"#000":void 0,borderRadius:X?0:void 0,boxShadow:X?"none":void 0},p),children:[W.jsx("video",w({ref:C,className:m,style:w({display:"block",width:"100%",height:X?"100%":"auto",maxWidth:"100%",maxHeight:X?"100%":"none",objectFit:X?"cover":"contain",backgroundColor:"#000",aspectRatio:X?"unset":void 0},y),controls:V&&T&&!u,playsInline:E,preload:k,poster:S},x,{children:b})),(Te||Se)&&!c&&W.jsx(Wu,{className:"stormcloud-loading-indicator",size:42,color:"white",style:{position:"absolute",top:"calc(50% - 21px)",left:"calc(50% - 21px)",zIndex:20,animation:"spin 1s linear infinite",filter:"drop-shadow(0 3px 6px rgba(0, 0, 0, 0.8))"}}),we&&W.jsxs("div",{style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",zIndex:25,background:"linear-gradient(135deg, rgba(220, 38, 38, 0.95) 0%, rgba(185, 28, 28, 0.9) 100%)",color:"white",padding:"24px 32px",borderRadius:"16px",backdropFilter:"blur(20px)",border:"2px solid rgba(255, 255, 255, 0.2)",boxShadow:"0 20px 60px rgba(0, 0, 0, 0.6), inset 0 2px 0 rgba(255, 255, 255, 0.2)",textAlign:"center",maxWidth:"400px",margin:"0 16px"},children:[W.jsx("div",{style:{fontSize:"20px",fontWeight:"bold",marginBottom:"12px",color:"#ffffff",textShadow:"0 2px 4px rgba(0, 0, 0, 0.5)"},children:"License Key Required"}),W.jsxs("div",{style:{fontSize:"14px",lineHeight:"1.5",color:"rgba(255, 255, 255, 0.9)",textShadow:"0 1px 2px rgba(0, 0, 0, 0.3)"},children:["Please provide a valid license key to use the Stormcloud Video Player.",W.jsx("br",{}),"Contact your administrator for licensing information."]})]}),Le&&!Te&&!Se&&!we&&!U.showAds&&W.jsx("div",{onClick:function(){var e;C.current&&C.current.paused&&(C.current.src||C.current.currentSrc&&""!==C.current.currentSrc||C.current.readyState>=1?(null===(e=C.current.play())||void 0===e||e.catch(function(e){console.error("[StormcloudVideoPlayer] Failed to play:",e)}),Re(!1)):console.warn("[StormcloudVideoPlayer] Cannot play: video has no valid source"))},style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",zIndex:15,cursor:"pointer",background:"linear-gradient(135deg, rgba(0, 0, 0, 0.9) 0%, rgba(20, 20, 20, 0.8) 100%)",borderRadius:"50%",width:"100px",height:"100px",display:"flex",alignItems:"center",justifyContent:"center",backdropFilter:"blur(20px)",border:"3px solid rgba(255, 255, 255, 0.8)",boxShadow:"0 12px 40px rgba(0, 0, 0, 0.8), inset 0 2px 0 rgba(255, 255, 255, 0.3)",transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)"},onMouseEnter:function(e){var t=e.currentTarget;t.style.transform="translate(-50%, -50%)",t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.95) 0%, rgba(40, 40, 40, 0.9) 100%)",t.style.boxShadow="0 16px 48px rgba(0, 0, 0, 0.9), inset 0 2px 0 rgba(255, 255, 255, 0.4)",t.style.borderColor="rgba(255, 255, 255, 0.9)"},onMouseLeave:function(e){var t=e.currentTarget;t.style.transform="translate(-50%, -50%)",t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.9) 0%, rgba(20, 20, 20, 0.8) 100%)",t.style.boxShadow="0 12px 40px rgba(0, 0, 0, 0.8), inset 0 2px 0 rgba(255, 255, 255, 0.3)",t.style.borderColor="rgba(255, 255, 255, 0.8)"},title:"Play",children:W.jsx(qu,{size:36,color:"white",style:{marginLeft:"6px",filter:"drop-shadow(0 2px 4px rgba(0, 0, 0, 0.8))"}})}),Ve&&!we?W.jsx(W.Fragment,{children:W.jsxs("div",{style:{position:"absolute",bottom:0,left:0,right:0,background:"linear-gradient(180deg, transparent 0%, rgba(0, 0, 0, 0.8) 100%)",padding:"20px 16px 16px",zIndex:10},children:[W.jsxs("div",{style:{width:"100%",height:"8px",background:"linear-gradient(90deg, rgba(255, 255, 255, 0.2) 0%, rgba(255, 255, 255, 0.1) 100%)",borderRadius:"8px",marginBottom:"16px",cursor:"pointer",position:"relative",backdropFilter:"blur(5px)",border:"1px solid rgba(255, 255, 255, 0.1)",boxShadow:"inset 0 2px 4px rgba(0, 0, 0, 0.2)"},onClick:function(e){if(C.current&&ne>0&&isFinite(ne)){var t=e.currentTarget.getBoundingClientRect(),r=e.clientX-t.left,i=Math.max(0,Math.min(1,r/t.width))*ne;isFinite(i)&&i>=0&&i<=ne&&(C.current.currentTime=i)}},children:[W.jsx("div",{style:{height:"100%",background:"linear-gradient(90deg, rgba(139, 92, 246, 0.9) 0%, rgba(59, 130, 246, 0.8) 50%, rgba(34, 197, 94, 0.9) 100%)",borderRadius:"8px",width:"".concat(ne>0?te/ne*100:0,"%"),transition:"width 0.2s cubic-bezier(0.4, 0, 0.2, 1)",boxShadow:"0 2px 8px rgba(139, 92, 246, 0.4)"}}),W.jsx("div",{style:{position:"absolute",top:"-6px",right:"".concat(ne>0?100-te/ne*100:100,"%"),width:"20px",height:"20px",background:"linear-gradient(135deg, rgba(255, 255, 255, 0.95) 0%, rgba(240, 240, 240, 0.9) 100%)",borderRadius:"50%",border:"3px solid rgba(139, 92, 246, 0.8)",boxShadow:"0 4px 16px rgba(139, 92, 246, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.8)",transform:"translateX(50%)",transition:"all 0.2s cubic-bezier(0.4, 0, 0.2, 1)"}})]}),W.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",color:"white",flexWrap:xe<768?"wrap":"nowrap",gap:"".concat(8*Fe,"px")},children:[W.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"".concat(12*Fe,"px"),flexWrap:xe<480?"wrap":"nowrap"},children:[W.jsx("button",{onClick:function(){var e;C.current&&(C.current.paused?C.current.src||C.current.currentSrc&&""!==C.current.currentSrc||C.current.readyState>=1?(null===(e=C.current.play())||void 0===e||e.catch(function(e){console.error("[StormcloudVideoPlayer] Failed to play:",e)}),Re(!1)):console.warn("[StormcloudVideoPlayer] Cannot play: video has no valid source"):(C.current.pause(),Re(!0)))},style:{background:"linear-gradient(135deg, rgba(0, 0, 0, 0.75) 0%, rgba(0, 0, 0, 0.65) 100%)",backdropFilter:"blur(12px)",border:"".concat(2*Fe,"px solid rgba(255, 255, 255, 0.3)"),color:"#ffffff",cursor:"pointer",padding:"".concat(10*Fe,"px"),borderRadius:"".concat(16*Fe,"px"),display:"flex",alignItems:"center",justifyContent:"center",transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",boxShadow:"0 8px 32px rgba(0, 0, 0, 0.4), 0 4px 16px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.3)",minWidth:"".concat(48*Fe,"px"),minHeight:"".concat(48*Fe,"px")},onMouseEnter:function(e){var t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.85) 0%, rgba(0, 0, 0, 0.75) 100%)",t.style.boxShadow="0 12px 48px rgba(0, 0, 0, 0.6), 0 6px 24px rgba(0, 0, 0, 0.4), inset 0 2px 0 rgba(255, 255, 255, 0.4)"},onMouseLeave:function(e){var t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.75) 0%, rgba(0, 0, 0, 0.65) 100%)",t.style.boxShadow="0 8px 32px rgba(0, 0, 0, 0.4), 0 4px 16px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.3)"},title:J?"Pause":"Play",children:J?W.jsx(ju,{size:Math.max(16,20*Fe),style:{filter:"drop-shadow(0 0 0 transparent)"}}):W.jsx(qu,{size:Math.max(16,20*Fe),style:{filter:"drop-shadow(0 0 0 transparent)"}})}),W.jsxs("div",{style:{position:"relative",display:"flex",alignItems:"center",padding:"8px",margin:"-8px"},onMouseEnter:function(){return ve(!0)},onMouseLeave:function(){return ve(!1)},children:[W.jsx("button",{onClick:function(){M.current&&M.current.toggleMute(),d&&d()},style:{background:"linear-gradient(135deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.6) 100%)",backdropFilter:"blur(10px)",border:"".concat(2*Fe,"px solid rgba(255, 255, 255, 0.3)"),color:"#ffffff",cursor:"pointer",padding:"".concat(8*Fe,"px"),borderRadius:"".concat(16*Fe,"px"),display:"flex",alignItems:"center",justifyContent:"center",transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",boxShadow:"0 6px 28px rgba(0, 0, 0, 0.4), 0 3px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.25)",minWidth:"".concat(44*Fe,"px"),minHeight:"".concat(44*Fe,"px")},onMouseEnter:function(e){var t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.8) 0%, rgba(0, 0, 0, 0.7) 100%)",t.style.boxShadow="0 10px 36px rgba(0, 0, 0, 0.6), 0 5px 16px rgba(0, 0, 0, 0.4), inset 0 2px 0 rgba(255, 255, 255, 0.35)"},onMouseLeave:function(e){var t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.6) 100%)",t.style.boxShadow="0 6px 28px rgba(0, 0, 0, 0.4), 0 3px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.25)"},title:K?"Unmute":"Mute",children:K||0===oe?W.jsx(zu,{size:Math.max(14,16*Fe),style:{filter:"drop-shadow(0 0 0 transparent)"}}):oe<.5?W.jsx(Yu,{size:Math.max(14,16*Fe),style:{filter:"drop-shadow(0 0 0 transparent)"}}):W.jsx(Xu,{size:Math.max(14,16*Fe),style:{filter:"drop-shadow(0 0 0 transparent)"}})}),fe&&W.jsxs(W.Fragment,{children:[W.jsx("div",{style:{position:"absolute",bottom:"100%",left:"50%",transform:"translateX(-50%)",width:"60px",height:"20px",marginBottom:"-16px",zIndex:9},onMouseEnter:function(){return ve(!0)},onMouseLeave:function(){return ve(!1)}}),W.jsx("div",{style:{position:"absolute",bottom:"100%",left:"50%",transform:"translateX(-50%)",marginBottom:"4px",background:"linear-gradient(135deg, rgba(0, 0, 0, 0.88) 0%, rgba(20, 20, 20, 0.92) 100%)",backdropFilter:"blur(15px)",padding:"10px 14px",borderRadius:"14px",border:"1px solid rgba(255, 255, 255, 0.15)",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"128px",boxShadow:"0 12px 40px rgba(0, 0, 0, 0.5), 0 4px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.15)",zIndex:10,transition:"transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out, border-color 0.2s ease-in-out"},onMouseEnter:function(e){ve(!0),e.currentTarget.style.boxShadow="0 16px 48px rgba(0, 0, 0, 0.6), 0 6px 16px rgba(0, 0, 0, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 0 24px rgba(59, 130, 246, 0.3)",e.currentTarget.style.borderColor="rgba(59, 130, 246, 0.4)"},onMouseLeave:function(e){ve(!1),e.currentTarget.style.boxShadow="0 12px 40px rgba(0, 0, 0, 0.5), 0 4px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.15)",e.currentTarget.style.borderColor="rgba(255, 255, 255, 0.15)"},children:W.jsxs("div",{style:{position:"relative",width:"8px",height:"104px",cursor:"pointer",transition:"transform 0.2s ease-in-out"},onMouseEnter:function(e){},onMouseLeave:function(e){},onMouseDown:function(e){e.preventDefault();var t=e.currentTarget,r=function(e){if(t){var r=t.getBoundingClientRect(),i=e.clientY-r.top,n=1-Math.max(0,Math.min(1,i/r.height));Ne(n)}},i=function(){document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",i)};document.addEventListener("mousemove",r),document.addEventListener("mouseup",i);var n=t.getBoundingClientRect(),a=e.clientY-n.top,s=1-Math.max(0,Math.min(1,a/n.height));Ne(s)},onClick:function(e){e.stopPropagation();var t=e.currentTarget.getBoundingClientRect(),r=e.clientY-t.top,i=1-Math.max(0,Math.min(1,r/t.height));Ne(i)},children:[W.jsx("div",{style:{position:"absolute",bottom:"0",left:"0",width:"100%",height:"100%",background:"linear-gradient(180deg, rgba(255, 255, 255, 0.4) 0%, rgba(255, 255, 255, 0.15) 100%)",borderRadius:"4px",boxShadow:"inset 0 1px 3px rgba(0, 0, 0, 0.2)"}}),W.jsx("div",{style:{position:"absolute",bottom:"0",left:"0",width:"100%",height:"".concat(100*(K?0:oe),"%"),background:"linear-gradient(180deg, rgba(96, 165, 250, 1) 0%, rgba(59, 130, 246, 0.95) 50%, rgba(37, 99, 235, 0.9) 100%)",borderRadius:"4px",transition:"height 0.15s ease-out, box-shadow 0.2s ease-in-out",boxShadow:"0 0 8px rgba(59, 130, 246, 0.5), inset 0 1px 0 rgba(255, 255, 255, 0.3)"}}),W.jsx("div",{style:{position:"absolute",bottom:"calc(".concat(100*(K?0:oe),"% - 7px)"),left:"50%",transform:"translateX(-50%)",width:"14px",height:"14px",background:"linear-gradient(135deg, #ffffff 0%, #f0f9ff 100%)",borderRadius:"50%",boxShadow:"0 2px 6px rgba(0, 0, 0, 0.3), 0 0 0 2px rgba(59, 130, 246, 0.3), 0 0 12px rgba(59, 130, 246, 0.4)",transition:"bottom 0.15s ease-out, transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out, width 0.2s ease-in-out, height 0.2s ease-in-out",cursor:"grab"},onMouseEnter:function(e){e.currentTarget.style.boxShadow="0 3px 10px rgba(0, 0, 0, 0.4), 0 0 0 3px rgba(59, 130, 246, 0.5), 0 0 20px rgba(59, 130, 246, 0.6)",e.currentTarget.style.cursor="grab"},onMouseLeave:function(e){e.currentTarget.style.boxShadow="0 2px 6px rgba(0, 0, 0, 0.3), 0 0 0 2px rgba(59, 130, 246, 0.3), 0 0 12px rgba(59, 130, 246, 0.4)"},onMouseDown:function(e){e.currentTarget.style.cursor="grabbing"},onMouseUp:function(e){e.currentTarget.style.cursor="grab"}})]})})]})]}),W.jsxs("div",{style:{fontSize:"".concat(14*Fe,"px"),fontFamily:"monospace",color:"rgba(255, 255, 255, 0.9)",display:xe<480?"none":"block"},children:[Ue(te)," / ",Ue(ne)]})]}),W.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"".concat(12*Fe,"px")},children:[W.jsxs("div",{style:{position:"relative",display:xe<600?"none":"block"},children:[W.jsxs("button",{onClick:function(){return me(!pe)},style:{background:"linear-gradient(135deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.6) 100%)",backdropFilter:"blur(10px)",border:"".concat(2*Fe,"px solid rgba(255, 255, 255, 0.3)"),color:"#ffffff",cursor:"pointer",padding:"".concat(8*Fe,"px ").concat(14*Fe,"px"),borderRadius:"".concat(14*Fe,"px"),fontSize:"".concat(14*Fe,"px"),fontFamily:"monospace",fontWeight:"700",transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",boxShadow:"0 6px 24px rgba(0, 0, 0, 0.4), 0 3px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.25)",minWidth:"".concat(56*Fe,"px"),minHeight:"".concat(40*Fe,"px")},onMouseEnter:function(e){var t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.8) 0%, rgba(0, 0, 0, 0.7) 100%)",t.style.boxShadow="0 10px 32px rgba(0, 0, 0, 0.6), 0 5px 16px rgba(0, 0, 0, 0.4), inset 0 2px 0 rgba(255, 255, 255, 0.35)"},onMouseLeave:function(e){var t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.6) 100%)",t.style.boxShadow="0 6px 24px rgba(0, 0, 0, 0.4), 0 3px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.25)"},title:"Playback Speed",children:[ce,"x"]}),pe&&W.jsx("div",{style:{position:"absolute",bottom:"100%",right:0,marginBottom:"12px",background:"linear-gradient(135deg, rgba(0, 0, 0, 0.9) 0%, rgba(20, 20, 20, 0.95) 100%)",backdropFilter:"blur(20px)",borderRadius:"12px",border:"1px solid rgba(255, 255, 255, 0.1)",overflow:"hidden",minWidth:"90px",boxShadow:"0 16px 48px rgba(0, 0, 0, 0.5), inset 0 1px 0 rgba(255, 255, 255, 0.1)"},children:[.25,.5,.75,1,1.25,1.5,1.75,2].map(function(e){return W.jsxs("button",{onClick:function(){return t=e,C.current&&isFinite(t)&&t>0&&(C.current.playbackRate=t),void me(!1);var t},style:{display:"block",width:"100%",padding:"10px 16px",background:ce===e?"linear-gradient(135deg, rgba(99, 102, 241, 0.8) 0%, rgba(139, 92, 246, 0.6) 100%)":"transparent",border:"none",color:"white",cursor:"pointer",fontSize:"13px",fontFamily:"monospace",fontWeight:"600",textAlign:"center",transition:"all 0.2s cubic-bezier(0.4, 0, 0.2, 1)",borderBottom:2!==e?"1px solid rgba(255, 255, 255, 0.05)":"none"},onMouseEnter:function(t){ce!==e&&(t.target.style.background="linear-gradient(135deg, rgba(255, 255, 255, 0.15) 0%, rgba(255, 255, 255, 0.05) 100%)")},onMouseLeave:function(t){ce!==e&&(t.target.style.background="transparent")},children:[e,"x"]},e)})})]}),W.jsx("button",{onClick:function(){h?h():M.current&&M.current.toggleFullscreen().catch(function(e){console.error("Fullscreen error:",e)})},style:{background:"linear-gradient(135deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.6) 100%)",backdropFilter:"blur(10px)",border:"".concat(2*Fe,"px solid rgba(255, 255, 255, 0.3)"),color:"#ffffff",cursor:"pointer",padding:"".concat(8*Fe,"px"),borderRadius:"".concat(16*Fe,"px"),display:"flex",alignItems:"center",justifyContent:"center",transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",boxShadow:"0 6px 28px rgba(0, 0, 0, 0.4), 0 3px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.25)",minWidth:"".concat(44*Fe,"px"),minHeight:"".concat(44*Fe,"px")},onMouseEnter:function(e){var t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.8) 0%, rgba(0, 0, 0, 0.7) 100%)",t.style.boxShadow="0 10px 36px rgba(0, 0, 0, 0.6), 0 5px 16px rgba(0, 0, 0, 0.4), inset 0 2px 0 rgba(255, 255, 255, 0.35)"},onMouseLeave:function(e){var t=e.target;t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.6) 100%)",t.style.boxShadow="0 6px 28px rgba(0, 0, 0, 0.4), 0 3px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.25)"},title:X?"Exit Fullscreen":"Enter Fullscreen",children:X?W.jsx(Hu,{size:Math.max(14,16*Fe),style:{filter:"drop-shadow(0 0 0 transparent)"}}):W.jsx(Ku,{size:Math.max(14,16*Fe),style:{filter:"drop-shadow(0 0 0 transparent)"}})})]})]})]})}):u&&!we&&W.jsxs("div",{style:{position:"absolute",bottom:"".concat(10*Fe,"px"),right:"".concat(10*Fe,"px"),transform:"none",display:"flex",flexDirection:Me?"column":"row",gap:"".concat(10*Fe,"px"),zIndex:10},children:[W.jsxs("div",{style:{position:"relative",display:"flex",alignItems:"center",padding:"8px",margin:"-8px"},onMouseEnter:function(){return ve(!0)},onMouseLeave:function(){return ve(!1)},children:[W.jsx("button",{onClick:function(){M.current&&M.current.toggleMute(),d&&d()},onMouseEnter:function(e){var t=e.currentTarget;t.style.boxShadow="0 14px 48px rgba(0, 0, 0, 0.7), 0 0 0 3px rgba(255, 255, 255, 0.8), inset 0 2px 0 rgba(255, 255, 255, 0.4)",t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.85) 0%, rgba(0, 0, 0, 0.75) 100%)"},onMouseLeave:function(e){var t=e.currentTarget;t.style.boxShadow="0 10px 36px rgba(0, 0, 0, 0.6), 0 0 0 2px rgba(255, 255, 255, 0.7), inset 0 1px 0 rgba(255, 255, 255, 0.3)",t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.75) 0%, rgba(0, 0, 0, 0.65) 100%)"},style:{background:"linear-gradient(135deg, rgba(0, 0, 0, 0.75) 0%, rgba(0, 0, 0, 0.65) 100%)",color:"#ffffff",border:"none",borderRadius:"".concat(18*Fe,"px"),padding:"".concat(8*Fe,"px"),cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",backdropFilter:"blur(20px)",boxShadow:"0 10px 36px rgba(0, 0, 0, 0.6), 0 0 0 2px rgba(255, 255, 255, 0.7), inset 0 1px 0 rgba(255, 255, 255, 0.3)",transition:"all 0.4s cubic-bezier(0.4, 0, 0.2, 1)",minWidth:"".concat(46*Fe,"px"),minHeight:"".concat(46*Fe,"px")},title:K?"Unmute":"Mute",children:K||0===oe?W.jsx(zu,{size:Math.max(14,16*Fe),style:{filter:"drop-shadow(0 2px 4px rgba(0, 0, 0, 0.8))",color:"#ffffff"}}):oe<.5?W.jsx(Yu,{size:Math.max(14,16*Fe),style:{filter:"drop-shadow(0 2px 4px rgba(0, 0, 0, 0.8))",color:"#ffffff"}}):W.jsx(Xu,{size:Math.max(14,16*Fe),style:{filter:"drop-shadow(0 2px 4px rgba(0, 0, 0, 0.8))",color:"#ffffff"}})}),fe&&W.jsxs(W.Fragment,{children:[W.jsx("div",{style:{position:"absolute",bottom:"100%",left:"50%",transform:"translateX(-50%)",width:"60px",height:"20px",marginBottom:"-16px",zIndex:9},onMouseEnter:function(){return ve(!0)},onMouseLeave:function(){return ve(!1)}}),W.jsx("div",{style:{position:"absolute",bottom:"100%",left:"50%",transform:"translateX(-50%)",marginBottom:"4px",background:"linear-gradient(135deg, rgba(0, 0, 0, 0.96) 0%, rgba(20, 20, 20, 0.92) 100%)",backdropFilter:"blur(20px)",padding:"10px 14px",borderRadius:"14px",border:"2px solid rgba(255, 255, 255, 0.7)",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"128px",boxShadow:"0 12px 40px rgba(0, 0, 0, 0.85), 0 4px 12px rgba(0, 0, 0, 0.6), inset 0 1px 0 rgba(255, 255, 255, 0.35)",zIndex:10,transition:"transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out, border-color 0.2s ease-in-out"},onMouseEnter:function(e){ve(!0),e.currentTarget.style.boxShadow="0 16px 48px rgba(0, 0, 0, 0.9), 0 6px 16px rgba(0, 0, 0, 0.7), inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 0 24px rgba(96, 165, 250, 0.4)",e.currentTarget.style.borderColor="rgba(96, 165, 250, 0.8)"},onMouseLeave:function(e){ve(!1),e.currentTarget.style.boxShadow="0 12px 40px rgba(0, 0, 0, 0.85), 0 4px 12px rgba(0, 0, 0, 0.6), inset 0 1px 0 rgba(255, 255, 255, 0.35)",e.currentTarget.style.borderColor="rgba(255, 255, 255, 0.7)"},children:W.jsxs("div",{style:{position:"relative",width:"8px",height:"104px",cursor:"pointer",transition:"transform 0.2s ease-in-out"},onMouseDown:function(e){e.preventDefault();var t=e.currentTarget,r=function(e){if(t){var r=t.getBoundingClientRect(),i=e.clientY-r.top,n=1-Math.max(0,Math.min(1,i/r.height));Ne(n)}},i=function(){document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",i)};document.addEventListener("mousemove",r),document.addEventListener("mouseup",i);var n=t.getBoundingClientRect(),a=e.clientY-n.top,s=1-Math.max(0,Math.min(1,a/n.height));Ne(s)},onClick:function(e){e.stopPropagation();var t=e.currentTarget.getBoundingClientRect(),r=e.clientY-t.top,i=1-Math.max(0,Math.min(1,r/t.height));Ne(i)},children:[W.jsx("div",{style:{position:"absolute",bottom:"0",left:"0",width:"100%",height:"100%",background:"linear-gradient(180deg, rgba(255, 255, 255, 0.85) 0%, rgba(255, 255, 255, 0.5) 100%)",borderRadius:"4px",border:"1px solid rgba(255, 255, 255, 0.4)",boxShadow:"inset 0 1px 3px rgba(0, 0, 0, 0.3)"}}),W.jsx("div",{style:{position:"absolute",bottom:"0",left:"0",width:"100%",height:"".concat(100*(K?0:oe),"%"),background:"linear-gradient(180deg, rgba(125, 211, 252, 1) 0%, rgba(96, 165, 250, 0.98) 50%, rgba(59, 130, 246, 0.95) 100%)",borderRadius:"4px",transition:"height 0.15s ease-out, box-shadow 0.2s ease-in-out",boxShadow:"0 0 12px rgba(96, 165, 250, 0.6), inset 0 1px 0 rgba(255, 255, 255, 0.4)"}}),W.jsx("div",{style:{position:"absolute",bottom:"calc(".concat(100*(K?0:oe),"% - 8px)"),left:"50%",transform:"translateX(-50%)",width:"16px",height:"16px",background:"linear-gradient(135deg, #ffffff 0%, #f0f9ff 100%)",borderRadius:"50%",border:"2px solid rgba(96, 165, 250, 0.9)",boxShadow:"0 3px 8px rgba(0, 0, 0, 0.5), 0 0 0 2px rgba(96, 165, 250, 0.4), 0 0 16px rgba(96, 165, 250, 0.5)",transition:"bottom 0.15s ease-out, transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out, width 0.2s ease-in-out, height 0.2s ease-in-out",cursor:"grab"},onMouseEnter:function(e){e.currentTarget.style.boxShadow="0 4px 12px rgba(0, 0, 0, 0.6), 0 0 0 3px rgba(96, 165, 250, 0.6), 0 0 24px rgba(96, 165, 250, 0.7)",e.currentTarget.style.cursor="grab"},onMouseLeave:function(e){e.currentTarget.style.boxShadow="0 3px 8px rgba(0, 0, 0, 0.5), 0 0 0 2px rgba(96, 165, 250, 0.4), 0 0 16px rgba(96, 165, 250, 0.5)"},onMouseDown:function(e){e.currentTarget.style.cursor="grabbing"},onMouseUp:function(e){e.currentTarget.style.cursor="grab"}})]})})]})]}),W.jsx("button",{onClick:function(){h?h():M.current&&M.current.toggleFullscreen().catch(function(e){console.error("Fullscreen error:",e)})},onMouseEnter:function(e){var t=e.currentTarget;t.style.boxShadow="0 14px 48px rgba(0, 0, 0, 0.7), 0 0 0 3px rgba(255, 255, 255, 0.8), inset 0 2px 0 rgba(255, 255, 255, 0.4)",t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.85) 0%, rgba(0, 0, 0, 0.75) 100%)"},onMouseLeave:function(e){var t=e.currentTarget;t.style.boxShadow="0 10px 36px rgba(0, 0, 0, 0.6), 0 0 0 2px rgba(255, 255, 255, 0.7), inset 0 1px 0 rgba(255, 255, 255, 0.3)",t.style.background="linear-gradient(135deg, rgba(0, 0, 0, 0.75) 0%, rgba(0, 0, 0, 0.65) 100%)"},style:{background:"linear-gradient(135deg, rgba(0, 0, 0, 0.75) 0%, rgba(0, 0, 0, 0.65) 100%)",color:"#ffffff",border:"none",borderRadius:"".concat(18*Fe,"px"),padding:"".concat(8*Fe,"px"),cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",backdropFilter:"blur(20px)",boxShadow:"0 10px 36px rgba(0, 0, 0, 0.6), 0 0 0 2px rgba(255, 255, 255, 0.7), inset 0 1px 0 rgba(255, 255, 255, 0.3)",transition:"all 0.4s cubic-bezier(0.4, 0, 0.2, 1)",minWidth:"".concat(46*Fe,"px"),minHeight:"".concat(46*Fe,"px")},title:X?"Exit Fullscreen":"Enter Fullscreen",children:X?W.jsx(Hu,{size:Math.max(14,16*Fe),style:{filter:"drop-shadow(0 2px 4px rgba(0, 0, 0, 0.8))",color:"#ffffff"}}):W.jsx(Ku,{size:Math.max(14,16*Fe),style:{filter:"drop-shadow(0 2px 4px rgba(0, 0, 0, 0.8))",color:"#ffffff"}})})]}),f&&W.jsx("div",{onClick:f,style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:1,cursor:"pointer"}})]})]})},function(e,t){var r,i,n,a,s,o;try{for(var l=C(Qu),u=l.next();!u.done;u=l.next()){if(e[v=u.value]!==t[v])return!1}}catch(e){r={error:e}}finally{try{u&&!u.done&&(i=l.return)&&i.call(l)}finally{if(r)throw r.error}}try{for(var c=C(["autoplay","muted","controls","showCustomControls","className","style","wrapperClassName","wrapperStyle","playsInline","preload","poster","children"]),d=c.next();!d.done;d=c.next()){if(e[v=d.value]!==t[v])return!1}}catch(e){n={error:e}}finally{try{d&&!d.done&&(a=c.return)&&a.call(c)}finally{if(n)throw n.error}}try{for(var h=C(["onReady","onVolumeToggle","onFullscreenToggle","onControlClick"]),f=h.next();!f.done;f=h.next()){var v;if(e[v=f.value]!==t[v])return!1}}catch(e){s={error:e}}finally{try{f&&!f.done&&(o=h.return)&&o.call(h)}finally{if(s)throw s.error}}return!0}),Ju=function(){},Zu={playing:!1,loop:!1,controls:!0,volume:1,muted:!1,playbackRate:1,width:"100%",height:"auto",style:{},progressInterval:1e3,playsInline:!1,autoplay:!1,preload:"metadata",poster:"",className:"",wrapperClassName:"",wrapperStyle:{},allowNativeHls:!1,lowLatencyMode:!1,driftToleranceMs:1e3,immediateManifestAds:!0,debugAdTiming:!1,showCustomControls:!1,hideLoadingIndicator:!1,licenseKey:"",adFailsafeTimeoutMs:1e4,minSegmentsBeforePlay:2,onStart:Ju,onPlay:Ju,onPause:Ju,onBuffer:Ju,onBufferEnd:Ju,onEnded:Ju,onError:Ju,onDuration:Ju,onSeek:Ju,onProgress:Ju,onVolumeToggle:Ju,onFullscreenToggle:Ju,onControlClick:Ju},ec=Y.lazy,tc=function(e,t){var r=w({},e);return t.forEach(function(e){delete r[e]}),r},rc=function(e){return"undefined"!=typeof window&&window.MediaStream&&e instanceof window.MediaStream},ic=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(nc(e)&&nc(a))for(var s in a)nc(a[s])?(e[s]||Object.assign(e,((t={})[s]={},t)),ic(e[s],a[s])):Object.assign(e,((r={})[s]=a[s],r));return ic.apply(void 0,M([e],_(i),!1))},nc=function(e){return e&&"object"===S(e)&&!Array.isArray(e)},ac="undefined"!=typeof window&&window.document,sc="undefined"!=typeof globalThis&&globalThis.window&&globalThis.window.document,oc=ac&&/iPad|iPhone|iPod/.test(navigator.userAgent),lc=ac&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent),uc=/\.(m3u8)($|\?)/i,cc=/\/hls\//i,dc=/\.(mpd)($|\?)/i,hc=/\.(mp4|webm|ogg|avi|mov|wmv|flv|mkv)($|\?)/i,fc=/\.(mp3|wav|ogg|aac|wma|flac|m4a)($|\?)/i,vc={hls:function(e){return!(!e||"string"!=typeof e)&&(uc.test(e)||cc.test(e))},dash:function(e){return!(!e||"string"!=typeof e)&&dc.test(e)},video:function(e){return!(!e||"string"!=typeof e)&&hc.test(e)},audio:function(e){return!(!e||"string"!=typeof e)&&fc.test(e)},file:function(e){return!(!e||"string"!=typeof e)&&(hc.test(e)||fc.test(e))}},gc=function(e){function t(){var t=e.apply(this,M([],_(arguments),!1))||this;return t.player=null,t.mounted=!1,t.load=function(){return D(t,void 0,void 0,function(){var e,t,r,i,n,a,s,o;return x(this,function(l){switch(l.label){case 0:if(!this.props.videoElement||!this.props.src)return[2];l.label=1;case 1:return l.trys.push([1,3,,4]),this.player&&(this.player.destroy(),this.player=null),e={src:this.props.src,videoElement:this.props.videoElement},void 0!==this.props.autoplay&&(e.autoplay=this.props.autoplay),void 0!==this.props.muted&&(e.muted=this.props.muted),void 0!==this.props.lowLatencyMode&&(e.lowLatencyMode=this.props.lowLatencyMode),void 0!==this.props.allowNativeHls&&(e.allowNativeHls=this.props.allowNativeHls),void 0!==this.props.driftToleranceMs&&(e.driftToleranceMs=this.props.driftToleranceMs),void 0!==this.props.immediateManifestAds&&(e.immediateManifestAds=this.props.immediateManifestAds),void 0!==this.props.debugAdTiming&&(e.debugAdTiming=this.props.debugAdTiming),void 0!==this.props.showCustomControls&&(e.showCustomControls=this.props.showCustomControls),void 0!==this.props.onVolumeToggle&&(e.onVolumeToggle=this.props.onVolumeToggle),void 0!==this.props.onFullscreenToggle&&(e.onFullscreenToggle=this.props.onFullscreenToggle),void 0!==this.props.onControlClick&&(e.onControlClick=this.props.onControlClick),void 0!==this.props.licenseKey&&(e.licenseKey=this.props.licenseKey),void 0!==this.props.adFailsafeTimeoutMs&&(e.adFailsafeTimeoutMs=this.props.adFailsafeTimeoutMs),void 0!==this.props.minSegmentsBeforePlay&&(e.minSegmentsBeforePlay=this.props.minSegmentsBeforePlay),this.player=new Du(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 I(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=vc.hls,t}(Y.Component),pc=function(e){function t(){var t=e.apply(this,M([],_(arguments),!1))||this;return t.mounted=!1,t.ready=!1,t.load=function(){var e,r;if(t.props.videoElement&&t.props.src){var i=t.props.videoElement,n=function(){var e,r;t.mounted&&!t.ready&&(t.ready=!0,null===(r=(e=t.props).onReady)||void 0===r||r.call(e))},a=function(){var e,r;t.mounted&&(null===(r=(e=t.props).onPlay)||void 0===r||r.call(e))},s=function(){var e,r;t.mounted&&(null===(r=(e=t.props).onPause)||void 0===r||r.call(e))},o=function(){var e,r;t.mounted&&(null===(r=(e=t.props).onEnded)||void 0===r||r.call(e))},l=function(e){var r,i;t.mounted&&(null===(i=(r=t.props).onError)||void 0===i||i.call(r,e))},u=function(){var e,r;t.mounted&&(null===(r=(e=t.props).onLoaded)||void 0===r||r.call(e))};return i.addEventListener("loadedmetadata",n),i.addEventListener("play",a),i.addEventListener("pause",s),i.addEventListener("ended",o),i.addEventListener("error",l),i.addEventListener("loadeddata",u),i.src=t.props.src,void 0!==t.props.autoplay&&(i.autoplay=t.props.autoplay),void 0!==t.props.muted&&(i.muted=t.props.muted),void 0!==t.props.loop&&(i.loop=t.props.loop),void 0!==t.props.controls&&(i.controls=t.props.controls),void 0!==t.props.playsInline&&(i.playsInline=t.props.playsInline),void 0!==t.props.preload&&(i.preload=t.props.preload),void 0!==t.props.poster&&(i.poster=t.props.poster),null===(r=(e=t.props).onMount)||void 0===r||r.call(e,t),function(){i.removeEventListener("loadedmetadata",n),i.removeEventListener("play",a),i.removeEventListener("pause",s),i.removeEventListener("ended",o),i.removeEventListener("error",l),i.removeEventListener("loadeddata",u)}}},t.play=function(){var e;if(t.props.videoElement){var r=t.props.videoElement;r.src||r.currentSrc&&""!==r.currentSrc||r.readyState>=1?null===(e=r.play())||void 0===e||e.catch(function(e){var r,i;console.error("[FilePlayer] Failed to play:",e),null===(i=(r=t.props).onError)||void 0===i||i.call(r,e)}):console.warn("[FilePlayer] Cannot play: video has no valid source")}},t.pause=function(){t.props.videoElement&&t.props.videoElement.pause()},t.stop=function(){t.pause(),t.props.videoElement&&(t.props.videoElement.currentTime=0)},t.seekTo=function(e,r){t.props.videoElement&&(t.props.videoElement.currentTime=e,r||t.pause())},t.setVolume=function(e){t.props.videoElement&&(t.props.videoElement.volume=Math.max(0,Math.min(1,e)))},t.mute=function(){t.props.videoElement&&(t.props.videoElement.muted=!0)},t.unmute=function(){t.props.videoElement&&(t.props.videoElement.muted=!1)},t.setPlaybackRate=function(e){t.props.videoElement&&e>0&&(t.props.videoElement.playbackRate=e)},t.setLoop=function(e){t.props.videoElement&&(t.props.videoElement.loop=e)},t.getDuration=function(){return t.props.videoElement&&isFinite(t.props.videoElement.duration)?t.props.videoElement.duration:null},t.getCurrentTime=function(){return t.props.videoElement&&isFinite(t.props.videoElement.currentTime)?t.props.videoElement.currentTime:null},t.getSecondsLoaded=function(){return t.props.videoElement&&t.props.videoElement.buffered.length>0?t.props.videoElement.buffered.end(t.props.videoElement.buffered.length-1):null},t.getInternalPlayer=function(e){return void 0===e&&(e="player"),"video"===e?t.props.videoElement:null},t.enablePIP=function(){return D(t,void 0,void 0,function(){var e;return x(this,function(t){switch(t.label){case 0:if(!this.props.videoElement||!("requestPictureInPicture"in this.props.videoElement))return[3,4];t.label=1;case 1:return t.trys.push([1,3,,4]),[4,this.props.videoElement.requestPictureInPicture()];case 2:return t.sent(),[3,4];case 3:return e=t.sent(),console.warn("Picture-in-Picture failed:",e),[3,4];case 4:return[2]}})})},t.disablePIP=function(){return D(t,void 0,void 0,function(){var e;return x(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 I(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=vc.file,t}(Y.Component),mc=[{key:"hls",name:"HLS Player",canPlay:vc.hls,lazyPlayer:ec(function(){return Promise.resolve({default:gc})})},{key:"file",name:"File Player",canPlay:vc.file,canEnablePIP:function(e){return vc.file(e)&&(document.pictureInPictureEnabled||"function"==typeof document.webkitSupportsPresentationMode)},lazyPlayer:ec(function(){return Promise.resolve({default:pc})})}],yc=function(e){function t(){var t=e.apply(this,M([],_(arguments),!1))||this;return t.mounted=!1,t.isReady=!1,t.isPlaying=!1,t.isLoading=!0,t.loadOnReady=null,t.startOnPlay=!0,t.seekOnPlay=null,t.onDurationCalled=!1,t.handlePlayerMount=function(e){t.player||(t.player=e,t.player.load(t.props.src)),t.progress()},t.getInternalPlayer=function(e){return t.player?t.player.getInternalPlayer(e):null},t.progress=function(){var e,r;if(t.props.src&&t.player&&t.isReady){var i=t.getCurrentTime()||0,n=t.getSecondsLoaded(),a=t.getDuration();if(a){var s={playedSeconds:i,played:i/a,loaded:0,loadedSeconds:0};null!==n&&(s.loadedSeconds=n,s.loaded=n/a),s.playedSeconds===t.prevPlayed&&s.loadedSeconds===t.prevLoaded||null===(r=(e=t.props).onProgress)||void 0===r||r.call(e,s),t.prevPlayed=s.playedSeconds,t.prevLoaded=s.loadedSeconds}}t.progressTimeout=window.setTimeout(t.progress,t.props.progressInterval||1e3)},t.handleReady=function(){if(t.mounted){t.isReady=!0,t.isLoading=!1;var e=t.props,r=e.onReady,i=e.playing,n=e.volume,a=e.muted;r(),a||null===n||t.player.setVolume(n),t.loadOnReady?(t.player.load(t.loadOnReady,!0),t.loadOnReady=null):i&&t.player.play(),t.handleDurationCheck()}},t.handlePlay=function(){t.isPlaying=!0,t.isLoading=!1;var e=t.props,r=e.onStart,i=e.onPlay,n=e.playbackRate;t.startOnPlay&&(t.player.setPlaybackRate&&1!==n&&t.player.setPlaybackRate(n),null==r||r(),t.startOnPlay=!1),null==i||i(),t.seekOnPlay&&(t.seekTo(t.seekOnPlay),t.seekOnPlay=null),t.handleDurationCheck()},t.handlePause=function(e){var r,i;t.isPlaying=!1,t.isLoading||null===(i=(r=t.props).onPause)||void 0===i||i.call(r,e)},t.handleEnded=function(){var e=t.props,r=e.activePlayer,i=e.loop,n=e.onEnded;r.loopOnEnded&&i&&t.seekTo(0),i||(t.isPlaying=!1,null==n||n())},t.handleError=function(){for(var e,r,i=[],n=0;n<arguments.length;n++)i[n]=arguments[n];t.isLoading=!1,null===(r=(e=t.props).onError)||void 0===r||r.call(e,i[0],i[1],i[2],i[3])},t.handleDurationCheck=function(){var e,r;clearTimeout(t.durationCheckTimeout);var i=t.getDuration();i?t.onDurationCalled||(null===(r=(e=t.props).onDuration)||void 0===r||r.call(e,i),t.onDurationCalled=!0):t.durationCheckTimeout=window.setTimeout(t.handleDurationCheck,100)},t.handleLoaded=function(){t.isLoading=!1},t}return I(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&&!rc(i))return console.warn("StormcloudPlayer: the attempt to load ".concat(i," is being deferred until the player has loaded")),void(this.loadOnReady=i||null);this.isLoading=!0,this.startOnPlay=!0,this.onDurationCalled=!1,this.player.load(i,this.isReady)}e.playing||!n||this.isPlaying||this.player.play(),e.playing&&!n&&this.isPlaying&&this.player.pause(),e.volume!==a&&null!==a&&this.player.setVolume(a),e.muted!==s&&(s?this.player.mute():(this.player.unmute(),null!==a&&setTimeout(function(){return t.player.setVolume(a)}))),e.playbackRate!==o&&this.player.setPlaybackRate&&this.player.setPlaybackRate(o),e.loop!==l&&this.player.setLoop&&this.player.setLoop(l)}},t.prototype.getDuration=function(){return this.isReady?this.player.getDuration():null},t.prototype.getCurrentTime=function(){return this.isReady?this.player.getCurrentTime():null},t.prototype.getSecondsLoaded=function(){return this.isReady?this.player.getSecondsLoaded():null},t.prototype.seekTo=function(e,t,r){var i=this;if(this.isReady){if(t?"fraction"===t:e>0&&e<1){var n=this.player.getDuration();return n?void this.player.seekTo(n*e,r):void console.warn("StormcloudPlayer: could not seek using fraction – duration not yet available")}this.player.seekTo(e,r)}else 0!==e&&(this.seekOnPlay=e,setTimeout(function(){i.seekOnPlay=null},5e3))},t.prototype.render=function(){var e=this.props.activePlayer;return e?z.createElement(e,w(w({},this.props),{onMount:this.handlePlayerMount,onReady:this.handleReady,onPlay:this.handlePlay,onPause:this.handlePause,onEnded:this.handleEnded,onLoaded:this.handleLoaded,onError:this.handleError})):null},t.displayName="Player",t.defaultProps=Zu,t}(Y.Component),Tc="undefined"!=typeof window&&window.document,Ec="undefined"!=typeof globalThis&&globalThis.window&&globalThis.window.document,kc=Tc||Ec?Y.Suspense:function(){return null},Sc=["src","playing","loop","controls","volume","muted","playbackRate","width","height","style","progressInterval","playsInline","autoplay","preload","poster","className","wrapperClassName","wrapperStyle","allowNativeHls","lowLatencyMode","driftToleranceMs","immediateManifestAds","debugAdTiming","showCustomControls","licenseKey","adFailsafeTimeoutMs","minSegmentsBeforePlay","onReady","onStart","onPlay","onPause","onBuffer","onBufferEnd","onEnded","onError","onDuration","onSeek","onProgress","onVolumeToggle","onFullscreenToggle","onControlClick"],bc=[],Ac=function(e,t){var r;return r=function(r){function i(){var i=r.apply(this,M([],_(arguments),!1))||this;return i.state={showPreview:!1},i.references={wrapper:function(e){i.wrapper=e},player:function(e){i.player=e}},i.getActivePlayer=function(r){var i,n;if(!r)return null;try{for(var a=C(M(M([],_(bc),!1),_(e),!1)),s=a.next();!s.done;s=a.next()){var o=s.value;if(o.canPlay(r))return o}}catch(e){i={error:e}}finally{try{s&&!s.done&&(n=a.return)&&n.call(a)}finally{if(i)throw i.error}}return t||null},i.getAttributes=function(e){return tc(i.props,Sc)},i.handleReady=function(){var e,t;null===(t=(e=i.props).onReady)||void 0===t||t.call(e,i)},i.seekTo=function(e,t,r){if(!i.player)return null;i.player.seekTo(e,t,r)},i.getCurrentTime=function(){return i.player?i.player.getCurrentTime():null},i.getSecondsLoaded=function(){return i.player?i.player.getSecondsLoaded():null},i.getDuration=function(){return i.player?i.player.getDuration():null},i.getInternalPlayer=function(e){return void 0===e&&(e="player"),i.player?i.player.getInternalPlayer(e):null},i.renderActivePlayer=function(e){if(!e)return null;var t=i.getActivePlayer(e);return t?z.createElement(yc,w(w({},i.props),{key:t.key,ref:i.references.player,activePlayer:t.lazyPlayer||t,onReady:i.handleReady})):null},i}return I(i,r),i.prototype.render=function(){var e=this.props,t=e.src,r=e.style,i=e.width,n=e.height,a=e.fallback,s=e.wrapper,o=this.getAttributes(t),l="string"==typeof s?this.references.wrapper:void 0;return z.createElement(s,w({ref:l,style:w(w({},r),{width:i,height:n})},o),z.createElement(kc,{fallback:a},this.renderActivePlayer(t)))},i}(Y.Component),r.displayName="StormcloudPlayer",r.defaultProps=w(w({},Zu),{fallback:null,wrapper:"div"}),r.addCustomPlayer=function(e){bc.push(e)},r.removeCustomPlayers=function(){bc.length=0},r.canPlay=function(t){var r,i;try{for(var n=C(M(M([],_(bc),!1),_(e),!1)),a=n.next();!a.done;a=n.next()){if(a.value.canPlay(t))return!0}}catch(e){r={error:e}}finally{try{a&&!a.done&&(i=n.return)&&i.call(n)}finally{if(r)throw r.error}}return!1},r.canEnablePIP=function(t){var r,i;try{for(var n=C(M(M([],_(bc),!1),_(e),!1)),a=n.next();!a.done;a=n.next()){var s=a.value;if(s.canEnablePIP&&s.canEnablePIP(t))return!0}}catch(e){r={error:e}}finally{try{a&&!a.done&&(i=n.return)&&i.call(n)}finally{if(r)throw r.error}}return!1},r},Lc=Ac(mc,mc[mc.length-1]);e.IS_BROWSER=ac,e.IS_GLOBAL=sc,e.IS_IOS=oc,e.IS_SAFARI=lc,e.SUPPORTS_DASH=function(){if(!ac)return!1;var e=document.createElement("video");return Boolean(e.canPlayType("application/dash+xml"))},e.SUPPORTS_HLS=function(){if(!ac)return!1;var e=document.createElement("video");return Boolean(e.canPlayType("application/vnd.apple.mpegurl"))},e.StormcloudPlayer=Lc,e.StormcloudVideoPlayer=Du,e.StormcloudVideoPlayerComponent=$u,e.canPlay=vc,e.createHlsAdPlayer=bu,e.createImaController=Su,e.createStormcloudPlayer=Ac,e.default=$u,e.detectBrowser=yu,e.getBrowserConfigOverrides=ku,e.getBrowserID=Ru,e.getClientInfo=Lu,e.getRecommendedAdPlayer=function(){return yu().recommendedAdPlayer},e.initializePolyfills=Pu,e.isMediaStream=rc,e.lazy=ec,e.logBrowserInfo=Eu,e.merge=ic,e.omit=tc,e.parseQuery=function(e){var t={},r=e.split("?")[1]||"";if(!r)return t;var i=function(e){e.split("&").forEach(function(e){var r=_(e.split("="),2),i=r[0],n=r[1];if(i)try{t[decodeURIComponent(i)]=n?decodeURIComponent(n.replace(/\+/g," ")):""}catch(e){t[i]=n||""}})};if("undefined"!=typeof URLSearchParams)try{return new URLSearchParams(r).forEach(function(e,r){t[r]=e}),t}catch(e){i(r)}else i(r);return t},e.players=mc,e.randomString=function(){return Math.random().toString(36).substr(2,9)},e.sendHeartbeat=wu,e.sendInitialTracking=Iu,e.supportsFeature=function(e){switch(e){case"ima":return Tu();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.supportsGoogleIMA=Tu,e.supportsModernJS=function(){try{return"undefined"!=typeof Promise&&"undefined"!=typeof Map&&"undefined"!=typeof Set&&void 0!==Array.from&&void 0!==Object.assign&&void 0!==Array.prototype.forEach&&void 0!==String.prototype.includes}catch(e){return!1}},e.supportsWebKitPresentationMode=function(){return"undefined"!=typeof window&&"webkitSupportsPresentationMode"in document.createElement("video")},Object.defineProperty(e,"__esModule",{value:!0})});
|