hx-player 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2 @@
1
+ function _OverloadYield(e,t){this.v=e,this.k=t}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _arrayWithHoles(e){if(Array.isArray(e))return e}function _arrayWithoutHoles(e){if(Array.isArray(e))return _arrayLikeToArray(e)}function _assertThisInitialized(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function _asyncGeneratorDelegate(e){var t={},r=!1;function n(t,n){return r=!0,n=new Promise(function(r){r(e[t](n))}),{done:!1,value:new _OverloadYield(n,1)}}return t["undefined"!=typeof Symbol&&Symbol.iterator||"@@iterator"]=function(){return this},t.next=function(e){return r?(r=!1,e):n("next",e)},"function"==typeof e.throw&&(t.throw=function(e){if(r)throw r=!1,e;return n("throw",e)}),"function"==typeof e.return&&(t.return=function(e){return r?(r=!1,e):n("return",e)}),t}function _asyncIterator(e){var t,r,n,i=2;for("undefined"!=typeof Symbol&&(r=Symbol.asyncIterator,n=Symbol.iterator);i--;){if(r&&null!=(t=e[r]))return t.call(e);if(n&&null!=(t=e[n]))return new AsyncFromSyncIterator(t.call(e));r="@@asyncIterator",n="@@iterator"}throw new TypeError("Object is not async iterable")}function AsyncFromSyncIterator(e){function t(e){if(Object(e)!==e)return Promise.reject(new TypeError(e+" is not an object."));var t=e.done;return Promise.resolve(e.value).then(function(e){return{value:e,done:t}})}return AsyncFromSyncIterator=function(e){this.s=e,this.n=e.next},AsyncFromSyncIterator.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var r=this.s.return;return void 0===r?Promise.resolve({value:e,done:!0}):t(r.apply(this.s,arguments))},throw:function(e){var r=this.s.return;return void 0===r?Promise.reject(e):t(r.apply(this.s,arguments))}},new AsyncFromSyncIterator(e)}function asyncGeneratorStep(e,t,r,n,i,a,s){try{var o=e[a](s),l=o.value}catch(e){return void r(e)}o.done?t(l):Promise.resolve(l).then(n,i)}function _asyncToGenerator(e){return function(){var t=this,r=arguments;return new Promise(function(n,i){var a=e.apply(t,r);function s(e){asyncGeneratorStep(a,n,i,s,o,"next",e)}function o(e){asyncGeneratorStep(a,n,i,s,o,"throw",e)}s(void 0)})}}function _awaitAsyncGenerator(e){return new _OverloadYield(e,0)}function _callSuper(e,t,r){return t=_getPrototypeOf(t),_possibleConstructorReturn(e,_isNativeReflectConstruct()?Reflect.construct(t,r||[],_getPrototypeOf(e).constructor):t.apply(e,r))}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _construct(e,t,r){if(_isNativeReflectConstruct())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,t);var i=new(e.bind.apply(e,n));return r&&_setPrototypeOf(i,r.prototype),i}function _defineProperties(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,_toPropertyKey$1(n.key),n)}}function _createClass(e,t,r){return t&&_defineProperties(e.prototype,t),r&&_defineProperties(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function _createForOfIteratorHelper(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=_unsupportedIterableToArray(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,s=!0,o=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return s=e.done,e},e:function(e){o=!0,a=e},f:function(){try{s||null==r.return||r.return()}finally{if(o)throw a}}}}function _defineProperty$1(e,t,r){return(t=_toPropertyKey$1(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function _get(){return _get="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(e,t,r){var n=_superPropBase(e,t);if(n){var i=Object.getOwnPropertyDescriptor(n,t);return i.get?i.get.call(arguments.length<3?e:r):i.value}},_get.apply(null,arguments)}function _getPrototypeOf(e){return _getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},_getPrototypeOf(e)}function _inherits(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&&_setPrototypeOf(e,t)}function _isNativeFunction(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}function _isNativeReflectConstruct(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(_isNativeReflectConstruct=function(){return!!e})()}function _iterableToArray(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function _iterableToArrayLimit(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,i,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=(n=a.call(r)).done)&&(o.push(n.value),o.length!==t);l=!0);}catch(e){u=!0,i=e}finally{try{if(!l&&null!=r.return&&(s=r.return(),Object(s)!==s))return}finally{if(u)throw i}}return o}}function _nonIterableRest(){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 _nonIterableSpread(){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 ownKeys$1(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function _objectSpread2$1(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$1(Object(r),!0).forEach(function(t){_defineProperty$1(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys$1(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function _possibleConstructorReturn(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 _assertThisInitialized(e)}function _regenerator(){var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",i=r.toStringTag||"@@toStringTag";function a(r,n,i,a){var l=n&&n.prototype instanceof o?n:o,u=Object.create(l.prototype);return _regeneratorDefine(u,"_invoke",function(r,n,i){var a,o,l,u=0,c=i||[],d=!1,h={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,r){return a=t,o=0,l=e,h.n=r,s}};function f(r,n){for(o=r,l=n,t=0;!d&&u&&!i&&t<c.length;t++){var i,a=c[t],f=h.p,v=a[2];r>3?(i=v===n)&&(l=a[(o=a[4])?5:(o=3,3)],a[4]=a[5]=e):a[0]<=f&&((i=r<2&&f<a[1])?(o=0,h.v=n,h.n=a[1]):f<v&&(i=r<3||a[0]>n||n>v)&&(a[4]=r,a[5]=n,h.n=v,o=0))}if(i||r>1)return s;throw d=!0,n}return function(i,c,v){if(u>1)throw TypeError("Generator is already running");for(d&&1===c&&f(c,v),o=c,l=v;(t=o<2?e:l)||!d;){a||(o?o<3?(o>1&&(h.n=-1),f(o,l)):h.n=l:h.v=l);try{if(u=2,a){if(o||(i="next"),t=a[i]){if(!(t=t.call(a,l)))throw TypeError("iterator result is not an object");if(!t.done)return t;l=t.value,o<2&&(o=0)}else 1===o&&(t=a.return)&&t.call(a),o<2&&(l=TypeError("The iterator does not provide a '"+i+"' method"),o=1);a=e}else if((t=(d=h.n<0)?l:r.call(n,h))!==s)break}catch(t){a=e,o=1,l=t}finally{u=1}}return{value:t,done:d}}}(r,i,a),!0),u}var s={};function o(){}function l(){}function u(){}t=Object.getPrototypeOf;var c=[][n]?t(t([][n]())):(_regeneratorDefine(t={},n,function(){return this}),t),d=u.prototype=o.prototype=Object.create(c);function h(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,_regeneratorDefine(e,i,"GeneratorFunction")),e.prototype=Object.create(d),e}return l.prototype=u,_regeneratorDefine(d,"constructor",u),_regeneratorDefine(u,"constructor",l),l.displayName="GeneratorFunction",_regeneratorDefine(u,i,"GeneratorFunction"),_regeneratorDefine(d),_regeneratorDefine(d,i,"Generator"),_regeneratorDefine(d,n,function(){return this}),_regeneratorDefine(d,"toString",function(){return"[object Generator]"}),(_regenerator=function(){return{w:a,m:h}})()}function _regeneratorDefine(e,t,r,n){var i=Object.defineProperty;try{i({},"",{})}catch(e){i=0}_regeneratorDefine=function(e,t,r,n){function a(t,r){_regeneratorDefine(e,t,function(e){return this._invoke(t,r,e)})}t?i?i(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(a("next",0),a("throw",1),a("return",2))},_regeneratorDefine(e,t,r,n)}function _regeneratorValues(e){if(null!=e){var t=e["function"==typeof Symbol&&Symbol.iterator||"@@iterator"],r=0;if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length))return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}throw new TypeError(typeof e+" is not iterable")}function _setPrototypeOf(e,t){return _setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},_setPrototypeOf(e,t)}function _slicedToArray(e,t){return _arrayWithHoles(e)||_iterableToArrayLimit(e,t)||_unsupportedIterableToArray(e,t)||_nonIterableRest()}function _superPropBase(e,t){for(;!{}.hasOwnProperty.call(e,t)&&null!==(e=_getPrototypeOf(e)););return e}function _superPropGet(e,t,r,n){var i=_get(_getPrototypeOf(e.prototype),t,r);return"function"==typeof i?function(e){return i.apply(r,e)}:i}function _toConsumableArray(e){return _arrayWithoutHoles(e)||_iterableToArray(e)||_unsupportedIterableToArray(e)||_nonIterableSpread()}function _toPrimitive$1(e,t){if("object"!=typeof e||!e)return e;var r;if("undefined"!=typeof Symbol&&void 0!==(r=e[Symbol.toPrimitive])){var n=r.call(e,t);if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}function _toPropertyKey$1(e){var t=_toPrimitive$1(e,"string");return"symbol"==typeof t?t:t+""}function _typeof(e){return _typeof="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},_typeof(e)}function _unsupportedIterableToArray(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray(e,t):void 0}}function _wrapAsyncGenerator(e){return function(){return new AsyncGenerator(e.apply(this,arguments))}}function AsyncGenerator(e){var t,r;function n(t,r){try{var a=e[t](r),s=a.value,o=s instanceof _OverloadYield;Promise.resolve(o?s.v:s).then(function(r){if(o){var l="return"===t&&s.k?t:"next";if(!s.k||r.done)return n(l,r);r=e[l](r).value}i(!!a.done,r)},function(e){n("throw",e)})}catch(e){i(2,e)}}function i(e,i){2===e?t.reject(i):t.resolve({value:i,done:e}),(t=t.next)?n(t.key,t.arg):r=null}this._invoke=function(e,i){return new Promise(function(a,s){var o={key:e,arg:i,resolve:a,reject:s,next:null};r?r=r.next=o:(t=r=o,n(e,i))})},"function"!=typeof e.return&&(this.return=void 0)}function _wrapNativeSuper(e){var t="function"==typeof Map?new Map:void 0;return _wrapNativeSuper=function(e){if(null===e||!_isNativeFunction(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 _construct(e,arguments,_getPrototypeOf(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),_setPrototypeOf(r,e)},_wrapNativeSuper(e)}AsyncGenerator.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},AsyncGenerator.prototype.next=function(e){return this._invoke("next",e)},AsyncGenerator.prototype.throw=function(e){return this._invoke("throw",e)},AsyncGenerator.prototype.return=function(e){return this._invoke("return",e)};var isFiniteNumber=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},isSafeInteger=Number.isSafeInteger||function(e){return"number"==typeof e&&Math.abs(e)<=MAX_SAFE_INTEGER},MAX_SAFE_INTEGER=Number.MAX_SAFE_INTEGER||9007199254740991,ErrorTypes=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}({}),ErrorDetails=function(e){return e.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",e.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",e.KEY_SYSTEM_NO_SESSION="keySystemNoSession",e.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",e.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",e.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",e.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",e.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",e.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",e.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",e.MANIFEST_LOAD_ERROR="manifestLoadError",e.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",e.MANIFEST_PARSING_ERROR="manifestParsingError",e.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",e.LEVEL_EMPTY_ERROR="levelEmptyError",e.PLAYLIST_UNCHANGED_ERROR="playlistUnchangedError",e.LEVEL_LOAD_ERROR="levelLoadError",e.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",e.LEVEL_PARSING_ERROR="levelParsingError",e.LEVEL_SWITCH_ERROR="levelSwitchError",e.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",e.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",e.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",e.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",e.FRAG_LOAD_ERROR="fragLoadError",e.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",e.FRAG_DECRYPT_ERROR="fragDecryptError",e.FRAG_PARSING_ERROR="fragParsingError",e.FRAG_GAP="fragGap",e.REMUX_ALLOC_ERROR="remuxAllocError",e.KEY_LOAD_ERROR="keyLoadError",e.KEY_LOAD_TIMEOUT="keyLoadTimeOut",e.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",e.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",e.BUFFER_APPEND_ERROR="bufferAppendError",e.BUFFER_APPENDING_ERROR="bufferAppendingError",e.BUFFER_APPEND_NO_PROGRESS="bufferAppendNoProgress",e.BUFFER_STALLED_ERROR="bufferStalledError",e.BUFFER_FULL_ERROR="bufferFullError",e.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",e.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",e.ASSET_LIST_LOAD_ERROR="assetListLoadError",e.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",e.ASSET_LIST_PARSING_ERROR="assetListParsingError",e.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",e.INTERNAL_EXCEPTION="internalException",e.INTERNAL_ABORTED="aborted",e.ATTACH_MEDIA_ERROR="attachMediaError",e.MEDIA_SOURCE_REQUIRES_RESET="mediaSourceRequiresReset",e.UNKNOWN="unknown",e}({}),Events$2=function(e){return e.MEDIA_ATTACHING="hlsMediaAttaching",e.MEDIA_ATTACHED="hlsMediaAttached",e.MEDIA_DETACHING="hlsMediaDetaching",e.MEDIA_DETACHED="hlsMediaDetached",e.MEDIA_ENDED="hlsMediaEnded",e.STALL_RESOLVED="hlsStallResolved",e.BUFFER_RESET="hlsBufferReset",e.BUFFER_CODECS="hlsBufferCodecs",e.BUFFER_CREATED="hlsBufferCreated",e.BUFFER_APPENDING="hlsBufferAppending",e.BUFFER_APPENDED="hlsBufferAppended",e.BUFFER_EOS="hlsBufferEos",e.BUFFERED_TO_END="hlsBufferedToEnd",e.BUFFER_FLUSHING="hlsBufferFlushing",e.BUFFER_FLUSHED="hlsBufferFlushed",e.MANIFEST_LOADING="hlsManifestLoading",e.MANIFEST_LOADED="hlsManifestLoaded",e.MANIFEST_PARSED="hlsManifestParsed",e.LEVEL_SWITCHING="hlsLevelSwitching",e.LEVEL_SWITCHED="hlsLevelSwitched",e.LEVEL_LOADING="hlsLevelLoading",e.LEVEL_LOADED="hlsLevelLoaded",e.LEVEL_UPDATED="hlsLevelUpdated",e.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",e.LEVELS_UPDATED="hlsLevelsUpdated",e.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",e.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",e.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",e.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",e.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",e.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",e.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",e.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",e.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",e.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",e.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",e.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",e.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",e.CUES_PARSED="hlsCuesParsed",e.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",e.INIT_PTS_FOUND="hlsInitPtsFound",e.FRAG_LOADING="hlsFragLoading",e.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",e.FRAG_LOADED="hlsFragLoaded",e.FRAG_DECRYPTED="hlsFragDecrypted",e.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",e.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",e.FRAG_PARSING_METADATA="hlsFragParsingMetadata",e.FRAG_PARSED="hlsFragParsed",e.FRAG_BUFFERED="hlsFragBuffered",e.FRAG_CHANGED="hlsFragChanged",e.FPS_DROP="hlsFpsDrop",e.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",e.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",e.ERROR="hlsError",e.DESTROYING="hlsDestroying",e.KEY_LOADING="hlsKeyLoading",e.KEY_LOADED="hlsKeyLoaded",e.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",e.BACK_BUFFER_REACHED="hlsBackBufferReached",e.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",e.ASSET_LIST_LOADING="hlsAssetListLoading",e.ASSET_LIST_LOADED="hlsAssetListLoaded",e.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",e.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",e.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",e.INTERSTITIAL_STARTED="hlsInterstitialStarted",e.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",e.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",e.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",e.INTERSTITIAL_ENDED="hlsInterstitialEnded",e.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",e.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",e.EVENT_CUE_ENTER="hlsEventCueEnter",e}({});function getDefaultExportFromCjs$1(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var hasRequiredUrlToolkit,urlToolkit={exports:{}};function requireUrlToolkit(){return hasRequiredUrlToolkit||(hasRequiredUrlToolkit=1,e=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,t=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,i={buildAbsoluteURL:function(e,r,n){if(n=n||{},e=e.trim(),!(r=r.trim())){if(!n.alwaysNormalize)return e;var a=i.parseURL(e);if(!a)throw new Error("Error trying to parse base URL.");return a.path=i.normalizePath(a.path),i.buildURLFromParts(a)}var s=i.parseURL(r);if(!s)throw new Error("Error trying to parse relative URL.");if(s.scheme)return n.alwaysNormalize?(s.path=i.normalizePath(s.path),i.buildURLFromParts(s)):r;var o=i.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=t.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=i.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=n.alwaysNormalize?i.normalizePath(s.path):s.path),i.buildURLFromParts(u)},parseURL:function(t){var r=e.exec(t);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(r,"");e.length!==(e=e.replace(n,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}},urlToolkit.exports=i),urlToolkit.exports;var e,t,r,n,i}var urlToolkitExports=requireUrlToolkit(),LoadStats=_createClass(function e(){_classCallCheck(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}}),LoaderContextType=function(e){return e.MANIFEST="manifest",e.LEVEL="level",e.AUDIO_TRACK="audioTrack",e.SUBTITLE_TRACK="subtitleTrack",e.MEDIA_FRAGMENT="media-fragment",e.KEY="key",e.STEERING_MANIFEST="steering-manifest",e.SERVER_CERTIFICATE="server-certificate",e.INTERSTITIAL_ASSET_LIST="interstitial-asset-list",e}({}),PlaylistLevelType=function(e){return e.MAIN="main",e.AUDIO="audio",e.SUBTITLE="subtitle",e}({}),ElementaryStreamTypes={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"},BaseSegment=function(){return _createClass(function e(t){_classCallCheck(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,makeEnumerable(this,"stats")},[{key:"setByteRange",value:function(e,t){var r,n=e.split("@",2);r=1===n.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(n[1]),this._byteRange=[r,parseInt(n[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=_defineProperty$1(_defineProperty$1(_defineProperty$1({},ElementaryStreamTypes.AUDIO,null),ElementaryStreamTypes.VIDEO,null),ElementaryStreamTypes.AUDIOVIDEO,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 LoadStats),this._stats},set:function(e){this._stats=e}},{key:"url",get:function(){return!this._url&&this.relurl&&(this._url=urlToolkitExports.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""},set:function(e){this._url=e}},{key:"clearElementaryStreamInfo",value:function(){var e=this.elementaryStreams;e[ElementaryStreamTypes.AUDIO]=null,e[ElementaryStreamTypes.VIDEO]=null,e[ElementaryStreamTypes.AUDIOVIDEO]=null,this.url=null}}])}();function isMediaFragment(e){return"initSegment"!==e.sn}function mediaFragmentsAreEqual(e,t){return e.sn===(null==t?void 0:t.sn)&&e.level===t.level}function fragmentsAreEqual(e,t){return e.sn===(null==t?void 0:t.sn)&&e.level===t.level&&e.cc===t.cc}var Fragment=function(){function e(t,r){var n;return _classCallCheck(this,e),(n=_callSuper(this,e,[r]))._decryptdata=null,n._programDateTime=null,n._ref=null,n._bitrate=void 0,n.rawProgramDateTime=null,n.tagList=[],n.duration=0,n.sn=0,n.levelkeys=void 0,n.type=void 0,n.loader=null,n.keyLoader=null,n.level=-1,n.cc=0,n.startPTS=void 0,n.endPTS=void 0,n.startDTS=void 0,n.endDTS=void 0,n.start=0,n.playlistOffset=0,n.deltaPTS=void 0,n.maxStartPTS=void 0,n.minEndPTS=void 0,n.data=void 0,n.bitrateTest=!1,n.title=null,n.initSegment=null,n.endList=void 0,n.gap=void 0,n.urlId=0,n.type=t,n}return _inherits(e,BaseSegment),_createClass(e,[{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(isFiniteNumber(t)&&isFiniteNumber(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 n=this._decryptdata=t[r[0]]||null;n&&(this._decryptdata=n.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=isFiniteNumber(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),n=r.length;if(n>1||1===n&&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){isFiniteNumber(e)?this._programDateTime=e:this._programDateTime=this.rawProgramDateTime=null}},{key:"ref",get:function(){return isMediaFragment(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,n=t[e];!n||null!=(r=this._decryptdata)&&r.keyId||(this._decryptdata=n.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,n,i){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,n),o.endDTS=Math.max(o.endDTS,i)):s[e]={startPTS:t,endPTS:r,startDTS:n,endDTS:i,partial:a}}}])}(),Part=function(){function e(t,r,n,i,a){var s;_classCallCheck(this,e),(s=_callSuper(this,e,[n])).fragOffset=0,s.duration=0,s.independent=!1,s.relurl=void 0,s.fragment=void 0,s.index=void 0,s.gap=!1,s.duration=t.decimalFloatingPoint("DURATION"),s.gap=t.bool("GAP"),s.independent=t.bool("INDEPENDENT"),s.relurl=t.enumeratedString("URI"),s.fragment=r,s.index=i;var o=t.enumeratedString("BYTERANGE");return o&&s.setByteRange(o,a),a&&(s.fragOffset=a.fragOffset+a.duration),s}return _inherits(e,BaseSegment),_createClass(e,[{key:"start",get:function(){return this.fragment.start+this.fragOffset}},{key:"end",get:function(){return this.start+this.duration}},{key:"loaded",get:function(){var e=this.elementaryStreams;return!!(e.audio||e.video||e.audiovideo||this.fragment.type===PlaylistLevelType.SUBTITLE&&this.stats.loading.end>0)}}])}();function getOwnPropertyDescriptorFromPrototypeChain(e,t){var r=Object.getPrototypeOf(e);if(r){var n=Object.getOwnPropertyDescriptor(r,t);return n||getOwnPropertyDescriptorFromPrototypeChain(r,t)}}function makeEnumerable(e,t){var r=getOwnPropertyDescriptorFromPrototypeChain(e,t);r&&(r.enumerable=!0,Object.defineProperty(e,t,r))}function _defineProperty(e,t,r){return(t=_toPropertyKey(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function _extends(){return _extends=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},_extends.apply(null,arguments)}function ownKeys(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function _objectSpread2(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys(Object(r),!0).forEach(function(t){_defineProperty(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function _objectWithoutProperties(e,t){if(null==e)return{};var r,n,i=_objectWithoutPropertiesLoose(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(n=0;n<a.length;n++)r=a[n],-1===t.indexOf(r)&&{}.propertyIsEnumerable.call(e,r)&&(i[r]=e[r])}return i}function _objectWithoutPropertiesLoose(e,t){if(null==e)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(-1!==t.indexOf(n))continue;r[n]=e[n]}return r}function _toPrimitive(e,t){if("object"!=_typeof(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t);if("object"!=_typeof(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}function _toPropertyKey(e){var t=_toPrimitive(e,"string");return"symbol"==_typeof(t)?t:t+""}function isTimeoutError(e){switch(e.details){case ErrorDetails.FRAG_LOAD_TIMEOUT:case ErrorDetails.KEY_LOAD_TIMEOUT:case ErrorDetails.LEVEL_LOAD_TIMEOUT:case ErrorDetails.MANIFEST_LOAD_TIMEOUT:case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:case ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:case ErrorDetails.ASSET_LIST_LOAD_TIMEOUT:return!0}return!1}function isKeyError(e){return e.details.startsWith("key")}function isUnusableKeyError(e){return isKeyError(e)&&!!e.frag&&!e.frag.decryptdata}function getRetryConfig(e,t){var r=isTimeoutError(t);return e.default["".concat(r?"timeout":"error","Retry")]}function getRetryDelay(e,t){var r="linear"===e.backoff?1:Math.pow(2,t);return Math.min(r*e.retryDelayMs,e.maxRetryDelayMs)}function getLoaderConfigWithoutReties(e){return _objectSpread2(_objectSpread2({},e),{errorRetry:null,timeoutRetry:null})}function shouldRetry(e,t,r,n){if(!e)return!1;var i=null==n?void 0:n.code,a=t<e.maxNumRetry&&(retryForHttpStatus(i)||!!r);return e.shouldRetry?e.shouldRetry(e,t,r,n,a):a}function retryForHttpStatus(e){return offlineHttpStatus(e)||!!e&&(e<400||e>499)}function offlineHttpStatus(e){return 0===e&&!1===navigator.onLine}function isPenaltyExpired(e,t){return t>0&&e.loadError>0&&0!==e.loadErrorTime&&self.performance.now()-e.loadErrorTime>t}var EWMA=function(){return _createClass(function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;_classCallCheck(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_=n},[{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_}}])}(),EwmaBandWidthEstimator=function(){return _createClass(function e(t,r,n){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:100;_classCallCheck(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_=n,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new EWMA(t),this.fast_=new EWMA(r),this.defaultTTFB_=i,this.ttfb_=new EWMA(t)},[{key:"update",value:function(e,t){var r=this.slow_,n=this.fast_,i=this.ttfb_;r.halfLife!==e&&(this.slow_=new EWMA(e,r.getEstimate(),r.getTotalWeight())),n.halfLife!==t&&(this.fast_=new EWMA(t,n.getEstimate(),n.getTotalWeight())),i.halfLife!==e&&(this.ttfb_=new EWMA(e,i.getEstimate(),i.getTotalWeight()))}},{key:"sample",value:function(e,t){if(!(t<=0)){var r=Math.min(this.minDelayMs_,t/1e5),n=8*t,i=Math.max(e,r)/1e3,a=n/i;this.fast_.sample(i,a),this.slow_.sample(i,a)}}},{key:"sampleTTFB",value:function(e){var t=e/1e3,r=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(r,Math.max(e,5))}},{key:"canEstimate",value:function(){return this.fast_.getTotalWeight()>=this.minWeight_}},{key:"getEstimate",value:function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}},{key:"getEstimateTTFB",value:function(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}},{key:"defaultEstimate",get:function(){return this.defaultEstimate_}},{key:"destroy",value:function(){}}])}(),Logger$1=_createClass(function e(t,r){_classCallCheck(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 n="[".concat(t,"]:");this.trace=noop$1,this.debug=r.debug.bind(null,n),this.log=r.log.bind(null,n),this.warn=r.warn.bind(null,n),this.info=r.info.bind(null,n),this.error=r.error.bind(null,n)}),noop$1=function(){},fakeLogger={trace:noop$1,debug:noop$1,log:noop$1,warn:noop$1,info:noop$1,error:noop$1};function createLogger(){return _extends({},fakeLogger)}function consolePrintFn(e,t){var r=self.console[e];return r?r.bind(self.console,"".concat(t?"["+t+"] ":"","[").concat(e,"] >")):noop$1}function getLoggerFn(e,t,r){return t[e]?t[e].bind(t):consolePrintFn(e,r)}var exportedLogger=createLogger();function enableLogs(e,t,r){var n=createLogger();if("object"===("undefined"==typeof console?"undefined":_typeof(console))&&!0===e||"object"===_typeof(e)){var i=["debug","log","info","warn","error"];i.forEach(function(t){n[t]=getLoggerFn(t,e,r)});try{n.log('Debug logs enabled for "'.concat(t,'" in hls.js version ',"1.7.3"))}catch(a){return createLogger()}i.forEach(function(t){exportedLogger[t]=getLoggerFn(t,e)})}else _extends(exportedLogger,n);return n}var logger=exportedLogger;function _getMediaSource2(){if("undefined"!=typeof self)return(!(arguments.length>0&&void 0!==arguments[0])||arguments[0]||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function isManagedMediaSource(e){return"undefined"!=typeof self&&e===self.ManagedMediaSource}function isCompatibleTrackChange(e,t){var r=Object.keys(e),n=Object.keys(t),i=r.length,a=n.length;return!i||!a||i===a&&!r.some(function(e){return-1===n.indexOf(e)})}function encodeBase64(e){return btoa(String.fromCharCode.apply(String,_toConsumableArray(e)))}function isArrayBufferLike(e){return e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer}var UTF_16="utf-16",UTF_16_BE="utf-16be",UTF_16_LE="utf-16le",UTF_8="utf-8";function decodeText(e){var t,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};t=isArrayBufferLike(e)?new DataView(e):new DataView(e.buffer,e.byteOffset,e.byteLength);var n=0,i=r.encoding;if(!i){var a=t.getUint8(0),s=t.getUint8(1);239==a&&187==s&&191==t.getUint8(2)?(i=UTF_8,n=3):254==a&&255==s?(i=UTF_16_BE,n=2):255==a&&254==s?(i=UTF_16_LE,n=2):i=UTF_8}if("undefined"!=typeof TextDecoder)return new TextDecoder(i).decode(t);for(var o,l=t.byteLength,u=i!==UTF_16_BE,c="";n<l;){switch(i){case UTF_8:if((o=t.getUint8(n))<128)n++;else if(o>=194&&o<=223)if(n+1<l){var d=t.getUint8(n+1);d>=128&&d<=191?(o=(31&o)<<6|63&d,n+=2):n++}else n++;else if(o>=224&&o<=239)if(n+2<=l-1){var h=t.getUint8(n+1),f=t.getUint8(n+2);h>=128&&h<=191&&f>=128&&f<=191?(o=(15&o)<<12|(63&h)<<6|63&f,n+=3):n++}else n++;else if(o>=240&&o<=244)if(n+3<=l-1){var v=t.getUint8(n+1),p=t.getUint8(n+2),g=t.getUint8(n+3);v>=128&&v<=191&&p>=128&&p<=191&&g>=128&&g<=191?(o=(7&o)<<18|(63&v)<<12|(63&p)<<6|63&g,n+=4):n++}else n++;else n++;break;case UTF_16_BE:case UTF_16:case UTF_16_LE:o=t.getUint16(n,u),n+=2}c+=String.fromCodePoint(o)}return c}function getBaseUrl(e){var t="string"==typeof e?new URL(e):e;return t.origin+t.pathname.substring(0,t.pathname.lastIndexOf("/")+1)}function roundToEven(e,t){if(e<0)return-roundToEven(-e,t);var r=Math.pow(10,t);if(Math.abs(e*r%1-.5)<Number.EPSILON){var n=Math.floor(e*r);return(n%2==0?n:n+1)/r}return Math.round(e*r)/r}function urlToRelativePath(e,t){var r;try{r=new URL(e)}catch(l){return e}var n=new URL(t);if(r.origin!==n.origin)return e;for(var i=r.pathname.split("/").slice(1),a=n.pathname.split("/").slice(1,-1),s=Math.min(i.length,a.length),o=0;o<s&&i[o]===a[o];o++)i.shift(),a.shift();for(;a.length;)a.shift(),i.unshift("..");return i.join("/")+r.search+r.hash}function uuid(){try{return crypto.randomUUID()}catch(n){try{var e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(i){var r=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=(r+16*Math.random())%16|0;return r=Math.floor(r/16),("x"==e?t:3&t|8).toString(16)})}}}function isId3Header(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 readId3Size(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 canParseId3(e,t){return isId3Header(e,t)&&readId3Size(e,t+6)+10<=e.length-t}function isId3Footer(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 getId3Data(e,t){for(var r=t,n=0;isId3Header(e,t);){n+=10,n+=readId3Size(e,t+6),isId3Footer(e,t+10)&&(n+=10),t+=n}if(n>0)return e.subarray(r,r+n)}function toArrayBuffer(e){return isArrayBufferLike(e)?e:0==e.byteOffset&&e.byteLength==e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer}function toUint8(e){return view(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,arguments.length>2&&void 0!==arguments[2]?arguments[2]:1/0,Uint8Array)}function view(e,t,r,n){var i=unsafeGetArrayBuffer(e),a=1;"BYTES_PER_ELEMENT"in n&&(a=n.BYTES_PER_ELEMENT);var s=isArrayBufferView$1(e)?e.byteOffset:0,o=(s+e.byteLength)/a,l=(s+t)/a,u=Math.floor(Math.max(0,Math.min(l,o)));return new n(i,u,Math.floor(Math.min(u+Math.max(r,0),o))-u)}function unsafeGetArrayBuffer(e){return isArrayBufferLike(e)?e:e.buffer}function isArrayBufferView$1(e){return e&&isArrayBufferLike(e.buffer)&&void 0!==e.byteLength&&void 0!==e.byteOffset}function utf8ArrayToStr(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=t?e.indexOf(0):e.length,n=decodeText(new DataView(e.buffer,e.byteOffset,r),{encoding:UTF_8});return t?n:n.replace(/\0/g,"")}function decodeId3ImageFrame(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 n=utf8ArrayToStr(toUint8(e.data,1,r)),i=e.data[2+r],a=e.data.subarray(3+r).indexOf(0);if(-1!==a){var s,o=utf8ArrayToStr(toUint8(e.data,3+r,a));return s="--\x3e"===n?utf8ArrayToStr(toUint8(e.data,4+r+a)):toArrayBuffer(e.data.subarray(4+r+a)),t.mimeType=n,t.pictureType=i,t.description=o,t.data=s,t}}}else console.log("Ignore frame with unrecognized character encoding")}function decodeId3PrivFrame(e){if(!(e.size<2)){var t=utf8ArrayToStr(e.data,!0),r=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:r.buffer}}}function decodeId3TextFrame(e){if(!(e.size<2)){if("TXXX"===e.type){var t=1,r=e.data,n=utf8ArrayToStr(r.subarray(t),!0);t+=n.length+1;var i=utf8ArrayToStr(r.subarray(t));return{key:e.type,info:n,data:i}}var a=utf8ArrayToStr(e.data.subarray(1));return{key:e.type,info:"",data:a}}}function decodeId3UrlFrame(e){if("WXXX"===e.type){if(e.size<2)return;var t=1,r=utf8ArrayToStr(e.data.subarray(t),!0);t+=r.length+1;var n=utf8ArrayToStr(e.data.subarray(t));return{key:e.type,info:r,data:n}}var i=utf8ArrayToStr(e.data);return{key:e.type,info:"",data:i}}function decodeId3Frame(e){return"PRIV"===e.type?decodeId3PrivFrame(e):"W"===e.type[0]?decodeId3UrlFrame(e):"APIC"===e.type?decodeId3ImageFrame(e):decodeId3TextFrame(e)}function getId3FrameData(e){var t=String.fromCharCode(e[0],e[1],e[2],e[3]),r=readId3Size(e,4);return{type:t,size:r,data:e.subarray(10,10+r)}}var HEADER_FOOTER_SIZE=10,FRAME_SIZE=10;function getId3Frames(e){for(var t=0,r=[];isId3Header(e,t);){var n=readId3Size(e,t+6);e[t+5]>>6&1&&(t+=HEADER_FOOTER_SIZE);for(var i=(t+=HEADER_FOOTER_SIZE)+n;t+FRAME_SIZE<i;){var a=getId3FrameData(e.subarray(t)),s=decodeId3Frame(a);s&&r.push(s),t+=a.size+HEADER_FOOTER_SIZE}isId3Footer(e,t)&&(t+=HEADER_FOOTER_SIZE)}return r}function isId3TimestampFrame(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info}function readId3Timestamp(e){if(8===e.data.byteLength){var t=new Uint8Array(e.data),r=1&t[3],n=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return n/=45,r&&(n+=47721858.84),Math.round(n)}}function getId3Timestamp(e){var t,r=_createForOfIteratorHelper(getId3Frames(e));try{for(r.s();!(t=r.n()).done;){var n=t.value;if(isId3TimestampFrame(n))return readId3Timestamp(n)}}catch(i){r.e(i)}finally{r.f()}}function arrayToHex(e){for(var t="",r=0;r<e.length;r++){var n=e[r].toString(16);n.length<2&&(n="0"+n),t+=n}return t}function hexToArrayBuffer(e){return Uint8Array.from(e.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function base64Decode(e){return Uint8Array.from(atob(e),function(e){return e.charCodeAt(0)})}function bin2str(e){return String.fromCharCode.apply(null,e)}var utf8TextDecoder,UINT32_MAX=Math.pow(2,32)-1,types={avc1:1635148593,avcC:1635148611,hvc1:1752589105,hvcC:1752589123,btrt:1651798644,dinf:1684631142,dref:1685218662,esds:1702061171,free:1718773093,ftyp:1718909296,hdlr:1751411826,mdat:1835295092,mdhd:1835296868,mdia:1835297121,mfhd:1835427940,minf:1835626086,moof:1836019558,moov:1836019574,mp4a:1836069985,".mp3":778924083,dac3:1684103987,"ac-3":1633889587,mvex:1836475768,mvhd:1836476516,pasp:1885434736,sdtp:1935963248,stbl:1937007212,stco:1937007471,stsc:1937011555,stsd:1937011556,stsz:1937011578,stts:1937011827,tfdt:1952867444,tfhd:1952868452,traf:1953653094,trak:1953653099,trun:1953658222,trex:1953654136,tkhd:1953196132,vmhd:1986881636,smhd:1936549988},RemuxerTrackIdConfig={video:1,audio:2,id3:3,text:4};function readUint16(e,t){var r=e[t]<<8|e[t+1];return r<0?65536+r:r}function readUint32(e,t){var r=e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3];return r<0?4294967296+r:r}function readUint64(e,t){var r=readUint32(e,t);return r*=Math.pow(2,32),r+=readUint32(e,t+4)}function readCString(e,t){for(var r="",n=t;n<e.length;n++)if(r+=String.fromCharCode(e[n]),0===e[n])return r;return null}function readSint32(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function writeUint32(e,t,r){e[t]=r>>24,e[t+1]=r>>16&255,e[t+2]=r>>8&255,e[t+3]=255&r}function shrinkBox(e,t,r){var n=t.byteOffset-e.byteOffset-8,i=8+r,a=t.byteLength+8-i;a<8||(writeUint32(e,n,i),writeUint32(e,n+i,a),writeUint32(e,n+i+4,types.free))}function boxRange(e,t){return[e.byteOffset-t-8,e.byteOffset-t+e.byteLength]}function spliceOutBoxes(e,t){t.sort(function(e,t){return e[0]-t[0]});for(var r=t.reduce(function(e,t){var r=_slicedToArray(t,2),n=r[0];return e+r[1]-n},0),n=new Uint8Array(e.byteLength-r),i=0,a=0,s=0;s<t.length;s++){var o=_slicedToArray(t[s],2),l=o[0],u=o[1];n.set(e.subarray(i,l),a),a+=l-i,i=u}n.set(e.subarray(i),a);return{result:n,dropped:r,droppedBefore:function(e){return t.reduce(function(t,r){var n=_slicedToArray(r,2),i=n[0],a=n[1];return a<=e?t+a-i:t},0)}}}function videoOnlyInitSegment(e){var t=findBox(e,["moov"]);if(1!==t.length||findBox(e,["moof"]).length)return null;for(var r=e.byteOffset,n=[],i=[],a=!1,s=findBox(t[0],["trak"]),o=0;o<s.length;o++){var l=s[o],u=findBox(l,["mdia","hdlr"])[0];if("vide"!==(u?bin2str(u.subarray(8,12)):"")){var c=findBox(l,["tkhd"])[0];if(!c)return null;var d=c[0];i.push(readUint32(c,0===d?12:20)),n.push(boxRange(l,r))}else a=!0}if(!a||!n.length)return null;var h=findBox(t[0],["mvex"])[0],f=0;if(h)for(var v=findBox(h,["trex"]),p=0;p<v.length;p++){var g=v[p];-1!==i.indexOf(readUint32(g,4))&&(n.push(boxRange(g,r)),f+=g.byteLength+8)}var y=spliceOutBoxes(e,n),m=y.result,E=y.dropped,S=y.droppedBefore;if(writeUint32(m,t[0].byteOffset-r-8,t[0].byteLength+8-E),h&&f){var T=h.byteOffset-r-8;writeUint32(m,T-S(T),h.byteLength+8-f)}return m}function remuxVideoOnlyIFrameMoof(e,t,r,n,i){if(r<1)return null;var a=findBox(e,["moof"]);if(1!==a.length)return null;for(var s=a[0],o=e.byteOffset,l=[],u=[],c=findBox(s,["traf"]),d=!0,h=0;h<c.length;h++){var f=c[h],v=findBox(f,["tfhd"])[0];if(!v)return null;readUint32(v,4)===t?(l.push(f),131072&readUint32(v,0)||(d=!1)):u.push(boxRange(f,o))}if(!l.length)return null;if(u.length&&!d)return null;if(void 0!==n){for(var p=r,g=0;g<l.length;g++){for(var y=l[g],m=0,E=findBox(y,["trun"]),S=0;S<E.length;S++){var T=E[S],k=Math.min(p,readUint32(T,4));if(k){writeUint32(e,T.byteOffset-o+4,k);var _=16777215&readUint32(T,0);shrinkBox(e,T,8+(1&_?4:0)+(4&_?4:0)+k*((256&_?4:0)+(512&_?4:0)+(1024&_?4:0)+(2048&_?4:0)))}else writeUint32(e,T.byteOffset-o-4,types.free);p-=k,m+=k}var A=findBox(y,["senc"])[0];A&&writeUint32(e,A.byteOffset-o+4,m);var b=findBox(y,["saiz"])[0];if(b){var L=4;1&(b[1]<<16|b[2]<<8|b[3])&&(L+=8);var R=b[L];L+=1,writeUint32(e,b.byteOffset-o+L,m),shrinkBox(e,b,L+4+(0===R?m:0))}}var C=findBox(e,["mdat"]);if(1===C.length){var I=C[0].byteOffset-o-8;writeUint32(e,I,n-I)}}var P=e,D=0,w=function(){return 0};if(u.length){var O=spliceOutBoxes(e,u);P=O.result,D=O.dropped,w=O.droppedBefore,writeUint32(P,s.byteOffset-o-8,s.byteLength+8-D);for(var x=0;x<l.length;x++){for(var M=l[x],F=w(M.byteOffset-o),N=findBox(M,["trun"]),U=0;U<N.length;U++){var B=N[U];1&readUint32(B,0)&&writeUint32(P,B.byteOffset-o-F+8,readUint32(B,8)-D)}if(F)for(var G=findBox(M,["saio"]),H=0;H<G.length;H++){var $=G[H],K=0===$[0]?4:8,V=1&readUint32($,0)?12:4,j=readUint32($,V);for(V+=4;j--;V+=K){var q=V+K-4;writeUint32(P,$.byteOffset-o-F+q,readUint32($,q)-F)}}}}if(i){var W=i.durationOffset,Y=i.value;writeUint32(P,W-w(W),Y)}return void 0!==n?P.subarray(0,n-D):P}function hasBoxData(e,t){for(var r=e.byteLength,n=0;n<r;){var i=readUint32(e,n);if(i>8&&readUint32(e,n+4)===types[t])return!0;n=i>1?n+i:r}return!1}function findBox(e,t){var r=[];return t.length?(findBoxPath(e,t,0,0,e.byteLength,r),r):r}function findBoxPath(e,t,r,n,i,a){var s=t[r];if(4===(null==s?void 0:s.length))for(var o=s.charCodeAt(0),l=s.charCodeAt(1),u=s.charCodeAt(2),c=s.charCodeAt(3),d=t.length-1,h=n;h<i;){var f=h+8<=i,v=h+4<=i?16777216*e[h]+(e[h+1]<<16|e[h+2]<<8|e[h+3]):readUint32(e,h),p=v>1?h+v:i;if(f&&e[h+4]===o&&e[h+5]===l&&e[h+6]===u&&e[h+7]===c){var g=Math.min(p,i);r===d?a.push(e.subarray(h+8,g)):findBoxPath(e,t,r+1,h+8,g,a)}h=p}}function parseSegmentIndex(e){var t=[],r=e[0],n=8,i=readUint32(e,n);n+=4;var a=0,s=0;0===r?(a=readUint32(e,n),s=readUint32(e,n+4),n+=8):(a=readUint64(e,n),s=readUint64(e,n+8),n+=16),n+=2;var o=e.length+s,l=readUint16(e,n);n+=2;for(var u=0;u<l;u++){var c=n,d=readUint32(e,c);c+=4;var h=2147483647&d;if(1===(2147483648&d)>>>31)return logger.warn("SIDX has hierarchical references (not supported)"),null;var f=readUint32(e,c);c+=4,t.push({referenceSize:h,subsegmentDuration:f,info:{duration:f/i,start:o,end:o+h-1}}),o+=h,n=c+=4}return{earliestPresentationTime:a,timescale:i,version:r,referencesCount:l,references:t}}function parseInitSegment(e){for(var t=[],r=findBox(e,["moov","trak"]),n=0;n<r.length;n++){var i=r[n],a=findBox(i,["tkhd"])[0];if(a){var s=a[0],o=readUint32(a,0===s?12:20),l=findBox(i,["mdia","mdhd"])[0];if(l){var u=readUint32(l,0===(s=l[0])?12:20),c=findBox(i,["mdia","hdlr"])[0];if(c){var d=bin2str(c.subarray(8,12)),h={soun:ElementaryStreamTypes.AUDIO,vide:ElementaryStreamTypes.VIDEO}[d],f=parseStsd(findBox(i,["mdia","minf","stbl","stsd"])[0]);h?(t[o]={timescale:u,type:h,stsd:f},t[h]=_objectSpread2({timescale:u,id:o},f)):t[o]={timescale:u,type:d,stsd:f}}}}}return findBox(e,["moov","mvex","trex"]).forEach(function(e){var r=readUint32(e,4),n=t[r];n&&(n.default={duration:readUint32(e,12),sampleSize:readUint32(e,16),flags:readUint32(e,20)})}),t}function parseStsd(e){var t,r=e.subarray(8),n=r.subarray(86),i=bin2str(r.subarray(4,8)),a=i,s="enca"===i||"encv"===i;if(s){var o=findBox(r,[i])[0];findBox(o.subarray("enca"===i?28:78),["sinf"]).forEach(function(e){var t=findBox(e,["schm"])[0];if(t){var r=bin2str(t.subarray(4,8));if("cbcs"===r||"cenc"===r){var n=findBox(e,["frma"])[0];n&&(a=bin2str(n))}}})}var l=a;switch(a){case"avc1":case"avc2":case"avc3":case"avc4":var u=findBox(n,["avcC"])[0];u&&u.length>3&&(a+="."+toHex(u[1])+toHex(u[2])+toHex(u[3]),t=parseSupplementalDoViCodec("avc1"===l?"dva1":"dvav",n));break;case"mp4a":var c=findBox(r,[i])[0],d=findBox(c.subarray(28),["esds"])[0];if(d&&d.length>7){var h=4;if(3!==d[h++])break;h=skipBERInteger(d,h),h+=2;var f=d[h++];if(128&f&&(h+=2),64&f&&(h+=d[h++]),4!==d[h++])break;h=skipBERInteger(d,h);var v=d[h++];if(64!==v)break;if(a+="."+toHex(v),h+=12,5!==d[h++])break;h=skipBERInteger(d,h);var p=d[h++],g=(248&p)>>3;31===g&&(g+=1+((7&p)<<3)+((224&d[h])>>5)),a+="."+g}break;case"hvc1":case"hev1":var y=findBox(n,["hvcC"])[0];if(y&&y.length>12){var m=y[1],E=["","A","B","C"][m>>6],S=31&m,T=readUint32(y,2),k=(32&m)>>5?"H":"L",_=y[12],A=y.subarray(6,12);a+="."+E+S,a+="."+reverse32BitInt(T).toString(16).toUpperCase(),a+="."+k+_;for(var b="",L=A.length;L--;){var R=A[L];if(R||b)b="."+R.toString(16).toUpperCase()+b}a+=b}t=parseSupplementalDoViCodec("hev1"==l?"dvhe":"dvh1",n);break;case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":a=parseSupplementalDoViCodec(a,n)||a;break;case"vp09":var C=findBox(n,["vpcC"])[0];if(C&&C.length>6){var I=C[4],P=C[5],D=C[6]>>4&15;a+="."+addLeadingZero(I)+"."+addLeadingZero(P)+"."+addLeadingZero(D)}break;case"av01":var w=findBox(n,["av1C"])[0];if(w&&w.length>2){var O=w[1]>>>5,x=31&w[1],M=w[2]>>>7?"H":"M",F=(64&w[2])>>6,N=(32&w[2])>>5,U=2===O&&F?N?12:10:F?10:8,B=(16&w[2])>>4,G=(8&w[2])>>3,H=(4&w[2])>>2,$=3&w[2];a+="."+O+"."+addLeadingZero(x)+M+"."+addLeadingZero(U)+"."+B+"."+G+H+$+"."+addLeadingZero(1)+"."+addLeadingZero(1)+"."+addLeadingZero(1)+".0",t=parseSupplementalDoViCodec("dav1",n)}}return{codec:a,encrypted:s,supplemental:t}}function parseSupplementalDoViCodec(e,t){var r=findBox(t,["dvvC"]),n=r.length?r[0]:findBox(t,["dvcC"])[0];if(n){var i=n[2]>>1&127,a=n[2]<<5&32|n[3]>>3&31;return e+"."+addLeadingZero(i)+"."+addLeadingZero(a)}}function reverse32BitInt(e){for(var t=0,r=0;r<32;r++)t|=(e>>r&1)<<31-r;return t>>>0}function skipBERInteger(e,t){for(var r=t+5;128&e[t++]&&t<r;);return t}function toHex(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function addLeadingZero(e){return(e<10?"0":"")+e}function patchEncyptionData(e,t){if(e&&t){var r=t.keyId;16===(null==r?void 0:r.byteLength)&&t.isCommonEncryption&&applyToTencBoxes(e,function(e,t){var n=e.subarray(8,24);n.some(function(e){return 0!==e})||(logger.log("[eme] Patching keyId in 'enc".concat(t?"a":"v",">sinf>>tenc' box: ").concat(arrayToHex(n)," -> ").concat(arrayToHex(r))),e.set(r,8))})}}function parseKeyIdsFromTenc(e){var t=[];return applyToTencBoxes(e,function(e){return t.push(e.subarray(8,24))}),t}function applyToTencBoxes(e,t){findBox(e,["moov","trak"]).forEach(function(e){var r=findBox(e,["mdia","minf","stbl","stsd"])[0];if(r){var n=r.subarray(8),i=findBox(n,["enca"]),a=i.length>0;a||(i=findBox(n,["encv"])),i.forEach(function(e){findBox(a?e.subarray(28):e.subarray(78),["sinf"]).forEach(function(e){var r=parseSinf(e);r&&t(r,a)})})}})}function parseSinf(e){var t=findBox(e,["schm"])[0];if(t){var r=bin2str(t.subarray(4,8));if("cbcs"===r||"cenc"===r){var n=findBox(e,["schi","tenc"])[0];if(n)return n}}}function decodeUtf8UserData(e){return"undefined"==typeof TextDecoder?utf8ArrayToStr(e):(utf8TextDecoder||(utf8TextDecoder=new TextDecoder("utf-8"))).decode(e).replace(/\0/g,"")}function findMoofTrafs(e){for(var t=e.byteLength,r=[],n=0;n<t;){var i=n+8<=t,a=n+4<=t?16777216*e[n]+(e[n+1]<<16|e[n+2]<<8|e[n+3]):readUint32(e,n),s=a>1?n+a:t;if(i&&109===e[n+4]&&111===e[n+5]&&111===e[n+6]&&102===e[n+7])for(var o=Math.min(s,t),l=n+8;l<o;){var u=l+8<=o,c=l+4<=o?16777216*e[l]+(e[l+1]<<16|e[l+2]<<8|e[l+3]):readUint32(e,l),d=c>1?l+c:o;if(u&&116===e[l+4]&&114===e[l+5]&&97===e[l+6]&&102===e[l+7]){for(var h=Math.min(d,o),f=void 0,v=void 0,p=[],g=l+8;g<h;){var y=g+8<=h,m=g+4<=h?16777216*e[g]+(e[g+1]<<16|e[g+2]<<8|e[g+3]):readUint32(e,g),E=m>1?g+m:h;if(y&&116===e[g+4]){var S=Math.min(E,h);102===e[g+5]&&104===e[g+6]&&100===e[g+7]?v||(v=e.subarray(g+8,S)):102===e[g+5]&&100===e[g+6]&&116===e[g+7]?f||(f=e.subarray(g+8,S)):114===e[g+5]&&117===e[g+6]&&110===e[g+7]&&p.push(e.subarray(g+8,S))}g=E}r.push({moofOffset:e.byteOffset+n,tfdt:f,tfhd:v,truns:p})}l=d}n=s}return r}function getSampleData(e,t,r,n){return parseSampleData(e,t,n,!(arguments.length>4&&void 0!==arguments[4])||arguments[4])}function parseSamplesAndTiming(e,t,r,n){var i=arguments.length>4&&void 0!==arguments[4]&&arguments[4],a=[];return{samples:a,sampleData:{includeSampleDetails:i,tracks:parseSampleData(t.samples,r,n,i,{isHEVCFlavor:isHEVC(t.codec),samples:a,timeOffset:e,timescale:t.timescale,trackId:t.id})}}}function parseSampleData(e,t,r,n,i){for(var a={},s=!1,o=findMoofTrafs(e),l=e.byteLength,u=0;u<o.length;u++){var c=o[u],d=c.moofOffset,h=c.tfdt,f=c.tfhd,v=c.truns,p=readUint32(f,4),g=t[p];if(g){var y=a[p]||(a[p]={start:NaN,duration:0,sampleCount:0,trun:[],timescale:g.timescale,type:g.type}),m=void 0;if(h){var E=h[0];m=readUint32(h,4),1===E&&(m===UINT32_MAX?r.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(m*=UINT32_MAX+1,m+=readUint32(h,8))),isFiniteNumber(m)&&(!isFiniteNumber(y.start)||m<y.start)&&(y.start=m),i&&isFiniteNumber(m)&&(i.timeOffset=m/i.timescale)}var S=(null==i?void 0:i.trackId)===p&&g.type===ElementaryStreamTypes.VIDEO,T=g.default,k=16777215&readUint32(f,0),_=(null==T?void 0:T.duration)||0,A=void 0,b=(null==T?void 0:T.sampleSize)||0,L=8;1&k&&(L+=8),2&k&&(L+=4),8&k&&(_=readUint32(f,L),A=f.byteOffset-e.byteOffset+L,L+=4),16&k&&(b=readUint32(f,L));var R=0,C=!!(1&k),I=!C&&!!(131072&k);C?(R=readUint32(f,8),R*=Math.pow(2,32),R+=readUint32(f,12)):I&&(R=d);for(var P=m||0,D=0,w=_,O=0;O<v.length;O++){var x=v[O],M=readUint32(x,4),F=y.sampleCount;y.sampleCount+=M;var N=1&x[3],U=0,B=4&x[3],G=1&x[2],H=2&x[2],$=4&x[2],K=8&x[2],V=8;if(N&&(U=readSint32(x,V),V+=4),B)1&x[V+1]||void 0!==y.keyFrameIndex||(y.keyFrameIndex=F),V+=4;var j=R+U;if(n||0!==x[1]||6!==x[2]||1!==x[3]){var q=void 0,W=void 0;n&&(W={sampleOffset:j,samples:q=[],defaultSampleDurationOffset:A},j<=l&&y.trun.push(W));for(var Y=void 0,z=0;z<M;z++){var X=void 0;G?(n&&(X=x.byteOffset-e.byteOffset+V),w=readUint32(x,V),V+=4):w=_,H?(Y=readUint32(x,V),V+=4):Y=b;var Q=void 0,J=void 0;$&&(J=1&x[V+1]?1:0,n&&(Q={isNonSync:J,dependsOn:1==(3&x[V])?1:2}),V+=4);var Z=0;if(K)Z=0===x[0]?readUint32(x,V):readSint32(x,V),V+=4;if(S){for(var ee=j,te=0;te<Y;){var re=readUint32(e,ee);ee+=4,isSEIMessage(i.isHEVCFlavor,e[ee])&&parseSEIMessageFromNALu(e.subarray(ee,ee+re),i.isHEVCFlavor?2:1,i.timeOffset+Z/i.timescale,i.samples),ee+=re,te+=re+4}i.timeOffset+=w/i.timescale}if((j+=Y)<=l){W&&void 0!==X&&(W.lastSampleDurationOffset=X),0===J&&void 0===y.keyFrameIndex&&(y.keyFrameIndex=z,y.keyFrameStart=P);var ne=P+Z;(!isFiniteNumber(y.ptsMin)||ne<y.ptsMin)&&(y.ptsMin=ne),(!isFiniteNumber(y.ptsMax)||ne+w>y.ptsMax)&&(y.ptsMax=ne+w),q&&(q[z]={cts:Z,duration:w,flags:Q,size:Y})}P+=w,D+=w}!D&&_&&(D+=_*M)}else{for(var ie,ae,se=P,oe=j,le=V,ue=-1,ce=0,de=0,he=null!=(ie=null==i?void 0:i.timeOffset)?ie:0,fe=_/(null!=(ae=null==i?void 0:i.timescale)?ae:1),ve=!0===(null==i?void 0:i.isHEVCFlavor),pe=ve?2:1,ge=0;ge<M;ge++){var ye=0===x[V]?x[V+1]<<16|x[V+2]<<8|x[V+3]:readUint32(x,V),me=-1===ue&&void 0===y.keyFrameIndex&&!(1&x[V+5]);V+=8;var Ee=j+ye;if(S){if(ye>0){var Se=j;do{var Te=0===e[Se]?e[Se+1]<<16|e[Se+2]<<8|e[Se+3]:readUint32(e,Se),ke=e[Se+=4],_e=ve?ke>>1&63:31&ke;(ve?39===_e||40===_e:6===_e)&&parseSEIMessageFromNALu(e.subarray(Se,Se+Te),pe,he,i.samples),Se+=Te}while(Se<Ee)}he+=fe}j=Ee,me&&(ue=ge,ce=j)}if(j<=l)de=M;else for(var Ae=oe,be=le,Le=0;Le<M;Le++){if((Ae+=0===x[be]?x[be+1]<<16|x[be+2]<<8|x[be+3]:readUint32(x,be))>l)break;de=Le+1,be+=8}if(S&&(i.timeOffset=he),-1!==ue&&ce<=l&&void 0===y.keyFrameIndex&&(y.keyFrameIndex=ue,y.keyFrameStart=se+ue*_),de){(!isFiniteNumber(y.ptsMin)||se<y.ptsMin)&&(y.ptsMin=se);var Re=se+de*_;(!isFiniteNumber(y.ptsMax)||Re>y.ptsMax)&&(y.ptsMax=Re)}var Ce=_*M;P=se+Ce,D+=Ce}}y.duration+=D,y.duration&&(s=!0)}}if(!s){for(var Ie=1/0,Pe=0,De=findBox(e,["sidx"]),we=0;we<De.length;we++){var Oe=parseSegmentIndex(De[we]);if(null!=Oe&&Oe.references){Ie=Math.min(Ie,Oe.earliestPresentationTime/Oe.timescale);var xe=Oe.references.reduce(function(e,t){return e+t.info.duration||0},0);Pe=Math.max(Pe,xe+Oe.earliestPresentationTime/Oe.timescale)}}Pe&&isFiniteNumber(Pe)&&Object.keys(a).forEach(function(e){a[e].duration||(a[e].duration=Pe*a[e].timescale-a[e].start)})}return a}function segmentValidRange(e){var t={valid:null,remainder:null},r=findBox(e,["moof"]);if(r.length<2)return t.remainder=e,t;var n=r[r.length-1];return t.valid=e.slice(0,n.byteOffset-8),t.remainder=e.slice(n.byteOffset-8),t}function appendUint8Array(e,t){var r=new Uint8Array(e.length+t.length);return r.set(e),r.set(t,e.length),r}function parseSamples(e,t){var r=[],n=t.samples,i=t.timescale,a=t.id,s=!1;return findBox(n,["moof"]).map(function(o){var l=o.byteOffset-8;findBox(o,["traf"]).map(function(o){var u=findBox(o,["tfdt"]).map(function(e){var t=e[0],r=readUint32(e,4);return 1===t&&(r*=Math.pow(2,32),r+=readUint32(e,8)),r/i})[0];return void 0!==u&&(e=u),findBox(o,["tfhd"]).map(function(u){var c=readUint32(u,4),d=16777215&readUint32(u,0),h=!!(1&d),f=0,v=!!(2&d),p=!!(8&d),g=0,y=!!(16&d),m=0,E=!!(32&d),S=!h&&!!(131072&d),T=8;c===a&&(h?(f=readUint32(u,T),T+=4,f*=Math.pow(2,32),f+=readUint32(u,T),T+=4):S&&(f=l),v&&(T+=4),p&&(g=readUint32(u,T),T+=4),y&&(m=readUint32(u,T),T+=4),E&&(T+=4),"video"===t.type&&(s=isHEVC(t.codec)),findBox(o,["trun"]).map(function(a){var o=a[0],l=16777215&readUint32(a,0),u=!!(1&l),c=0,d=!!(4&l),h=!!(256&l),v=0,p=!!(512&l),y=0,E=!!(1024&l),S=!!(2048&l),T=0,k=readUint32(a,4),_=8;u&&(c=readUint32(a,_),_+=4),d&&(_+=4);for(var A=f+c,b=0;b<k;b++){if(h?(v=readUint32(a,_),_+=4):v=g,p?(y=readUint32(a,_),_+=4):y=m,E&&(_+=4),S&&(T=0===o?readUint32(a,_):readSint32(a,_),_+=4),t.type===ElementaryStreamTypes.VIDEO)for(var L=0;L<y;){var R=readUint32(n,A);if(isSEIMessage(s,n[A+=4]))parseSEIMessageFromNALu(n.subarray(A,A+R),s?2:1,e+T/i,r);A+=R,L+=R+4}e+=v/i}}))})})}),r}function isHEVC(e){if(!e)return!1;var t=e.substring(0,4);return"hvc1"===t||"hev1"===t||"dvh1"===t||"dvhe"===t}function isSEIMessage(e,t){if(e){var r=t>>1&63;return 39===r||40===r}return 6===(31&t)}function parseSEIMessageFromNALu(e,t,r,n){var i=discardEPB(e),a=0;a+=t;for(var s=0,o=0,l=0;a<i.length;){s=0;do{if(a>=i.length)break;s+=l=i[a++]}while(255===l);o=0;do{if(a>=i.length)break;o+=l=i[a++]}while(255===l);var u=i.length-a,c=a;if(o<u)a+=o;else if(o>u){logger.error("Malformed SEI payload. ".concat(o," is too small, only ").concat(u," bytes left to parse."));break}if(4===s){if(181===i[c++]){var d=readUint16(i,c);if(c+=2,49===d){var h=readUint32(i,c);if(c+=4,1195456820===h){var f=i[c++];if(3===f){var v=i[c++],p=64&v,g=p?2+3*(31&v):0,y=new Uint8Array(g);if(p){y[0]=v;for(var m=1;m<g;m++)y[m]=i[c++]}n.push({type:f,payloadType:s,pts:r,bytes:y})}}}}}else if(5===s&&o>16){for(var E=[],S=0;S<16;S++){var T=i[c++].toString(16);E.push(1==T.length?"0"+T:T),3!==S&&5!==S&&7!==S&&9!==S||E.push("-")}for(var k=o-16,_=new Uint8Array(k),A=0;A<k;A++)_[A]=i[c++];n.push({payloadType:s,pts:r,uuid:E.join(""),userData:decodeUtf8UserData(_),userDataBytes:_})}}}function discardEPB(e){for(var t,r=e.byteLength,n=e.indexOf(3,3);-1!==n;)0===e[n-1]&&0===e[n-2]&&(t||(t=[])).push(n),n=e.indexOf(3,n+1);if(!t)return e;for(var i=r-t.length,a=new Uint8Array(i),s=0,o=0,l=0;l<i;o++,l++)o===t[s]&&(o++,s++),a[l]=e[o];return a}function parseEmsg(e){var t,r=e[0],n="",i="",a=0,s=0,o=0,l=0,u=4;if(0===r){var c=readCString(e,u),d=null!==c?readCString(e,u+c.length):null;null!==c&&null!==d?(n=c,i=d,a=readUint32(e,u+=c.length+d.length),s=readUint32(e,u+=4),o=readUint32(e,u+=4),l=readUint32(e,u+=4),u+=4):(logger.warn("Unterminated ".concat(null===c?"scheme_id_uri":"value"," in parsing emsg box: version 0 box ends inside a string, dropping all of its fields")),u=e.length)}else if(1===r){a=readUint32(e,u);var h=readUint32(e,u+=4),f=readUint32(e,u+=4);u+=4,t=Math.pow(2,32)*h+f,isSafeInteger(t)||(t=Number.MAX_SAFE_INTEGER,logger.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=readUint32(e,u),l=readUint32(e,u+=4);var v=readCString(e,u+=4),p=null!==v?readCString(e,u+v.length):null;null!==v&&(n=v,u+=v.length),null!==p?(i=p,u+=p.length):(logger.warn("Unterminated ".concat(null===v?"scheme_id_uri":"value"," in parsing emsg box: version 1 box ends inside a string, dropping its ").concat(null===v?"strings and payload":"value and payload")),u=e.length)}return{schemeIdUri:n,value:i,timeScale:a,presentationTime:t,presentationTimeDelta:s,eventDuration:o,id:l,payload:e.subarray(u,e.byteLength)}}function mp4Box(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];for(var i=r.length,a=8,s=i;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<i;s++)o.set(r[s],a),a+=r[s].byteLength;return o}function mp4pssh(e,t,r){if(16!==e.byteLength)throw new RangeError("Invalid system id");var n,i;n=new Uint8Array,i=new Uint8Array;var a=new Uint8Array(4);return r.byteLength>0&&new DataView(a.buffer).setUint32(0,r.byteLength,!1),mp4Box([112,115,115,104],new Uint8Array([0,0,0,0]),e,i,n,a,r)}function parseMultiPssh(e){var t=[];if(e instanceof ArrayBuffer)for(var r=e.byteLength,n=0;n+32<r;){var i=parsePssh(new DataView(e,n));t.push(i),n+=i.size}return t}function parseWidevinePsshKids(e){for(var t=[],r=0;r<e.length;){var n=e[r++],i=7&n;if(0!==i)if(2===i){for(var a=0,s=0,o=128;128&o;s+=7)a|=(127&(o=e[r++]))<<s;if(n>>3==2)if(32===a){for(var l=new Uint8Array(16),u=0;u<16;u++)l[u]=parseInt(String.fromCharCode(e[r+2*u],e[r+2*u+1]),16);t.push(l)}else 16===a&&t.push(e.subarray(r,r+16));r+=a}else r+=1===i?8:4;else for(;128&e[r++];);}return t}function parsePssh(e){var t=e.getUint32(0),r=e.byteOffset,n=e.byteLength;if(n<t)return{offset:r,size:n};if(1886614376!==e.getUint32(4))return{offset:r,size:t};var i=e.getUint32(8)>>>24;if(0!==i&&1!==i)return{offset:r,size:t};var a,s=e.buffer,o=arrayToHex(new Uint8Array(s,r+12,16)),l=null,u=0;if(0===i)u=28;else{var c=e.getUint32(28);if(!c||n<32+16*c)return{offset:r,size:t};l=[];for(var d=0;d<c;d++)l.push(new Uint8Array(s,r+32+16*d,16));u=32+16*c}if(!u)return{offset:r,size:t};var h=e.getUint32(u);return t-32<h?{offset:r,size:t}:(a=new Uint8Array(s,r+u+4,h),0===i&&(l=parseWidevinePsshKids(a)),{version:i,systemId:o,kids:l,data:a,offset:r,size:t})}var chromeVersion,firefoxVersion,safariVersion,ua=getNavigator("userAgent"),vendor=getNavigator("vendor");function getNavigator(e){try{return navigator[e]||""}catch(t){}return""}function userAgentSafariVersion(){if(void 0===safariVersion){var e=ua.match(/Safari\/(\d+)/i);safariVersion=e?parseInt(e[1]):0}return safariVersion}function userAgentChromeVersion(){if(void 0===chromeVersion){var e=ua.match(/Chrome\/(\d+)/i);chromeVersion=e?parseInt(e[1]):0}return chromeVersion}function userAgentFirefoxVersion(){if(void 0===firefoxVersion){var e=ua.match(/Firefox\/(\d+)/i);firefoxVersion=e?parseInt(e[1]):0}return firefoxVersion}function userAgentHevcSupportIsInaccurate(){return/\(Windows.+Firefox\//i.test(ua)}function userAgentIsIOSLike(){return vendor.indexOf("Apple")>-1||/iPhone|iPad|iPod/.test(ua)}function userAgentIsAndroidLike(){return/Android/.test(ua)}var sampleEntryCodesISO={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1},image:{mjpg:1}};function isCodecType(e,t){var r=sampleEntryCodesISO[t];return!!r&&!!r[e.slice(0,4)]}function areCodecsMediaSourceSupported(e,t){var r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return!e.split(",").some(function(e){return!isCodecMediaSourceSupported(e,t,r)})}function isCodecMediaSourceSupported(e,t){var r,n=_getMediaSource2(!(arguments.length>2&&void 0!==arguments[2])||arguments[2]);return null!=(r=null==n?void 0:n.isTypeSupported(mimeTypeForCodec(e,t)))&&r}function mimeTypeForCodec(e,t){return"".concat(t,"/mp4;codecs=").concat(e)}function videoCodecPreferenceValue(e){if(e){var t=e.substring(0,4);return sampleEntryCodesISO.video[t]}return 2}function codecsSetSelectionPreferenceValue(e){var t=userAgentHevcSupportIsInaccurate();return e.split(",").reduce(function(e,r){var n=t&&isHEVC(r)?9:sampleEntryCodesISO.video[r];return n?(2*n+e)/(e?3:2):(sampleEntryCodesISO.audio[r]+e)/(e?2:1)},0)}var CODEC_COMPATIBLE_NAMES={};function getCodecCompatibleNameLower(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(CODEC_COMPATIBLE_NAMES[e])return CODEC_COMPATIBLE_NAMES[e];for(var r={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e],n=0;n<r.length;n++){var i;if(isCodecMediaSourceSupported(r[n],"audio",t))return CODEC_COMPATIBLE_NAMES[e]=r[n],r[n];if("mp3"===r[n]&&null!=(i=_getMediaSource2(t))&&i.isTypeSupported("audio/mpeg"))return""}return e}var AUDIO_CODEC_REGEXP=/flac|opus|mp4a\.40\.34/i;function getCodecCompatibleName(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return e.replace(AUDIO_CODEC_REGEXP,function(e){return getCodecCompatibleNameLower(e.toLowerCase(),t)})}function replaceVideoCodec(e,t){var r=[];if(e)for(var n=e.split(","),i=0;i<n.length;i++)isCodecType(n[i],"video")||r.push(n[i]);return t&&r.push(t),r.join(",")}function pickMostCompleteCodecName(e,t){if(e&&(e.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e))&&(isCodecSupportedAsType(e,"audio")||isCodecSupportedAsType(e,"video")))return e;if(t){var r=t.split(",");if(r.length>1){if(e)for(var n=r.length;n--;)if(r[n].substring(0,4)===e.substring(0,4))return r[n];return r[0]}}return t||e}function isCodecSupportedAsType(e,t){return isCodecType(e,t)&&isCodecMediaSourceSupported(e,t)}function convertAVC1ToAVCOTI(e){for(var t=e.split(","),r=0;r<t.length;r++){var n=t[r].split(".");n.length>2&&"avc1"===n[0]&&(t[r]="avc1.".concat(parseInt(n[1]).toString(16)).concat(("000"+parseInt(n[2]).toString(16)).slice(-4)))}return t.join(",")}function fillInMissingAV01Params(e){if(e.startsWith("av01.")){for(var t=e.split("."),r=["0","111","01","01","01","0"],n=t.length;n>4&&n<10;n++)t[n]=r[n-4];return t.join(".")}return e}function getM2TSSupportedAudioTypes(e){var t=_getMediaSource2(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 getCodecsForMimeType(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}var supportedResult={supported:!0,powerEfficient:!0,smooth:!0},unsupportedResult={supported:!1,smooth:!1,powerEfficient:!1},SUPPORTED_INFO_DEFAULT={supported:!0,configurations:[],decodingInfoResults:[supportedResult]};function getUnsupportedResult(e,t){return{supported:!1,configurations:t,decodingInfoResults:[unsupportedResult],error:e}}function requiresMediaCapabilitiesDecodingInfo(e,t,r,n,i,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 n=t.groups[r];if(!n)throw new Error("Audio track group ".concat(r," not found"));Object.keys(n.channels).forEach(function(t){e[t]=(e[t]||0)+n.channels[t]})}return e},{2:0})}catch(h){return!0}return void 0!==s&&(s.split(",").some(function(e){return isHEVC(e)})||e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(n,30)||"SDR"!==e.videoRange&&e.videoRange!==r||e.bitrate>Math.max(i,8e6))||!!d&&isFiniteNumber(c)&&Object.keys(d).some(function(e){return parseInt(e)>c})}function getMediaDecodingInfoPromise(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=e.videoCodec;if(!i&&!e.audioCodec||!r)return Promise.resolve(SUPPORTED_INFO_DEFAULT);for(var a=[],s=makeVideoConfigurations(e),o=s.length,l=makeAudioConfigurations(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(i){var f=navigator.userAgent;if(i.split(",").some(function(e){return isHEVC(e)})&&userAgentHevcSupportIsInaccurate())return Promise.resolve(getUnsupportedResult(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=getMediaDecodingInfoKey(e);return n[t]||(n[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 makeVideoConfigurations(e){var t,r=null==(t=e.videoCodec)?void 0:t.split(","),n=getVariantDecodingBitrate(e),i=e.width||640,a=e.height||480,s=e.frameRate||30,o=e.videoRange.toLowerCase();return r?r.map(function(e){var t={contentType:mimeTypeForCodec(fillInMissingAV01Params(e),"video"),width:i,height:a,bitrate:n,framerate:s};return"sdr"!==o&&(t.transferFunction=o),t}):[]}function makeAudioConfigurations(e,t,r){var n,i=null==(n=e.audioCodec)?void 0:n.split(","),a=getVariantDecodingBitrate(e);return i&&e.audioGroups?e.audioGroups.reduce(function(e,n){var s,o=n?null==(s=t.groups[n])?void 0:s.tracks:null;return o?o.reduce(function(e,t){if(t.groupId===n){var s=parseFloat(t.channels||"");i.forEach(function(t){var n={contentType:mimeTypeForCodec(t,"audio"),bitrate:r?estimatedAudioBitrate(t,a):a};s&&(n.channels=""+s),e.push(n)})}return e},e):e},[]):[]}function estimatedAudioBitrate(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 getVariantDecodingBitrate(e){return 1e3*Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)/1e3)||1}function getMediaDecodingInfoKey(e){var t="",r=e.audio,n=e.video;if(n){var i=getCodecsForMimeType(n.contentType);t+="".concat(i,"_r").concat(n.height,"x").concat(n.width,"f").concat(Math.ceil(n.framerate)).concat(n.transferFunction||"sd","_").concat(Math.ceil(n.bitrate/1e5))}if(r){var a=getCodecsForMimeType(r.contentType);t+="".concat(n?"_":"").concat(a,"_c").concat(r.channels)}return t}function setQueryParam(e,t,r){var n=encodeURIComponent(t),i="".concat(n,"=").concat(encodeURIComponent(r)),a=!1,s=[];e.search.substring(1).split("&").forEach(function(e){e===n||e.startsWith(n+"=")?a||(s.push(i),a=!0):e&&s.push(e)}),a||s.push(i),e.search=s.join("&")}var HdcpLevels=["NONE","TYPE-0","TYPE-1",null];function isHdcpLevel(e){return HdcpLevels.indexOf(e)>-1}var VideoRangeValues=["SDR","PQ","HLG"];function isVideoRange(e){return!!e&&VideoRangeValues.indexOf(e)>-1}var HlsSkip={No:"",Yes:"YES",v2:"v2"};function getSkipValue(e){var t=e.canSkipUntil,r=e.canSkipDateRanges,n=e.age;return t&&n<t/2?r?HlsSkip.v2:HlsSkip.Yes:HlsSkip.No}var HlsUrlParameters=function(){return _createClass(function e(t,r,n){_classCallCheck(this,e),this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=r,this.skip=n},[{key:"addDirectives",value:function(e){var t=new self.URL(e);return void 0!==this.msn&&setQueryParam(t,"_HLS_msn",this.msn.toString()),void 0!==this.part&&setQueryParam(t,"_HLS_part",this.part.toString()),this.skip&&setQueryParam(t,"_HLS_skip",this.skip),t.href}}])}(),Level=function(){return _createClass(function e(t){if(_classCallCheck(this,e),this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.imageCodec=void 0,this.iframes=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loadErrorTime=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[t.url],this._attrs=[t.attrs],this.bitrate=t.bitrate,t.details&&(this.details=t.details),this.id=t.id||0,this.name=t.name,this.width=t.width||0,this.height=t.height||0,this.frameRate=t.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=t.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,"imageCodec"in t&&(this.imageCodec=t.imageCodec),this.codecSet=[t.videoCodec,t.audioCodec].filter(function(e){return!!e}).map(function(e){return e.substring(0,4)}).join(","),"supplemental"in t){var r;this.supplemental=t.supplemental;var n=null==(r=t.supplemental)?void 0:r.videoCodec;n&&n!==t.videoCodec&&(this.codecSet+=",".concat(n.substring(0,4)))}"iframes"in t&&t.iframes?this.iframes=!0:(this.addGroupId("audio",t.attrs.AUDIO),this.addGroupId("text",t.attrs.SUBTITLES))},[{key:"maxBitrate",get:function(){return Math.max(this.realBitrate,this.bitrate)}},{key:"averageBitrate",get:function(){return this._avgBitrate||this.realBitrate||this.bitrate}},{key:"attrs",get:function(){return this._attrs[0]}},{key:"codecs",get:function(){return this.attrs.CODECS||""}},{key:"pathwayId",get:function(){return this.attrs["PATHWAY-ID"]||"."}},{key:"videoRange",get:function(){return this.attrs["VIDEO-RANGE"]||"SDR"}},{key:"score",get:function(){return this.attrs.optionalFloat("SCORE",0)}},{key:"uri",get:function(){return this.url[0]||""}},{key:"hasAudioGroup",value:function(e){return hasGroup(this._audioGroups,e)}},{key:"hasSubtitleGroup",value:function(e){return hasGroup(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 n=this._subtitleGroups;n||(n=this._subtitleGroups=[]),-1===n.indexOf(t)&&n.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 hasGroup(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}function isHdrSupported(){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}function getVideoSelectionOptions(e,t){var r=!1,n=[];if(e&&(r="SDR"!==e,n=[e]),t){var i="SDR"!==(n=t.allowedVideoRanges||VideoRangeValues.slice(0)).join("")&&!t.videoCodec;(r=void 0!==t.preferHDR?t.preferHDR:i&&isHdrSupported())||(n=["SDR"])}return{preferHDR:r,allowedVideoRanges:n}}var omitCircularRefsReplacer=function(e){var t=new WeakSet;return function(r,n){if(e&&(n=e(r,n)),"object"===_typeof(n)&&null!==n){if(t.has(n))return;t.add(n)}return n}},stringify=function(e,t){return JSON.stringify(e,omitCircularRefsReplacer(t))};function getStartCodecTier(e,t,r,n,i){for(var a=Object.keys(e),s=null==n?void 0:n.channels,o=null==n?void 0:n.audioCodec,l=null==i?void 0:i.videoCodec,u=s&&2===parseInt(s),c=!1,d=!1,h=1/0,f=1/0,v=1/0,p=1/0,g=0,y=[],m=getVideoSelectionOptions(t,i),E=m.preferHDR,S=m.allowedVideoRanges,T=function(){var t=e[a[k]];c||(c=t.channels[2]>0),h=Math.min(h,t.minHeight),f=Math.min(f,t.minFramerate),v=Math.min(v,t.minBitrate);var r=S.filter(function(e){return t.videoRanges[e]>0});r.length>0&&(d=!0)},k=a.length;k--;)T();h=isFiniteNumber(h)?h:0,f=isFiniteNumber(f)?f:0;var _=Math.max(1080,h),A=Math.max(30,f);v=isFiniteNumber(v)?v:r,r=Math.max(v,r),d||(t=void 0);var b=a.length>1,L=a.reduce(function(t,n){var i=e[n];if(n===t)return t;if(y=d?S.filter(function(e){return i.videoRanges[e]>0}):[],b){if(i.minBitrate>r)return logStartCodecCandidateIgnored(n,"min bitrate of ".concat(i.minBitrate," > current estimate of ").concat(r)),t;if(!i.hasDefaultAudio)return logStartCodecCandidateIgnored(n,"no renditions with default or auto-select sound found"),t;if(o&&n.indexOf(o.substring(0,4))%5!=0)return logStartCodecCandidateIgnored(n,'audio codec preference "'.concat(o,'" not found')),t;if(s&&!u){if(!i.channels[s])return logStartCodecCandidateIgnored(n,"no renditions with ".concat(s," channel sound found (channels options: ").concat(Object.keys(i.channels),")")),t}else if((!o||u)&&c&&0===i.channels[2])return logStartCodecCandidateIgnored(n,"no renditions with stereo sound found"),t;if(i.minHeight>_)return logStartCodecCandidateIgnored(n,"min resolution of ".concat(i.minHeight," > maximum of ").concat(_)),t;if(i.minFramerate>A)return logStartCodecCandidateIgnored(n,"min framerate of ".concat(i.minFramerate," > maximum of ").concat(A)),t;if(!y.some(function(e){return i.videoRanges[e]>0}))return logStartCodecCandidateIgnored(n,"no variants with VIDEO-RANGE of ".concat(stringify(y)," found")),t;if(l&&n.indexOf(l.substring(0,4))%5!=0)return logStartCodecCandidateIgnored(n,'video codec preference "'.concat(l,'" not found')),t;if(i.maxScore<g)return logStartCodecCandidateIgnored(n,"max score of ".concat(i.maxScore," < selected max of ").concat(g)),t}return t&&(codecsSetSelectionPreferenceValue(n)>=codecsSetSelectionPreferenceValue(t)||i.fragmentError>e[t].fragmentError)?t:(p=i.minIndex,g=i.maxScore,n)},void 0);return{codecSet:L,videoRanges:y,preferHDR:E,minFramerate:f,minBitrate:v,minIndex:p}}function logStartCodecCandidateIgnored(e,t){logger.log('[abr] start candidates with "'.concat(e,'" ignored because ').concat(t))}function getAudioTracksByGroup(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 n=t.channels||"2";return r.channels[n]=(r.channels[n]||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 getCodecTiers(e,t,r,n){return e.slice(r,n+1).reduce(function(e,r,n){if(!r.codecSet)return e;var i=r.audioGroups,a=e[r.codecSet];a||(e[r.codecSet]=a={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:n,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!i,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,n),a.maxScore=Math.max(a.maxScore,r.score),a.fragmentError+=r.fragmentError,a.videoRanges[r.videoRange]=(a.videoRanges[r.videoRange]||0)+1,i&&i.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},{})}function getBasicSelectionOption(e){return e?{lang:e.lang,assocLang:e.assocLang,characteristics:e.characteristics,channels:e.channels,audioCodec:e.audioCodec}:e}function findMatchingOption(e,t,r){if("attrs"in e){var n=t.indexOf(e);if(-1!==n)return n}for(var i=0;i<t.length;i++){if(matchesOption(e,t[i],r))return i}return-1}function matchesOption(e,t,r){var n=e.groupId,i=e.name,a=e.lang,s=e.assocLang,o=e.default,l=e.forced;return(void 0===n||t.groupId===n)&&(void 0===i||t.name===i)&&(void 0===a||languagesMatch(a,t.lang))&&(void 0===s||t.assocLang===s)&&(void 0===o||t.default===o)&&(void 0===l||t.forced===l)&&(!("characteristics"in e)||characteristicsMatch(e.characteristics||"",t.characteristics))&&(void 0===r||r(e,t))}function languagesMatch(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"--";return e.length===t.length?e===t:e.startsWith(t)||t.startsWith(e)}function characteristicsMatch(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",r=e.split(","),n=t.split(",");return r.length===n.length&&!r.some(function(e){return-1===n.indexOf(e)})}function audioMatchPredicate(e,t){var r=e.audioCodec,n=e.channels;return!(void 0!==r&&(t.audioCodec||"").substring(0,4)!==r.substring(0,4)||void 0!==n&&n!==(t.channels||"2"))}function findClosestLevelWithAudioGroup(e,t,r,n,i){var a=t[n],s=t.reduce(function(e,t,r){var n=t.uri;return(e[n]||(e[n]=[])).push(r),e},{}),o=s[a.uri];o.length>1&&(n=Math.max.apply(Math,o));var l=a.videoRange,u=a.frameRate,c=a.codecSet.substring(0,4),d=searchDownAndUpList(t,n,function(t){if(t.videoRange!==l||t.frameRate!==u||t.codecSet.substring(0,4)!==c)return!1;var n=t.audioGroups,a=r.filter(function(e){return inGroupOrNone(e.groupId,n)});return findMatchingOption(e,a,i)>-1});return d>-1?d:searchDownAndUpList(t,n,function(t){var n=t.audioGroups,a=r.filter(function(e){return inGroupOrNone(e.groupId,n)});return findMatchingOption(e,a,i)>-1})}function searchDownAndUpList(e,t,r){for(var n=t;n>-1;n--)if(r(e[n]))return n;for(var i=t+1;i<e.length;i++)if(r(e[i]))return i;return-1}function useAlternateAudio(e,t){var r;return!!e&&e!==(null==(r=t.loadLevelObj)?void 0:r.uri)}function inGroupOrNone(e,t){return!t||-1!==t.indexOf(e)}function getVideoPreference(e,t){if(t||e){var r=_extends({},t);return e&&(e.videoCodec&&(r.videoCodec=e.videoCodec),e.videoRange&&(r.allowedVideoRanges=[e.videoRange])),r}}var AbrController=function(){function e(t){var r;return _classCallCheck(this,e),(r=_callSuper(this,e,["abr",t.logger])).hls=void 0,r.lastLevelLoadSec=0,r.lastLoadedFragLevel=-1,r.firstSelection=-1,r.firstAutoFloor=-1,r._nextAutoLevel=-1,r.nextAutoLevelKey="",r.audioTracksByGroup=null,r.codecTiers=null,r.timer=-1,r.fragCurrent=null,r.partCurrent=null,r.bitrateTestDelay=0,r.rebufferNotice=-1,r.supportedCache={},r.bwEstimator=void 0,r._abandonRulesCheck=function(e){var t,n=r,i=n.fragCurrent,a=n.partCurrent,s=n.hls;if(s){var o=s.autoLevelEnabled,l=s.media;if(i&&l){var u=performance.now(),c=a?a.stats:i.stats,d=a?a.duration:i.duration,h=u-c.loading.start,f=s.minAutoLevel,v=i.level,p=r._nextAutoLevel;if(c.aborted||c.loaded&&c.loaded===c.total||v<=f)return r.clearTimer(),void(r._nextAutoLevel=-1);if(o){var g=p>-1&&p!==v,y=!!e||g;if(y||!l.paused&&l.playbackRate&&l.readyState){var m=s.mainForwardBufferInfo;if(y||null!==m){var E=r.bwEstimator.getEstimateTTFB(),S=Math.abs(l.playbackRate);if(!(h<=Math.max(E,d/(2*S)*1e3))){var T=m?m.len/S:0,k=c.loading.first?c.loading.first-c.loading.start:-1,_=c.loaded&&k>-1,A=r.getBwEstimate(),b=s.levels,L=b[v],R=Math.max(c.loaded,Math.round(d*(i.bitrate||L.averageBitrate)/8)),C=_?h-k:h;C<1&&_&&(C=Math.min(h,8*c.loaded/A));var I=_?1e3*c.loaded/C:0,P=E/1e3,D=I?(R-c.loaded)/I:8*R/A+P;if(!(D<=T)){var w,O=I?8*I:A,x=!0===(null==(t=(null==e?void 0:e.details)||s.latestLevelDetails)?void 0:t.live),M=s.config.abrBandWidthUpFactor,F=Number.POSITIVE_INFINITY;for(w=v-1;w>f;w--){var N=b[w].maxBitrate,U=!b[w].details||x;if((F=r.getTimeToLoadFrag(P,O,d*N,U))<Math.min(T,d+P))break}if(!(F>=D||F>10*d)){_?r.bwEstimator.sample(h-Math.min(E,k),c.loaded):r.bwEstimator.sampleTTFB(h);var B=b[w].maxBitrate;r.getBwEstimate()*M>B&&(r.firstAutoFloor=Math.min(w,s.firstLevel),r.resetEstimator(B));var G=r.findBestLevel(B,f,w,0,T,1,1);G>-1&&(w=G),r.warn("Fragment ".concat(i.sn).concat(a?" part "+a.index:""," of level ").concat(v," is loading too slowly;\n Fragment duration: ").concat(i.duration.toFixed(3),"\n Time to underbuffer: ").concat(T.toFixed(3)," s\n Estimated load time for current fragment: ").concat(D.toFixed(3)," s\n Estimated load time for down switch fragment: ").concat(F.toFixed(3)," s\n TTFB estimate: ").concat(0|k," ms\n Current BW estimate: ").concat(isFiniteNumber(A)?0|A:"Unknown"," bps\n New BW estimate: ").concat(0|r.getBwEstimate()," bps\n Switching to level ").concat(w," @ ").concat(0|B," bps")),s.nextLoadLevel=s.nextAutoLevel=w,r.clearTimer();var H=function(){r.clearTimer();var e=r.hls;if(r.fragCurrent===i&&e.loadLevel===w&&w>0){var t=r.getStarvationDelay();if(r.warn("Aborting inflight request ".concat(w>0?"and switching down":"","\n Fragment duration: ").concat(i.duration.toFixed(3)," s\n Time to underbuffer: ").concat(t.toFixed(3)," s")),i.abortRequests(),r.fragCurrent=r.partCurrent=null,w>f){var n=r.findBestLevel(e.levels[f].bitrate,f,w,0,t,1,1);-1===n&&(n=f),e.nextLoadLevel=e.nextAutoLevel=n,r.firstAutoFloor=Math.min(n,e.firstLevel),r.resetEstimator(e.levels[n].bitrate)}}};g||D>2*F?H():r.timer=self.setInterval(H,1e3*F),s.trigger(Events$2.FRAG_LOAD_EMERGENCY_ABORTED,{frag:i,part:a,stats:c})}}}}}}}}},r.hls=t,r.bwEstimator=r.initEstimator(),r.registerListeners(),r}return _inherits(e,Logger$1),_createClass(e,[{key:"resetEstimator",value:function(e){this.hls&&(e&&(this.log("setting initial bwe to ".concat(e)),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator())}},{key:"initEstimator",value:function(){var e=this.hls.config;return new EwmaBandWidthEstimator(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}},{key:"registerListeners",value:function(){var e=this.hls;e.on(Events$2.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events$2.FRAG_LOADING,this.onFragLoading,this),e.on(Events$2.FRAG_LOADED,this.onFragLoaded,this),e.on(Events$2.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Events$2.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Events$2.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Events$2.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Events$2.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(Events$2.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(Events$2.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events$2.FRAG_LOADING,this.onFragLoading,this),e.off(Events$2.FRAG_LOADED,this.onFragLoaded,this),e.off(Events$2.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Events$2.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Events$2.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Events$2.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Events$2.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(Events$2.ERROR,this.onError,this))}},{key:"destroy",value:function(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.audioTracksByGroup=this.codecTiers=this.fragCurrent=this.partCurrent=null}},{key:"onManifestLoading",value:function(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}},{key:"onLevelsUpdated",value:function(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}},{key:"onMaxAutoLevelUpdated",value:function(){this.firstSelection=-1,this.nextAutoLevelKey=""}},{key:"onFragLoading",value:function(e,t){var r=t.frag;if(!this.ignoreFragment(r)){var n;if(!r.bitrateTest)this.fragCurrent=r,this.partCurrent=null!=(n=t.part)?n: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 ErrorDetails.BUFFER_ADD_CODEC_ERROR:case ErrorDetails.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case ErrorDetails.FRAG_LOAD_TIMEOUT:var r=t.frag,n=this.fragCurrent,i=this.partCurrent;if(r&&fragmentsAreEqual(r,n)){var a=performance.now(),s=i?i.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,n){return e+r/t+(n?e+this.lastLevelLoadSec:0)}},{key:"onLevelLoaded",value:function(e,t){var r=this.hls.config,n=t.stats.loading,i=n.end-n.first;isFiniteNumber(i)&&(this.lastLevelLoadSec=i/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,n=t.frag,i=t.part,a=i?i.stats:n.stats;if(n.type===PlaylistLevelType.MAIN&&this.bwEstimator.sampleTTFB(a.loading.first-a.loading.start),!this.ignoreFragment(n)){if(this.clearTimer(),n.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,null!=(r=this.hls)&&r.config.abrMaxWithRealBitrate){var s=i?i.duration:n.duration,o=this.hls.levels[n.level],l=(o.loaded?o.loaded.bytes:0)+a.loaded,u=(o.loaded?o.loaded.duration:0)+s;o.loaded={bytes:l,duration:u},o.realBitrate=Math.round(8*l/u)}if(n.bitrateTest){var c={stats:a,frag:n,part:i,id:n.type};this.onFragBuffered(Events$2.FRAG_BUFFERED,c),n.bitrateTest=!1}else this.lastLoadedFragLevel=n.level}}},{key:"onFragBuffered",value:function(e,t){var r=t.frag,n=t.part,i=null!=n&&n.stats.loaded?n.stats:r.stats;if(!i.aborted&&!this.ignoreFragment(r)){var a=((r.bitrate||0)>=1e5?i.parsing.end:i.loading.end)-i.loading.start-Math.min(i.loading.first-i.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,i.loaded),i.bwEstimate=this.getBwEstimate(),r.bitrateTest?this.bitrateTestDelay=a/1e3:(this.bitrateTestDelay=0,this.firstAutoFloor>-1&&this.bwEstimator.canEstimate()&&(this.firstAutoFloor=-1))}}},{key:"ignoreFragment",value:function(e){return e.type!==PlaylistLevelType.MAIN||"initSegment"===e.sn}},{key:"clearTimer",value:function(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}},{key:"firstAutoLevel",get:function(){var e=this.hls;if(!e)return 0;var t=e.maxAutoLevel,r=e.minAutoLevel,n=this.getBwEstimate(),i=this.getStarvationDelay(),a=e.config.maxStarvationDelay,s=this.findBestLevel(n,r,t,i/2,a,1,1);if(s>-1)return s;var o=e.firstLevel,l=-1===this.firstAutoFloor?1/0:this.firstAutoFloor,u=Math.min(Math.max(o,r),t,l);return this.warn("Could not find best starting auto level. Defaulting to first in playlist ".concat(o," clamped to ").concat(u)),u}},{key:"forcedAutoLevel",get:function(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}},{key:"nextAutoLevel",get:function(){if(!this.hls)return-1;var e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),r=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&r&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;var n=t&&r?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){var i=this.hls.levels;if(i.length>Math.max(e,n)&&i[e].loadError<=i[n].loadError)return e}return this._nextAutoLevel=n,this.nextAutoLevelKey=this.getAutoLevelKey(),n},set:function(e){var t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}},{key:"getAutoLevelKey",value:function(){return"".concat(this.getBwEstimate(),"_").concat(this.getStarvationDelay().toFixed(2))}},{key:"getNextABRAutoLevel",value:function(){var e=this.fragCurrent,t=this.partCurrent,r=this.hls;if(!r)return-1;if(r.levels.length<=1)return r.loadLevel;var n=r.maxAutoLevel,i=r.config,a=r.minAutoLevel,s=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay(),u=i.abrBandWidthFactor,c=i.abrBandWidthUpFactor;if(l){var d=this.findBestLevel(o,a,n,l,0,u,c);if(d>=0)return this.rebufferNotice=-1,d}var h=s?Math.min(s,i.maxStarvationDelay):i.maxStarvationDelay;if(!l){var f=this.bitrateTestDelay;if(f)h=(s?Math.min(s,i.maxLoadingDelay):i.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,n,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 p=r.levels[a],g=r.loadLevelObj;return g&&(null==p?void 0:p.bitrate)<g.bitrate?a:r.loadLevel}},{key:"getStarvationDelay",value:function(){var e=this.hls,t=null==e?void 0:e.media;if(!t)return 1/0;var r=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,n=e.mainForwardBufferInfo;return(n?n.len:0)/r}},{key:"getBwEstimate",value:function(){return this.bwEstimator.getEstimate()}},{key:"findBestLevel",value:function(e,t,r,n,i,a,s){var o=this,l=this.hls,u=this.lastLoadedFragLevel,c=this.fragCurrent,d=this.partCurrent;if(!l)return-1;var h=n+i,f=-1===u?l.firstLevel:u,v=l.levels,p=l.allAudioTracks,g=l.loadLevel,y=l.latestLevelDetails,m=l.config;if(1===v.length)return 0;var E,S=v[f],T=!(null==y||!y.live),k=-1===g||-1===u,_="SDR",A=(null==S?void 0:S.frameRate)||0,b=m.audioPreference,L=m.videoPreference,R=this.audioTracksByGroup||(this.audioTracksByGroup=getAudioTracksByGroup(p)),C=-1;if(k){if(-1!==this.firstSelection)return this.firstSelection;var I=getStartCodecTier(this.codecTiers||(this.codecTiers=getCodecTiers(v,R,t,r)),_,e,b,L),P=I.codecSet,D=I.videoRanges,w=I.minFramerate,O=I.minBitrate,x=I.minIndex,M=I.preferHDR;C=x,E=P,_=M?D[D.length-1]:D[0],A=w,e=Math.max(e,O),this.log("picked start tier ".concat(stringify(I)))}else E=null==S?void 0:S.codecSet,_=null==S?void 0:S.videoRange;for(var F,N,U=d?d.duration:c?c.duration:0,B=this.bwEstimator.getEstimateTTFB()/1e3,G=[],H=function(){var t=v[$],l=$>f;if(!t)return 0;if(m.useMediaCapabilities&&!t.supportedResult&&!t.supportedPromise){var c=navigator.mediaCapabilities;"function"==typeof(null==c?void 0:c.decodingInfo)&&requiresMediaCapabilitiesDecodingInfo(t,R,_,A,e,b)?(t.supportedPromise=getMediaDecodingInfoPromise(t,R,c,o.supportedCache),t.supportedPromise.then(function(e){if(o.hls){t.supportedResult=e;var r=o.hls.levels,n=r.indexOf(t);e.error?o.warn('MediaCapabilities decodingInfo error: "'.concat(e.error,'" for level ').concat(n," ").concat(stringify(e))):e.supported?e.decodingInfoResults.some(function(e){return!1===e.smooth||!1===e.powerEfficient})&&o.log("MediaCapabilities decodingInfo for level ".concat(n," not smooth or powerEfficient: ").concat(stringify(e))):(o.warn("Unsupported MediaCapabilities decodingInfo result for level ".concat(n," ").concat(stringify(e))),n>-1&&r.length>1&&(o.log("Removing unsupported level ".concat(n)),o.hls.removeLevel(n),-1===o.hls.loadLevel&&(o.hls.nextLoadLevel=0)))}}).catch(function(e){o.warn("Error handling MediaCapabilities decodingInfo: ".concat(e))})):t.supportedResult=SUPPORTED_INFO_DEFAULT}if((E&&t.codecSet!==E||_&&t.videoRange!==_||l&&A>t.frameRate||!l&&A>0&&A<t.frameRate||null!=(F=t.supportedResult)&&null!=(F=F.decodingInfoResults)&&F.some(function(e){return!1===e.smooth}))&&(!k||$!==C))return G.push($),0;var p,y=t.details,S=(d?null==y?void 0:y.partTarget:null==y?void 0:y.averagetargetduration)||U||1;p=l?s*e:a*e;var L=U&&n>=2*U&&0===i?t.averageBitrate:t.maxBitrate,I=o.getTimeToLoadFrag(B,p,L*S,!y||y.live);if(p>=L&&($===u||0===t.loadError&&0===t.fragmentError||isPenaltyExpired(t,m.errorPenaltyExpireMs))&&(I<=B||!isFiniteNumber(I)||T&&!o.bitrateTestDelay||I<h)){var P=o.forcedAutoLevel;return $===g||-1!==P&&P===g||(G.length&&o.trace("Skipped level(s) ".concat(G.join(",")," of ").concat(r,' max with CODECS and VIDEO-RANGE:"').concat(v[G[0]].codecs,'" ').concat(v[G[0]].videoRange,'; not compatible with "').concat(E,'" ').concat(_)),o.info("switch candidate:".concat(f,"->").concat($," adjustedbw(").concat(Math.round(p),")-bitrate=").concat(Math.round(p-L)," ttfb:").concat(B.toFixed(1)," avgDuration:").concat(S.toFixed(1)," maxFetchDuration:").concat(h.toFixed(1)," fetchDuration:").concat(I.toFixed(1)," firstSelection:").concat(k," codecSet:").concat(t.codecSet," videoRange:").concat(t.videoRange," hls.loadLevel:").concat(g))),k&&(o.firstSelection=$),{v:$}}},$=r;$>=t;$--)if(0!==(N=H())&&N)return N.v;return-1}},{key:"deriveNextAutoLevel",value:function(e){if(!this.hls)return-1;var t=this.hls,r=t.maxAutoLevel,n=t.minAutoLevel;return Math.min(Math.max(e,n),r)}}])}(),BinarySearch={search:function(e,t){for(var r=0,n=e.length-1,i=null,a=null;r<=n;){var s=t(a=e[i=(r+n)/2|0]);if(s>0)r=i+1;else{if(!(s<0))return a;n=i-1}}return null}};function findFragmentByPDT(e,t,r){if(null===t||!Array.isArray(e)||!e.length||!isFiniteNumber(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;for(var n=0;n<e.length;++n){var i=e[n];if(pdtWithinToleranceTest(t,r,i))return i}return null}function findFragmentByPTS(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,i=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===fragmentWithinToleranceTest(r,n,a)||fragmentWithinFastStartSwitch(a,e,Math.min(i,n))))return a;var o=BinarySearch.search(t,fragmentWithinToleranceTest.bind(null,r,n));return!o||o===e&&a?a:o}function fragmentWithinFastStartSwitch(e,t,r){if(0===(null==t?void 0:t.start)&&t.level<e.level&&(t.endPTS||0)>0){var n=t.tagList.reduce(function(e,t){return"INF"===t[0]&&(e+=parseFloat(t[1])),e},r);return e.start<=n}return!1}function fragmentWithinToleranceTest(){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 n=Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-n<=e?1:r.start-n>e&&r.start?-1:0}function pdtWithinToleranceTest(e,t,r){var n=1e3*Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-n>e}function findNearestWithCC(e,t,r){if(e&&e.startCC<=t&&e.endCC>=t){var n,i=e.fragments,a=e.fragmentHint;return a&&(i=i.concat(a)),BinarySearch.search(i,function(e){return e.cc<t?1:e.cc>t?-1:(n=e,e.end<=r?1:e.start>r?-1:0)}),n||null}return null}function getNextFrag(e,t){return t===e.endSN&&e.fragmentHint?e.fragmentHint:e.fragments[1+t-e.startSN]||null}var NetworkErrorAction={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},ErrorActionFlags={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8,ResetMediaSource:16},ErrorController=function(){function e(t){var r;return _classCallCheck(this,e),(r=_callSuper(this,e,["error-controller",t.logger])).hls=void 0,r.playlistError=0,r.hls=t,r.registerListeners(),r}return _inherits(e,Logger$1),_createClass(e,[{key:"registerListeners",value:function(){var e=this.hls;e.on(Events$2.ERROR,this.onError,this),e.on(Events$2.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events$2.LEVEL_UPDATED,this.onLevelUpdated,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(Events$2.ERROR,this.onError,this),e.off(Events$2.ERROR,this.onErrorOut,this),e.off(Events$2.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events$2.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)===PlaylistLevelType.MAIN?e.level:this.getVariantIndex()}},{key:"getVariantIndex",value:function(){var e,t=this.hls,r=t.currentLevel;return null!=(e=t.loadLevelObj)&&e.details||-1===r?t.loadLevel:r}},{key:"variantHasKey",value:function(e,t){if(e){var r;if(null!=(r=e.details)&&r.hasKey(t))return!0;var n=e.audioGroups;if(n)return this.hls.allAudioTracks.filter(function(e){return n.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 n=this.hls,i=t.context;switch(t.details){case ErrorDetails.FRAG_LOAD_ERROR:case ErrorDetails.FRAG_LOAD_TIMEOUT:case ErrorDetails.KEY_LOAD_ERROR:case ErrorDetails.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case ErrorDetails.FRAG_PARSING_ERROR:if(null!=(r=t.frag)&&r.gap)return void(t.errorAction=createDoNothingErrorAction());case ErrorDetails.FRAG_GAP:case ErrorDetails.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=NetworkErrorAction.SendAlternateToPenaltyBox);case ErrorDetails.PLAYLIST_UNCHANGED_ERROR:case ErrorDetails.LEVEL_EMPTY_ERROR:case ErrorDetails.LEVEL_PARSING_ERROR:var a,s=t.parent===PlaylistLevelType.MAIN?t.level:n.loadLevel;return void(t.details===ErrorDetails.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 ErrorDetails.LEVEL_LOAD_ERROR:case ErrorDetails.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==i?void 0:i.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.level)));case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:case ErrorDetails.SUBTITLE_LOAD_ERROR:case ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){var o=n.loadLevelObj;if(o&&(i.type===LoaderContextType.AUDIO_TRACK&&o.hasAudioGroup(i.groupId)||i.type===LoaderContextType.SUBTITLE_TRACK&&o.hasSubtitleGroup(i.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.loadLevel),t.errorAction.action=NetworkErrorAction.SendAlternateToPenaltyBox,void(t.errorAction.flags=ErrorActionFlags.MoveAllAlternatesMatchingHost)}return;case ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(t.errorAction={action:NetworkErrorAction.SendAlternateToPenaltyBox,flags:ErrorActionFlags.MoveAllAlternatesMatchingHDCP});case ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED:case ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case ErrorDetails.KEY_SYSTEM_NO_SESSION:return void(t.errorAction={action:NetworkErrorAction.SendAlternateToPenaltyBox,flags:ErrorActionFlags.MoveAllAlternatesMatchingKey});case ErrorDetails.BUFFER_ADD_CODEC_ERROR:case ErrorDetails.REMUX_ALLOC_ERROR:case ErrorDetails.BUFFER_APPEND_ERROR:return void(t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,t.level)));case ErrorDetails.MEDIA_SOURCE_REQUIRES_RESET:return t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,t.level)),void(t.errorAction.flags|=ErrorActionFlags.ResetMediaSource|ErrorActionFlags.SwitchToSDR);case ErrorDetails.INTERNAL_EXCEPTION:case ErrorDetails.BUFFER_APPENDING_ERROR:case ErrorDetails.BUFFER_APPEND_NO_PROGRESS:case ErrorDetails.BUFFER_FULL_ERROR:case ErrorDetails.LEVEL_SWITCH_ERROR:case ErrorDetails.BUFFER_STALLED_ERROR:case ErrorDetails.BUFFER_SEEK_OVER_HOLE:case ErrorDetails.BUFFER_NUDGE_ON_STALL:return void(t.errorAction=createDoNothingErrorAction())}t.type===ErrorTypes.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=createDoNothingErrorAction())}}},{key:"getPlaylistRetryOrSwitchAction",value:function(e,t){var r=getRetryConfig(this.hls.config.playlistLoadPolicy,e),n=this.playlistError++;if(shouldRetry(r,n,isTimeoutError(e),e.response))return{action:NetworkErrorAction.RetryRequest,flags:ErrorActionFlags.None,retryConfig:r,retryCount:n};var i=this.getLevelSwitchAction(e,t);return r&&(i.retryConfig=r,i.retryCount=n),i}},{key:"getFragRetryOrSwitchAction",value:function(e){var t=this.hls,r=this.getVariantLevelIndex(e.frag),n=t.levels[r],i=t.config,a=i.fragLoadPolicy,s=i.keyLoadPolicy,o=getRetryConfig(isKeyError(e)?s:a,e),l=t.levels.reduce(function(e,t){return e+t.fragmentError},0);if(n&&(e.details!==ErrorDetails.FRAG_GAP&&n.fragmentError++,!isUnusableKeyError(e)&&shouldRetry(o,l,isTimeoutError(e),e.response)))return{action:NetworkErrorAction.RetryRequest,flags:ErrorActionFlags.None,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 n=this.hls.levels[t];if(n){var i,a,s=e.details;n.loadError++,n.loadErrorTime=self.performance.now(),s===ErrorDetails.BUFFER_APPEND_ERROR&&n.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,p=null==(i=e.frag)?void 0:i.type,g=(p===PlaylistLevelType.AUDIO&&s===ErrorDetails.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&isCodecRelated(e))&&l.some(function(e){var t=e.audioCodec;return n.audioCodec!==t}),y="video"===e.sourceBufferName&&isCodecRelated(e)&&l.some(function(e){var t=e.codecSet,r=e.audioCodec;return n.codecSet!==t&&n.audioCodec===r}),m=null!=(a=e.context)?a:{},E=m.type,S=m.groupId,T=function(){var t=(k+u)%l.length;if(t!==u&&t>=c&&t<=d&&(0===l[t].loadError||isPenaltyExpired(l[t],r.config.errorPenaltyExpireMs))){var i=l[t];if(s===ErrorDetails.FRAG_GAP&&p===PlaylistLevelType.MAIN&&e.frag){var a=l[t].details;if(a){var v=findFragmentByPTS(e.frag,a.fragments,e.frag.start);if(null!=v&&v.gap)return 0}}else{if(E===LoaderContextType.AUDIO_TRACK&&i.hasAudioGroup(S)||E===LoaderContextType.SUBTITLE_TRACK&&i.hasSubtitleGroup(S))return 0;if(p===PlaylistLevelType.AUDIO&&null!=(h=n.audioGroups)&&h.some(function(e){return i.hasAudioGroup(e)})||p===PlaylistLevelType.SUBTITLE&&null!=(f=n.subtitleGroups)&&f.some(function(e){return i.hasSubtitleGroup(e)})||g&&n.audioCodec===i.audioCodec||y&&n.codecSet===i.codecSet||!g&&n.audioCodec!==i.audioCodec)return 0}return o=t,1}},k=l.length;k--&&(0===(v=T())||1!==v););if(o>-1&&r.loadLevel!==o)return e.levelRetry=!0,this.playlistError=0,{action:NetworkErrorAction.SendAlternateToPenaltyBox,flags:ErrorActionFlags.None,nextAutoLevel:o}}return{action:NetworkErrorAction.SendAlternateToPenaltyBox,flags:ErrorActionFlags.MoveAllAlternatesMatchingHost}}},{key:"onErrorOut",value:function(e,t){var r,n;switch(null==(r=t.errorAction)?void 0:r.action){case NetworkErrorAction.DoNothing:break;case NetworkErrorAction.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===ErrorDetails.FRAG_GAP||t.details===ErrorDetails.PLAYLIST_UNCHANGED_ERROR||isAppendStateRelated(t)||(t.fatal=!0)}((null==(n=t.errorAction)?void 0:n.flags)||0)&ErrorActionFlags.ResetMediaSource&&this.hls.recoverMediaError(),t.fatal&&this.hls.stopLoad()}},{key:"sendAlternateToPenaltyBox",value:function(e){var t=this.hls,r=e.errorAction;if(r){var n=r.nextAutoLevel;if(r.flags===ErrorActionFlags.None)this.switchLevel(e,n);else if(r.flags&ErrorActionFlags.SwitchToSDR)for(var i=this.hls.levels,a=i.length;a--;)"SDR"!==i[a].videoRange?(i[a].fragmentError++,i[a].loadError++):void 0===n&&(n=a);else if(r.flags&ErrorActionFlags.MoveAllAlternatesMatchingHDCP){var s=this.getVariantLevelIndex(e.frag),o=t.levels[s],l=null==o?void 0:o.attrs["HDCP-LEVEL"];r.hdcpLevel=l;var u="NONE"===l;l&&!u?(t.maxHdcpLevel=HdcpLevels[HdcpLevels.indexOf(l)-1],r.resolved=!0,this.warn('Restricting playback to HDCP-LEVEL of "'.concat(t.maxHdcpLevel,'" or lower'))):(u&&this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE"),r.flags|=ErrorActionFlags.MoveAllAlternatesMatchingKey)}if(r.flags&ErrorActionFlags.MoveAllAlternatesMatchingKey){var c=e.decryptdata;if(c){for(var d=this.hls.levels,h=d.length,f=h;f--;){var v,p;if(this.variantHasKey(d[f],c))this.log("Banned key found in level ".concat(f," (").concat(d[f].bitrate,'bps) or audio group "').concat(null==(v=d[f].audioGroups)?void 0:v.join(","),'" (').concat(null==(p=e.frag)?void 0:p.type," fragment) ").concat(arrayToHex(c.keyId||[]))),d[f].fragmentError++,d[f].loadError++,this.log("Removing level ".concat(f," with key error (").concat(e.error,")")),this.hls.removeLevel(f)}var g=e.frag;if(this.hls.levels.length<h)r.resolved=!0;else if(g&&g.type!==PlaylistLevelType.MAIN){var y=g.decryptdata;y&&!c.matches(y)&&(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===ErrorDetails.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&"audiovideo"!==e.sourceBufferName))for(var r=getCodecsForMimeType(e.mimeType),n=this.hls.levels,i=n.length;i--;)n[i]["".concat(e.sourceBufferName,"Codec")]===r&&(this.log("Removing level ".concat(i," for ").concat(e.details,' ("').concat(r,'" not supported)')),this.hls.removeLevel(i))}}])}();function isCodecRelated(e){var t=e.details;return t===ErrorDetails.BUFFER_ADD_CODEC_ERROR||t===ErrorDetails.MEDIA_SOURCE_REQUIRES_RESET||t===ErrorDetails.BUFFER_APPEND_ERROR&&!isAppendStateRelated(e)}function isAppendStateRelated(e){return e.details===ErrorDetails.BUFFER_APPEND_ERROR&&("QuotaExceededError"===e.error.name||"InvalidStateError"===e.error.name)}function createDoNothingErrorAction(e){var t={action:NetworkErrorAction.DoNothing,flags:ErrorActionFlags.None};return e&&(t.resolved=!0),t}var FragmentState={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"},FragmentTracker=function(){return _createClass(function e(t){_classCallCheck(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(Events$2.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events$2.BUFFER_APPENDED,this.onBufferAppended,this),e.on(Events$2.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Events$2.FRAG_LOADED,this.onFragLoaded,this))}},{key:"_unregisterListeners",value:function(){var e=this.hls;e&&(e.off(Events$2.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events$2.BUFFER_APPENDED,this.onBufferAppended,this),e.off(Events$2.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Events$2.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 n=r.length;n--;){var i=r[n];if(!i)break;if(i.start<=e&&e<=i.end&&i.loaded)return i}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 n=this.fragments,i=Object.keys(n),a=i.length;a--;){var s=n[i[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,n,i,a){var s=this;this.timeRanges&&(this.timeRanges[e]=t);var o=(null==i?void 0:i.fragment.sn)||-1;Object.keys(this.fragments).forEach(function(i){var l=s.fragments[i];if(l&&s.hls){var u=l.body;if(!(o>=u.sn))if(l.buffered||l.loaded&&!a){var c=l.range[e];if(c)if(0!==c.time.length){if(c.time.some(function(e){var r=!s.isTimeBuffered(e.startPTS,e.endPTS,t);return r&&s.removeFragment(u),r}),n&&n!==u&&userAgentChromeVersion()){var d=n.endPTS,h=u.startPTS;if(d&&h&&l.range.video){var f=h-d;f<0&&f>-.1&&(s.removeFragment(u),s.hls.trigger(Events$2.BUFFER_FLUSHING,{startOffset:d+.004,endOffset:1/0,type:"video"}))}}}else s.removeFragment(u)}else u.type===r&&s.removeFragment(u)}})}},{key:"detectPartialFragments",value:function(e){var t=this,r=this.timeRanges,n=e.frag,i=e.part,a=e.id;if(r&&isMediaFragment(n)){var s=getFragmentKey(n),o=this.fragments[s];if(!(!o||o.buffered&&n.gap)){var l=!n.relurl;Object.keys(r).forEach(function(e){var s=n.elementaryStreams[e];if(s){var u=r[e],c=l||!0===s.partial;o.range[e]=t.getBufferedTimes(n,i,c,u),t.detectEvictedFragments(e,u,a,n,i)}}),o.loaded=null;var u=Object.keys(o.range);if(u.length){if(this.bufferedEnd(o,n),isPartial(o)||this.removeParts(n.sn-1,n.type),!i){var c=Math.min(.004,n.duration);u.some(function(e){var r,i=null==(r=o.range[e])?void 0:r.time,a=0===i.length||1===i.length&&i[0].endPTS-i[0].startPTS<c;return a&&t.addAsGap(n),a})}}else this.removeFragment(n)}}}},{key:"addAsGap",value:function(e){e.gap=!0,this.removeFragment(e),this.fragBuffered(e,!0)}},{key:"bufferedEnd",value:function(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&!t.gap&&(this.endListFragments[e.body.type]=e)}},{key:"removeParts",value:function(e,t){var r=this.activePartLists[t];r&&(this.activePartLists[t]=filterParts(r,function(t){return t.fragment.sn>=e}))}},{key:"fragBuffered",value:function(e,t){var r=getFragmentKey(e),n=this.fragments[r];return!n&&t&&(n=this.fragments[r]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),n&&(n.loaded=null,this.bufferedEnd(n,e)),n}},{key:"getBufferedTimes",value:function(e,t,r,n){for(var i={time:[],partial:r},a=e.start,s=e.end,o=e.minEndPTS||s,l=e.maxStartPTS||a,u=0;u<n.length;u++){var c=n.start(u)-this.bufferPadding,d=n.end(u)+this.bufferPadding;if(l>=c&&o<=d){i.time.push({startPTS:Math.max(a,n.start(u)),endPTS:Math.min(s,n.end(u))});break}if(a<d&&s>c){var h=Math.max(a,n.start(u)),f=Math.min(s,n.end(u));f>h&&(i.partial=!0,i.time.push({startPTS:h,endPTS:f}))}else if(s<=c)break}return i}},{key:"getPartialFragment",value:function(e){var t,r,n,i=null,a=0,s=this.bufferPadding,o=this.fragments;return Object.keys(o).forEach(function(l){var u=o[l];u&&isPartial(u)&&(r=u.body.start-s,n=u.body.end+s,e>=r&&e<=n&&(t=Math.min(e-r,n-e),a<=t&&(i=u.body,a=t)))}),i}},{key:"isEndListAppended",value:function(e){var t=this.endListFragments[e];return void 0!==t&&(t.buffered||isPartial(t))}},{key:"getState",value:function(e){var t=getFragmentKey(e),r=this.fragments[t];return r?r.buffered?isPartial(r)?FragmentState.PARTIAL:FragmentState.OK:FragmentState.APPENDING:FragmentState.NOT_LOADED}},{key:"isTimeBuffered",value:function(e,t,r){for(var n,i,a=0;a<r.length;a++){if(n=r.start(a)-this.bufferPadding,i=r.end(a)+this.bufferPadding,e>=n&&t<=i)return!0;if(t<=n)return!1}return!1}},{key:"onManifestLoading",value:function(){this.removeAllFragments()}},{key:"onFragLoaded",value:function(e,t){if(isMediaFragment(t.frag)&&!t.frag.bitrateTest){var r=t.frag,n=t.part?null:t,i=getFragmentKey(r);this.fragments[i]={body:r,appendedPTS:null,loaded:n,buffered:!1,range:Object.create(null)}}}},{key:"onBufferAppended",value:function(e,t){var r=t.frag,n=t.part,i=t.timeRanges;if(isMediaFragment(r)){var a=r.type;if(n){var s=this.activePartLists[a];s||(this.activePartLists[a]=s=[]),s.push(n)}this.timeRanges=i}}},{key:"onFragBuffered",value:function(e,t){this.detectPartialFragments(t)}},{key:"hasFragment",value:function(e){var t=getFragmentKey(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 n=r.length;n--;){var i=t[r[n]];if((null==i?void 0:i.body.type)===e)return!0}return!1}},{key:"hasParts",value:function(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)}},{key:"getBackBufferEvictionEnd",value:function(e,t,r){for(var n=this.fragments,i=0,a=0,s=Object.keys(n),o=0;o<s.length;o++){var l=n[s[o]];if(l&&l.buffered&&l.body.type===t){var u=l.body;if(u.gap)return 0;var c=u.hasStats&&u.stats.loaded||u.byteLength||u.bitrate&&8*u.bitrate*u.duration;if(u.end<=e&&c&&(i+=c,a=Math.max(a,u.end),i>=r))return a}}return a>0?a:0}},{key:"removeFragmentsInRange",value:function(e,t,r,n,i){var a=this;n&&!this.hasGaps||Object.keys(this.fragments).forEach(function(s){var o=a.fragments[s];if(o){var l=o.body;l.type!==r||n&&!l.gap||l.start<t&&l.end>e&&(o.buffered||i)&&a.removeFragment(l)}})}},{key:"removeFragment",value:function(e){var t=getFragmentKey(e);e.clearElementaryStreamInfo();var r=this.activePartLists[e.type];if(r){var n=e.sn;this.activePartLists[e.type]=filterParts(r,function(e){return e.fragment.sn!==n})}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 isPartial(e){var t,r,n,i;return e.buffered&&!!(e.body.gap||null!=(t=e.range.video)&&t.partial||null!=(r=e.range.audio)&&r.partial||null!=(n=e.range.audiovideo)&&n.partial||null!=(i=e.range.subs)&&i.partial)}function getFragmentKey(e){return"".concat(e.type,"_").concat(e.level,"_").concat(e.sn)}function filterParts(e,t){return e.filter(function(e){var r=t(e);return r||e.clearElementaryStreamInfo(),r})}var DecrypterAesMode={cbc:0,ctr:1},AESCrypto=function(){return _createClass(function e(t,r,n){_classCallCheck(this,e),this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=r,this.aesMode=n},[{key:"decrypt",value:function(e,t){switch(this.aesMode){case DecrypterAesMode.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case DecrypterAesMode.ctr: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))}}}])}();function removePadding(e){var t=e.byteLength,r=t&&new DataView(e.buffer).getUint8(t-1);return r?e.slice(0,t-r):e}var AESDecryptor=function(){return _createClass(function e(){_classCallCheck(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),n=0;n<4;n++)r[n]=t.getUint32(4*n);return r}},{key:"initTable",value:function(){var e=this.sBox,t=this.invSBox,r=this.subMix,n=r[0],i=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,p=0;for(p=0;p<256;p++)h[p]=p<128?p<<1:p<<1^283;for(p=0;p<256;p++){var g=v^v<<1^v<<2^v<<3^v<<4;g=g>>>8^255&g^99,e[f]=g,t[g]=f;var y=h[f],m=h[y],E=h[m],S=257*h[g]^16843008*g;n[f]=S<<24|S>>>8,i[f]=S<<16|S>>>16,a[f]=S<<8|S>>>24,s[f]=S,S=16843009*E^65537*m^257*y^16843008*f,l[g]=S<<24|S>>>8,u[g]=S<<16|S>>>16,c[g]=S<<8|S>>>24,d[g]=S,f?(f=y^h[h[h[E^y]]],v^=h[h[v]]):f=v=1}}},{key:"expandKey",value:function(e){for(var t=this.uint8ArrayToUint32Array_(e),r=!0,n=0;n<t.length&&r;)r=t[n]===this.key[n],n++;if(!r){this.key=t;var i=this.keySize=t.length;if(4!==i&&6!==i&&8!==i)throw new Error("Invalid aes key size="+i);var a,s,o,l,u=this.ksRows=4*(i+6+1),c=this.keySchedule=new Uint32Array(u),d=this.invKeySchedule=new Uint32Array(u),h=this.sBox,f=this.rcon,v=this.invSubMix,p=v[0],g=v[1],y=v[2],m=v[3];for(a=0;a<u;a++)a<i?o=c[a]=t[a]:(l=o,a%i===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/i|0]<<24):i>6&&a%i===4&&(l=h[l>>>24]<<24|h[l>>>16&255]<<16|h[l>>>8&255]<<8|h[255&l]),c[a]=o=(c[a-i]^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:p[h[l>>>24]]^g[h[l>>>16&255]]^y[h[l>>>8&255]]^m[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 n,i,a,s,o,l,u,c,d,h,f,v,p,g,y=this.keySize+6,m=this.invKeySchedule,E=this.invSBox,S=this.invSubMix,T=S[0],k=S[1],_=S[2],A=S[3],b=this.uint8ArrayToUint32Array_(r),L=b[0],R=b[1],C=b[2],I=b[3],P=new Int32Array(e),D=new Int32Array(P.length),w=this.networkToHostOrderSwap;t<P.length;){for(d=w(P[t]),h=w(P[t+1]),f=w(P[t+2]),v=w(P[t+3]),o=d^m[0],l=v^m[1],u=f^m[2],c=h^m[3],p=4,g=1;g<y;g++)n=T[o>>>24]^k[l>>16&255]^_[u>>8&255]^A[255&c]^m[p],i=T[l>>>24]^k[u>>16&255]^_[c>>8&255]^A[255&o]^m[p+1],a=T[u>>>24]^k[c>>16&255]^_[o>>8&255]^A[255&l]^m[p+2],s=T[c>>>24]^k[o>>16&255]^_[l>>8&255]^A[255&u]^m[p+3],o=n,l=i,u=a,c=s,p+=4;n=E[o>>>24]<<24^E[l>>16&255]<<16^E[u>>8&255]<<8^E[255&c]^m[p],i=E[l>>>24]<<24^E[u>>16&255]<<16^E[c>>8&255]<<8^E[255&o]^m[p+1],a=E[u>>>24]<<24^E[c>>16&255]<<16^E[o>>8&255]<<8^E[255&l]^m[p+2],s=E[c>>>24]<<24^E[o>>16&255]<<16^E[l>>8&255]<<8^E[255&u]^m[p+3],D[t]=w(n^L),D[t+1]=w(s^R),D[t+2]=w(a^C),D[t+3]=w(i^I),L=d,R=h,C=f,I=v,t+=4}return D.buffer}}])}(),FastAESKey=function(){return _createClass(function e(t,r,n){_classCallCheck(this,e),this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=t,this.key=r,this.aesMode=n},[{key:"expandKey",value:function(){var e=getSubtleAlgoName(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}])}();function getSubtleAlgoName(e){switch(e){case DecrypterAesMode.cbc:return"AES-CBC";case DecrypterAesMode.ctr:return"AES-CTR";default:throw new Error("[FastAESKey] invalid aes mode ".concat(e))}}var CHUNK_SIZE=16,Decrypter=function(){return _createClass(function e(t,r){if(_classCallCheck(this,e),this.logEnabled=!0,this.decryptRange=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=t.enableSoftwareAES,!0!==r)try{var n=self.crypto;n&&(this.subtle=n.subtle||n.webkitSubtle)}catch(i){}this.useSoftware=!this.subtle},[{key:"destroy",value:function(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}},{key:"isSync",value:function(){return this.useSoftware}},{key:"flush",value:function(){var e=this.currentResult,t=this.remainderData;if(!e||t)return this.reset(),null;var r=new Uint8Array(e);this.reset();var n=this.decryptRange;return n?0===n.start&&n.end>=r.length?r:r.slice(n.start,n.end):removePadding(r)}},{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,n,i){var a=this;return this.decryptRange=i,this.useSoftware||i?new Promise(function(i,s){var o=ArrayBuffer.isView(e)?e:new Uint8Array(e);a.softwareDecrypt(o,t,r,n);var l=a.flush();l?i(l.buffer):s(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,r,n)}},{key:"softwareDecrypt",value:function(e,t,r,n){var i=this.currentIV,a=this.currentResult,s=this.remainderData;if(n!==DecrypterAesMode.cbc||16!==t.byteLength)return logger.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),s&&(e=appendUint8Array(s,e),this.remainderData=null);var o=this.getValidChunk(e);if(!o.length)return null;i&&(r=i);var l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new AESDecryptor),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,n){var i=this;if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,r,n));this.key=t,this.fastAesKey=new FastAESKey(this.subtle,t,n)}return this.fastAesKey.expandKey().then(function(t){return i.subtle?(i.logOnce("WebCrypto AES decrypt"),new AESCrypto(i.subtle,new Uint8Array(r),n).decrypt(e.buffer,t)):Promise.reject(new Error("web crypto not initialized"))}).catch(function(a){return logger.warn("[decrypter]: WebCrypto Error, disable WebCrypto API, ".concat(a.name,": ").concat(a.message)),i.onWebCryptoError(e,t,r,n)})}},{key:"onWebCryptoError",value:function(e,t,r,n){var i=this.enableSoftwareAES;if(i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,r,n);var a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(i?" and softwareDecrypt":"")+": failed to decrypt data")}},{key:"getValidChunk",value:function(e){var t=e,r=e.length-e.length%CHUNK_SIZE;return r!==e.length&&(t=e.slice(0,r),this.remainderData=e.slice(r)),t}},{key:"logOnce",value:function(e){this.logEnabled&&(logger.log("[decrypter]: ".concat(e)),this.logEnabled=!1)}}])}(),MIN_CHUNK_SIZE=Math.pow(2,17),FragmentLoader=function(){return _createClass(function e(t){_classCallCheck(this,e),this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t},[{key:"destroy",value:function(){this.loader&&(this.loader.destroy(),this.loader=null)}},{key:"abort",value:function(){this.loader&&this.loader.abort()}},{key:"load",value:function(e,t,r,n){var i=this,a=e.url;if(!a)return Promise.reject(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a ".concat(a?"part list":"url")),networkDetails:null}));this.abort();var s=this.config,o=s.fLoader,l=s.loader;return new Promise(function(u,c){if(i.loader&&i.loader.destroy(),e.gap){if(e.tagList.some(function(e){return"GAP"===e[0]}))return void c(createGapLoadError(e));e.gap=!1}var d=i.loader=o?new o(s):new l(s),h=createLoaderContext(e,null,t);e.loader=d;var f=getLoaderConfigWithoutReties(s.fragLoadPolicy.default),v={loadPolicy:f,timeout:f.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:MIN_CHUNK_SIZE};d.stats.retry=e.stats.retry,e.stats=d.stats;var p={onSuccess:function(t,r,n,a){i.resetLoader(e,d);var s=t.data;n.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(s.slice(0,16)),s=s.slice(16)),u({frag:e,part:null,payload:s,networkDetails:a})},onError:function(t,r,n,s){i.resetLoader(e,d),c(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:_objectSpread2({url:a,data:void 0},t),error:new Error("HTTP Error ".concat(t.code," ").concat(t.text)),networkDetails:n,stats:s}))},onAbort:function(t,r,n){i.resetLoader(e,d),c(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:n,stats:t}))},onTimeout:function(t,r,n){i.resetLoader(e,d),c(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error("Timeout after ".concat(v.timeout,"ms")),networkDetails:n,stats:t}))}};if(r){var g=i.gateProgress(r,n);p.onProgress=function(t,r,n,i){return g({frag:e,part:null,payload:n,networkDetails:i})}}d.load(h,v,p)})}},{key:"gateProgress",value:function(e,t){var r=e;if(t){var n=[],i=!1;t.then(function(){i=!0,n.forEach(function(t){return e(t)}),n.length=0}).catch(function(){}),r=function(t){i?e(t):n.push(t)}}return r}},{key:"loadPart",value:function(e,t,r){var n=this;this.abort();var i=this.config,a=i.fLoader,s=i.loader;return new Promise(function(o,l){if(n.loader&&n.loader.destroy(),e.gap||t.gap)l(createGapLoadError(e,t));else{var u=n.loader=a?new a(i):new s(i),c=createLoaderContext(e,t);e.loader=u;var d=getLoaderConfigWithoutReties(i.fragLoadPolicy.default),h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:MIN_CHUNK_SIZE};t.stats=u.stats,u.load(c,h,{onSuccess:function(i,a,s,l){n.resetLoader(e,u),n.updateStatsFromPart(e,t);var c={frag:e,part:t,payload:i.data,networkDetails:l};r(c),o(c)},onError:function(r,i,a,s){n.resetLoader(e,u),l(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:_objectSpread2({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,i,a){e.stats.aborted=t.stats.aborted,n.resetLoader(e,u),l(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:a,stats:r}))},onTimeout:function(r,i,a){n.resetLoader(e,u),l(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.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,n=t.stats,i=n.total;if(r.loaded+=n.loaded,i){var a=Math.round(e.duration/t.duration),s=Math.min(Math.round(r.loaded/i),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=n.loading;l.start?l.first+=u.first-u.start:(l.start=u.start,l.first=u.first),l.end=u.end}},{key:"resetLoader",value:function(e,t){e.loader=null,e.url=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}])}();function createLoaderContext(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,r=arguments.length>2?arguments[2]:void 0,n=t||e,i={type:LoaderContextType.MEDIA_FRAGMENT,frag:e,part:t,responseType:"arraybuffer",url:n.url,headers:{},rangeStart:0,rangeEnd:0},a=getAESAdjustments(e,t,r);return a.resetIV&&(i.resetIV=!0),a.byteRange&&(i.rangeStart=a.byteRange.start,i.rangeEnd=a.byteRange.end),i}function getAESAdjustments(e){var t,r=arguments.length>2?arguments[2]:void 0,n={},i=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:null)||e,a=i.byteRangeStartOffset,s=i.byteRangeEndOffset;if(isFiniteNumber(a)&&isFiniteNumber(s))if(("initSegment"===e.sn||r)&&isMethodFullSegmentAesCbc(null==(t=e.decryptdata)?void 0:t.method)){var o=16*Math.floor(a/16),l=16*Math.ceil(s/16);n.decryptRange={start:a-o,end:s-o},o>=16&&(n.resetIV=!0,o-=16),n.byteRange={start:o,end:l}}else n.byteRange={start:a,end:s};return n}function createGapLoadError(e,t){var r=new Error("GAP ".concat(e.gap?"tag":"attribute"," found")),n={type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_GAP,fatal:!1,frag:e,error:r,networkDetails:null};return t&&(n.part=t),(t||e).stats.aborted=!0,new LoadError(n)}function isMethodFullSegmentAesCbc(e){return"AES-128"===e||"AES-256"===e}var LoadError=function(){function e(t){var r;return _classCallCheck(this,e),(r=_callSuper(this,e,[t.error.message])).data=void 0,r.data=t,r}return _inherits(e,_wrapNativeSuper(Error)),_createClass(e)}(),TaskLoop=function(){function e(t,r){var n;return _classCallCheck(this,e),(n=_callSuper(this,e,[t,r]))._boundTick=void 0,n._tickTimer=null,n._tickInterval=null,n._tickCallCount=0,n._boundTick=n.tick.bind(n),n}return _inherits(e,Logger$1),_createClass(e,[{key:"destroy",value:function(){this.onHandlerDestroying(),this.onHandlerDestroyed()}},{key:"onHandlerDestroying",value:function(){this.clearNextTick(),this.clearInterval()}},{key:"onHandlerDestroyed",value:function(){}},{key:"hasInterval",value:function(){return!!this._tickInterval}},{key:"hasNextTick",value:function(){return!!this._tickTimer}},{key:"setInterval",value:function(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}},{key:"clearInterval",value:function(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}},{key:"clearNextTick",value:function(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}},{key:"tick",value:function(){this._tickCallCount++,1===this._tickCallCount?(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0):(this.log("possible exception thrown in task-loop (".concat(this.constructor.name,".doTick)")),this._tickCallCount=0)}},{key:"tickImmediate",value:function(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}},{key:"doTick",value:function(){}}])}(),ChunkMetadata=_createClass(function e(t,r,n){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:-1,s=arguments.length>5&&void 0!==arguments[5]&&arguments[5],o=arguments.length>6?arguments[6]:void 0,l=arguments.length>7?arguments[7]:void 0,u=arguments.length>8?arguments[8]:void 0;_classCallCheck(this,e),this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.iframe=void 0,this.duration=void 0,this.decryptRange=void 0,this.transmuxing=getNewPerformanceTiming(),this.buffering={audio:getNewPerformanceTiming(),video:getNewPerformanceTiming(),audiovideo:getNewPerformanceTiming()},this.level=t,this.sn=r,this.id=n,this.size=i,this.part=a,this.partial=s,this.duration=o||0,this.decryptRange=u,this.iframe=l||!1});function getNewPerformanceTiming(){return{start:0,executeStart:0,executeEnd:0,end:0}}var noopBuffered={length:0,start:function(){return 0},end:function(){return 0}},BufferHelper=function(){function e(){_classCallCheck(this,e)}return _createClass(e,null,[{key:"isBuffered",value:function(t,r){if(t)for(var n=e.getBuffered(t),i=n.length;i--;)if(r>=n.start(i)&&r<=n.end(i))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,n){if(t){var i=e.bufferedRanges(t);if(i.length)return e.bufferedInfo(i,r,n)}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 n=-1,i=[];if(r)for(var a=0;a<e.length;a++){t>=e[a].start&&t<=e[a].end&&(n=a);var s=i.length;if(s){var o=i[s-1].end;e[a].start-o<r?e[a].end>o&&(i[s-1].end=e[a].end):i.push(e[a])}else i.push(e[a])}else i=e;for(var l,u=0,c=t,d=t,h=0;h<i.length;h++){var f=i[h].start,v=i[h].end;if(-1===n&&t>=f&&t<=v&&(n=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:n}}},{key:"getBuffered",value:function(e){try{return e.buffered||noopBuffered}catch(t){return logger.log("failed to get media.buffered",t),noopBuffered}}}])}(),VARIABLE_REPLACEMENT_REGEX=/\{\$([a-zA-Z0-9-_]+)\}/g;function hasVariableReferences(e){return VARIABLE_REPLACEMENT_REGEX.lastIndex=0,VARIABLE_REPLACEMENT_REGEX.test(e)}function substituteVariables(e,t){if(null!==e.variableList||e.hasVariableRefs){var r=e.variableList;return t.replace(VARIABLE_REPLACEMENT_REGEX,function(t){var n=t.substring(2,t.length-1),i=null==r?void 0:r[n];return void 0===i?(e.playlistParsingError||(e.playlistParsingError=new Error('Missing preceding EXT-X-DEFINE tag for Variable Reference: "'.concat(n,'"'))),t):i})}return t}function addVariableDefinition(e,t,r){var n,i,a=e.variableList;if(a||(e.variableList=a={}),"QUERYPARAM"in t){n=t.QUERYPARAM;try{var s=new self.URL(r).searchParams;if(!s.has(n))throw new Error('"'.concat(n,'" does not match any query parameter in URI: "').concat(r,'"'));i=s.get(n)}catch(o){e.playlistParsingError||(e.playlistParsingError=new Error("EXT-X-DEFINE QUERYPARAM: ".concat(o.message)))}}else n=t.NAME,i=t.VALUE;n in a?e.playlistParsingError||(e.playlistParsingError=new Error('EXT-X-DEFINE duplicate Variable Name declarations: "'.concat(n,'"'))):a[n]=i||""}function importVariableDefinition(e,t,r){var n=t.IMPORT;if(r&&n in r){var i=e.variableList;i||(e.variableList=i={}),i[n]=r[n]}else e.playlistParsingError||(e.playlistParsingError=new Error('EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "'.concat(n,'"')))}var DECIMAL_RESOLUTION_REGEX=/^(\d+)x(\d+)$/,ATTR_LIST_REGEX=/(.+?)=(".*?"|.*?)(?:,|$)/g,AttrList=function(){return _createClass(function e(t,r){_classCallCheck(this,e),"string"==typeof t&&(t=e.parseAttrList(t,r)),_extends(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),n=0;n<t.length/2;n++)r[n]=parseInt(t.slice(2*n,2*n+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=DECIMAL_RESOLUTION_REGEX.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,n={};for(ATTR_LIST_REGEX.lastIndex=0;null!==(r=ATTR_LIST_REGEX.exec(e));){var i=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(i){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(t&&(s||o))a=substituteVariables(t,a);else if(!o&&!s)switch(i){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":logger.warn("".concat(e,": attribute ").concat(i," is missing quotes"))}n[i]=a}return n}}])}(),CLASS_INTERSTITIAL="com.apple.hls.interstitial";function isDateRangeCueAttribute(e){return"ID"!==e&&"CLASS"!==e&&"CUE"!==e&&"START-DATE"!==e&&"DURATION"!==e&&"END-DATE"!==e&&"END-ON-NEXT"!==e}function isSCTE35Attribute(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e||"SCTE35-CMD"===e}var DateRange=function(){return _createClass(function e(t,r){var n,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;if(_classCallCheck(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!=(n=null==r?void 0:r.tagOrder)?n:i,r){var a=r.attr;for(var s in a)if(Object.prototype.hasOwnProperty.call(t,s)&&t[s]!==a[s]){logger.warn('DATERANGE tag attribute: "'.concat(s,'" does not match for tags with ID: "').concat(t.ID,'"')),this._badValueForSameId=s;break}t=_extends(new AttrList({}),a,t)}if(this.attr=t,r?(this._startDate=r._startDate,this._cue=r._cue,this._endDate=r._endDate,this._dateAtEnd=r._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in t){var o=(null==r?void 0:r.endDate)||new Date(t["END-DATE"]);isFiniteNumber(o.getTime())&&(this._endDate=o)}},[{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?(logger.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(isFiniteNumber(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 this.class===CLASS_INTERSTITIAL}},{key:"isValid",get:function(){return!!this.id&&!this._badValueForSameId&&isFiniteNumber(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}},{key:"invalidReason",get:function(){return this.id?this._badValueForSameId?"Date range ".concat(this._badValueForSameId," mismatch"):isFiniteNumber(this.startDate.getTime())?!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr?this.isValid?null:"Unknown (check DURATION(|END|NEXT), CLASS, and CUE)":"Interstitial Date range missing X-ASSET-(LIST|URI)":"Date range invalid start date":"Missing ID"}}])}(),DEFAULT_TARGET_DURATION=10,LevelDetails=function(){return _createClass(function e(t){_classCallCheck(this,e),this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.iframesOnly=!1,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=t},[{key:"reloaded",value:function(e){if(!e)return this.advanced=!0,void(this.updated=!0);var t=this.lastPartSn-e.lastPartSn,r=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!r||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&r>0,this.updated||this.advanced?this.misses=0:this.misses=e.misses+1}},{key:"hasKey",value:function(e){return this.encryptedFragments.some(function(t){var r=t.decryptdata;return r||(t.setKeyFormat(e.keyFormat),r=t.decryptdata),!!r&&e.matches(r)})}},{key:"hasProgramDateTime",get:function(){return!!this.fragments.length&&isFiniteNumber(this.fragments[this.fragments.length-1].programDateTime)}},{key:"levelTargetDuration",get:function(){return this.averagetargetduration||this.targetduration||DEFAULT_TARGET_DURATION}},{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 arrayValuesMatch(e,t){return e.length===t.length&&!e.some(function(e,r){return e!==t[r]})}function optionalArrayValuesMatch(e,t){return!e&&!t||!(!e||!t)&&arrayValuesMatch(e,t)}function isFullSegmentEncryption(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function getAesModeFromFullSegmentMethod(e){switch(e){case"AES-128":case"AES-256":return DecrypterAesMode.cbc;case"AES-256-CTR":return DecrypterAesMode.ctr;default:throw new Error("invalid full segment method ".concat(e))}}function strToUtf8array(e){return Uint8Array.from(unescape(encodeURIComponent(e)),function(e){return e.charCodeAt(0)})}function getKeyIdBytes(e){var t=strToUtf8array(e).subarray(0,16),r=new Uint8Array(16);return r.set(t,16-t.length),r}function changeEndianness(e){var t=function(e,t,r){var n=e[t];e[t]=e[r],e[r]=n};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function convertDataUriToArrayBytes(e){var t=e.split(":"),r=null;if("data"===t[0]&&2===t.length){var n=t[1].split(";"),i=n[n.length-1].split(",");if(2===i.length){var a="base64"===i[0],s=i[1];a?(n.splice(-1,1),r=base64Decode(s)):r=getKeyIdBytes(s)}}return r}var optionalSelf="undefined"!=typeof self?self:void 0,KeySystems={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},KeySystemFormats={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function keySystemFormatToKeySystemDomain(e){switch(e){case KeySystemFormats.FAIRPLAY:return KeySystems.FAIRPLAY;case KeySystemFormats.PLAYREADY:return KeySystems.PLAYREADY;case KeySystemFormats.WIDEVINE:return KeySystems.WIDEVINE;case KeySystemFormats.CLEARKEY:return KeySystems.CLEARKEY}}var KeySystemIds={WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function keySystemDomainToKeySystemFormat(e){switch(e){case KeySystems.FAIRPLAY:return KeySystemFormats.FAIRPLAY;case KeySystems.PLAYREADY:return KeySystemFormats.PLAYREADY;case KeySystems.WIDEVINE:return KeySystemFormats.WIDEVINE;case KeySystems.CLEARKEY:return KeySystemFormats.CLEARKEY}}function getKeySystemsForConfig(e){var t=e.drmSystems,r=e.widevineLicenseUrl,n=t?[KeySystems.FAIRPLAY,KeySystems.WIDEVINE,KeySystems.PLAYREADY,KeySystems.CLEARKEY].filter(function(e){return!!t[e]}):[];return!n[KeySystems.WIDEVINE]&&r&&n.push(KeySystems.WIDEVINE),n}var _requestMediaKeySystemAccess=function(e){return null!=optionalSelf&&null!=(e=optionalSelf.navigator)&&e.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function getSupportedMediaKeySystemConfigurations(e,t,r,n){var i;switch(e){case KeySystems.FAIRPLAY:i=["cenc","sinf"];break;case KeySystems.WIDEVINE:case KeySystems.PLAYREADY:i=["cenc"];break;case KeySystems.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error("Unknown key-system: ".concat(e))}return createMediaKeySystemConfigurations(i,t,r,n)}function createMediaKeySystemConfigurations(e,t,r,n){return[{initDataTypes:e,persistentState:n.persistentState||"optional",distinctiveIdentifier:n.distinctiveIdentifier||"optional",sessionTypes:n.sessionTypes||[n.sessionType||"temporary"],audioCapabilities:t.map(function(e){return{contentType:"audio/mp4; codecs=".concat(e),robustness:n.audioRobustness||"",encryptionScheme:n.audioEncryptionScheme||null}}),videoCapabilities:r.map(function(e){return{contentType:"video/mp4; codecs=".concat(e),robustness:n.videoRobustness||"",encryptionScheme:n.videoEncryptionScheme||null}})}]}function isPersistentSessionType(e){var t;return!(!e||"persistent-license"!==e.sessionType&&(null==(t=e.sessionTypes)||!t.some(function(e){return"persistent-license"===e})))}function parsePlayReadyWRM(e){var t=bin2str(new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2)),r=t.substring(t.indexOf("<"),t.length),n=(new DOMParser).parseFromString(r,"text/xml").getElementsByTagName("KID")[0];if(n){var i=n.childNodes[0]?n.childNodes[0].nodeValue:n.getAttribute("VALUE");if(i){var a=base64Decode(i).subarray(0,16);return changeEndianness(a),a}}return null}var keyUriToKeyIdMap={},LevelKey=function(){function e(t,r,n){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[1],a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null,s=arguments.length>5?arguments[5]:void 0;_classCallCheck(this,e),this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.scheme=void 0,this.method=t,this.uri=r,this.keyFormat=n,this.keyFormatVersions=i,this.iv=a,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&!isFullSegmentEncryption(t),null!=s&&s.startsWith("0x")&&(this.keyId=new Uint8Array(hexToArrayBuffer(s)))}return _createClass(e,[{key:"matches",value:function(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&arrayValuesMatch(e.keyFormatVersions,this.keyFormatVersions)&&optionalArrayValuesMatch(e.iv,this.iv)&&optionalArrayValuesMatch(e.keyId,this.keyId)}},{key:"isSupported",value:function(){if(this.method){if(isFullSegmentEncryption(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case KeySystemFormats.FAIRPLAY:case KeySystemFormats.WIDEVINE:case KeySystemFormats.PLAYREADY:case KeySystemFormats.CLEARKEY:return-1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}},{key:"getDecryptData",value:function(t,r){var n;if(!this.encrypted||!this.uri)return null;if(isFullSegmentEncryption(this.method)){var i=this.iv;return i||("number"!=typeof t&&(logger.warn('missing IV for initialization segment with method="'.concat(this.method,'" - compliance issue')),t=0),i=createInitializationVector(t)),new e(this.method,this.uri,"identity",this.keyFormatVersions,i)}if(this.keyId){var a=keyUriToKeyIdMap[this.uri];if(a&&!arrayValuesMatch(this.keyId,a)&&e.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}var s,o=convertDataUriToArrayBytes(this.uri);if(o)switch(this.keyFormat){case KeySystemFormats.WIDEVINE:if(this.pssh=o,!this.keyId){var l=parseMultiPssh(o.buffer).filter(function(e){return e.systemId===KeySystemIds.WIDEVINE});if(l.length){var u,c=l[0];this.keyId=null!=(u=c.kids)&&u.length?c.kids[0]:null}}this.keyId||(this.keyId=getKeyIdFromPlayReadyKey(r));break;case KeySystemFormats.PLAYREADY:var d=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=mp4pssh(d,null,o),this.keyId=parsePlayReadyWRM(o);break;default:var h=o.subarray(0,16);if(16!==h.length){var f=new Uint8Array(16);f.set(h,16-h.length),h=f}this.keyId=h}16!==(null==(n=this.keyId)?void 0:n.byteLength)&&((s=getKeyIdFromWidevineKey(r))||(s=getKeyIdFromPlayReadyKey(r))||(s=keyUriToKeyIdMap[this.uri]),s&&(this.keyId=s,e.setKeyIdForUri(this.uri,s)));return this}}],[{key:"clearKeyUriToKeyIdMap",value:function(){keyUriToKeyIdMap={}}},{key:"setKeyIdForUri",value:function(e,t){keyUriToKeyIdMap[e]=t}},{key:"addKeyIdForUri",value:function(e){var t=Object.keys(keyUriToKeyIdMap).length%Number.MAX_SAFE_INTEGER,r=new Uint8Array(16);return new DataView(r.buffer,12,4).setUint32(0,t),keyUriToKeyIdMap[e]=r,r}}])}();function getKeyIdFromWidevineKey(e){var t=null==e?void 0:e[KeySystemFormats.WIDEVINE];return t?t.keyId:null}function getKeyIdFromPlayReadyKey(e){var t=null==e?void 0:e[KeySystemFormats.PLAYREADY];if(t){var r=convertDataUriToArrayBytes(t.uri);if(r)return parsePlayReadyWRM(r)}return null}function createInitializationVector(e){for(var t=new Uint8Array(16),r=12;r<16;r++)t[r]=e>>8*(15-r)&255;return t}var MASTER_PLAYLIST_REGEX=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(I-FRAME-STREAM-INF|SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)(?:[\r\n]+|$)/g,MASTER_PLAYLIST_MEDIA_REGEX=/#EXT-X-MEDIA:(.*)/g,IS_MEDIA_PLAYLIST=/^#EXT(?:INF|-X-TARGETDURATION):/m,LEVEL_PLAYLIST_REGEX_FAST=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),LEVEL_PLAYLIST_REGEX_SLOW=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS|I-FRAMES-ONLY)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|")),M3U8Parser=function(){function e(){_classCallCheck(this,e)}return _createClass(e,null,[{key:"findGroup",value:function(e,t){for(var r=0;r<e.length;r++){var n=e[r];if(n.id===t)return n}}},{key:"resolve",value:function(e,t){return urlToolkitExports.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}},{key:"isMediaPlaylist",value:function(e){return IS_MEDIA_PLAYLIST.test(e)}},{key:"parseMasterPlaylist",value:function(t,r){var n,i={contentSteering:null,levels:[],iframeVariants:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:hasVariableReferences(t)},a=[];if(MASTER_PLAYLIST_REGEX.lastIndex=0,!t.startsWith("#EXTM3U"))return i.playlistParsingError=new Error("no EXTM3U delimiter"),i;for(;null!=(n=MASTER_PLAYLIST_REGEX.exec(t));)if(n[1]){var s=createVariant(new AttrList(n[1],i),n[2],r,i,a);s&&i.levels.push(s)}else if(n[3]){var o=n[3],l=n[4];switch(o){case"I-FRAME-STREAM-INF":var u=new AttrList(l,i),c=createVariant(u,u.URI,r,i,a,!0);c&&i.iframeVariants.push(c);break;case"SESSION-DATA":var d=new AttrList(l,i),h=d["DATA-ID"];h&&(null===i.sessionData&&(i.sessionData={}),i.sessionData[h]=d);break;case"SESSION-KEY":var f=parseKey(l,r,i);f.encrypted&&f.isSupported()?(null===i.sessionKeys&&(i.sessionKeys=[]),i.sessionKeys.push(f)):logger.warn('[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "'.concat(l,'"'));break;case"DEFINE":addVariableDefinition(i,new AttrList(l,i),r);break;case"CONTENT-STEERING":var v=new AttrList(l,i);i.contentSteering={uri:e.resolve(v["SERVER-URI"],r),pathwayId:v["PATHWAY-ID"]||"."};break;case"START":i.startTimeOffset=parseStartTimeOffset(l)}}var p=a.length>0&&a.length<i.levels.length;return i.levels=p?a:i.levels,0===i.levels.length&&(i.playlistParsingError=new Error("no levels found in manifest")),i}},{key:"parseMasterPlaylistMedia",value:function(t,r,n){var i,a={},s=n.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(MASTER_PLAYLIST_MEDIA_REGEX.lastIndex=0;null!==(i=MASTER_PLAYLIST_MEDIA_REGEX.exec(t));){var u=new AttrList(i[1],n),c=u.TYPE;if(c){var d=o[c],h=a[c]||[];a[c]=h;var f=u.LANGUAGE,v=u["ASSOC-LANGUAGE"],p=u.CHANNELS,g=u.CHARACTERISTICS,y=u["INSTREAM-ID"],m={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&&(m.assocLang=v),p&&(m.channels=p),g&&(m.characteristics=g),y&&(m.instreamId=y),null!=d&&d.length){var E=e.findGroup(d,m.groupId)||d[0];assignCodec(m,E,"audioCodec"),assignCodec(m,E,"textCodec")}h.push(m)}}return a}},{key:"parseLevelPlaylist",value:function(e,t,r,n,i,a){var s,o,l,u,c,d={url:t},h=new LevelDetails(t),f=h.fragments,v=[],p=null,g=0,y=0,m=0,E=0,S=0,T=null,k=new Fragment(n,d),_=-1,A=!1,b=null;if(LEVEL_PLAYLIST_REGEX_FAST.lastIndex=0,h.m3u8=e,h.hasVariableRefs=hasVariableReferences(e),"#EXTM3U"!==(null==(s=LEVEL_PLAYLIST_REGEX_FAST.exec(e))?void 0:s[0]))return h.playlistParsingError=new Error("Missing format identifier #EXTM3U"),h;for(;null!==(o=LEVEL_PLAYLIST_REGEX_FAST.exec(e));){A&&(A=!1,(k=new Fragment(n,d)).playlistOffset=m,k.setStart(m),k.sn=g,k.cc=E,S&&(k.bitrate=S),k.level=r,p&&(k.initSegment=p,p.rawProgramDateTime&&(k.rawProgramDateTime=p.rawProgramDateTime,p.rawProgramDateTime=null),b&&(k.setByteRange(b),b=null)));var L=o[1];if(L){k.duration=parseFloat(L);var R=(" "+o[2]).slice(1);k.title=R||null,k.tagList.push(R?["INF",L,R]:["INF",L])}else if(o[3]){if(isFiniteNumber(k.duration)){var C;k.playlistOffset=m,k.setStart(m),u&&setFragLevelKeys(k,u,h),k.sn=g,k.level=r,k.cc=E;var I=(" "+o[3]).slice(1);k.relurl=substituteVariables(h,I),assignProgramDateTime(k,T,v),T=k,m+=k.duration,g++,y=0;var P=k.byteRange;if(2===P.length&&(k.bitrate=8*(P[1]-P[0])/k.duration|0),h.iframesOnly&&P[0]&&(null==(C=p)?void 0:C.cc)!==E){var D=new Fragment(n,d);D.relurl=k.relurl,D.setByteRange("".concat(Math.min(P[0],1316),"@0")),D.level=r,D.sn="initSegment",u&&(D.levelkeys=u,u.identity&&(D._decryptdata=u.identity.getDecryptData(0))),p=D,k.initSegment=p}f.push(k),A=!0}}else{if(!(o=o[0].match(LEVEL_PLAYLIST_REGEX_SLOW))){logger.warn("No matches on slow regex match for level playlist!");continue}for(l=1;l<o.length&&void 0===o[l];l++);var w=(" "+o[l]).slice(1),O=(" "+o[l+1]).slice(1),x=o[l+2]?(" "+o[l+2]).slice(1):null;switch(w){case"BYTERANGE":T?k.setByteRange(O,T):k.setByteRange(O);break;case"PROGRAM-DATE-TIME":k.rawProgramDateTime=O,k.tagList.push(["PROGRAM-DATE-TIME",O]),-1===_&&(_=f.length);break;case"PLAYLIST-TYPE":h.type&&assignMultipleMediaPlaylistTagOccuranceError(h,w,o),h.type=O.toUpperCase();break;case"MEDIA-SEQUENCE":0!==h.startSN?assignMultipleMediaPlaylistTagOccuranceError(h,w,o):null!==T&&assignMustAppearBeforeSegmentsError(h,w,o),h.startSN=parseInt(O),g=h.startSN+h.skippedSegments;break;case"SKIP":h.skippedSegments&&assignMultipleMediaPlaylistTagOccuranceError(h,w,o);var M=new AttrList(O,h),F=M.decimalInteger("SKIPPED-SEGMENTS");if(isFiniteNumber(F)){h.skippedSegments+=F;for(var N=F;N--;)f.push(null);g+=F}var U=M.enumeratedString("RECENTLY-REMOVED-DATERANGES");U&&(h.recentlyRemovedDateranges=(h.recentlyRemovedDateranges||[]).concat(U.split("\t")));break;case"TARGETDURATION":0!==h.targetduration&&assignMultipleMediaPlaylistTagOccuranceError(h,w,o),h.targetduration=Math.max(parseInt(O),1);break;case"VERSION":null!==h.version&&assignMultipleMediaPlaylistTagOccuranceError(h,w,o),h.version=parseInt(O);break;case"INDEPENDENT-SEGMENTS":break;case"I-FRAMES-ONLY":h.iframesOnly=!0;break;case"ENDLIST":h.live||assignMultipleMediaPlaylistTagOccuranceError(h,w,o),h.live=!1;break;case"#":(O||x)&&k.tagList.push(x?[O,x]:[O]);break;case"DISCONTINUITY":E++,k.tagList.push(["DIS"]);break;case"GAP":k.gap=!0,k.tagList.push([w]);break;case"BITRATE":k.tagList.push([w,O]),S=1e3*parseInt(O),isFiniteNumber(S)?k.bitrate=S:S=0;break;case"DATERANGE":var B=new AttrList(O,h),G=new DateRange(B,h.dateRanges[B.ID],h.dateRangeTagCount);h.dateRangeTagCount++,G.isValid||h.skippedSegments?h.dateRanges[G.id]=G:logger.log("Ignoring invalid DATERANGE tag: ".concat(G.invalidReason,": ").concat(O)),k.tagList.push(["EXT-X-DATERANGE",O]);break;case"DEFINE":var H=new AttrList(O,h);"IMPORT"in H?importVariableDefinition(h,H,a):addVariableDefinition(h,H,t);break;case"DISCONTINUITY-SEQUENCE":0!==h.startCC&&assignMultipleMediaPlaylistTagOccuranceError(h,w,o),h.startCC=E=parseInt(O),f.forEach(function(e){return e&&(e.cc=E)});break;case"KEY":var $=parseKey(O,t,h);if($.isSupported()){if("NONE"===$.method){u=void 0;break}u||(u={});var K=u[$.keyFormat];null!=K&&K.matches($)||(K&&(u=_extends({},u)),u[$.keyFormat]=$)}else logger.warn('[Keys] Ignoring unsupported EXT-X-KEY tag: "'.concat(O,'"'));break;case"START":h.startTimeOffset=parseStartTimeOffset(O);break;case"MAP":var V=new AttrList(O,h);if(k.duration){var j=new Fragment(n,d);setInitSegment(j,V,r,u),p=j,k.initSegment=p,p.rawProgramDateTime&&!k.rawProgramDateTime&&(k.rawProgramDateTime=p.rawProgramDateTime)}else{var q=k.byteRangeEndOffset;if(q){var W=k.byteRangeStartOffset;b="".concat(q-W,"@").concat(W)}else b=null;setInitSegment(k,V,r,u),p=k,A=!0}p.cc=E;break;case"SERVER-CONTROL":c&&assignMultipleMediaPlaylistTagOccuranceError(h,w,o),c=new AttrList(O),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&&assignMultipleMediaPlaylistTagOccuranceError(h,w,o);var Y=new AttrList(O);h.partTarget=Y.decimalFloatingPoint("PART-TARGET");break;case"PART":var z=h.partList;z||(z=h.partList=[]);var X=y>0?z[z.length-1]:void 0,Q=y++,J=new AttrList(O,h),Z=new Part(J,k,d,Q,X);z.push(Z),k.duration+=Z.duration;break;case"PRELOAD-HINT":var ee=new AttrList(O,h);h.preloadHint=ee;break;case"RENDITION-REPORT":var te=new AttrList(O,h);h.renditionReports=h.renditionReports||[],h.renditionReports.push(te);break;default:logger.warn("line parsed but not handled: ".concat(o))}}}T&&!T.relurl?(f.pop(),m-=T.duration,h.partList&&(h.fragmentHint=T)):h.partList&&(assignProgramDateTime(k,T,v),k.cc=E,h.fragmentHint=k,u&&setFragLevelKeys(k,u,h)),h.targetduration||(h.playlistParsingError=new Error("Missing Target Duration"));var re=f.length,ne=f[0],ie=f[re-1];if((m+=h.skippedSegments*h.targetduration)>0&&re&&ie){h.averagetargetduration=m/re;var ae=ie.sn;h.endSN="initSegment"!==ae?ae:0,h.live||(ie.endList=!0),_>0&&(backfillProgramDateTimes(f,_,_>re-1?k:null),ne&&v.unshift(ne))}return h.fragmentHint&&(m+=h.fragmentHint.duration),h.totalduration=m,v.length&&h.dateRangeTagCount&&ne&&mapDateRanges(v,h),h.endCC=E,h}}])}();function createVariant(e,t,r,n,i,a){var s;if(void 0===t)return null;var o=substituteVariables(n,t),l={attrs:e,bitrate:e.decimalInteger("BANDWIDTH")||e.decimalInteger("AVERAGE-BANDWIDTH"),name:e.NAME,url:M3U8Parser.resolve(o,r)},u=e.decimalResolution("RESOLUTION");u&&(l.width=u.width,l.height=u.height),setCodecs(e.CODECS,l);var c=e["SUPPLEMENTAL-CODECS"];return c&&(l.supplemental={},setCodecs(c,l.supplemental)),null!=(s=l.unknownCodecs)&&s.length||i.push(l),a&&(l.iframes=!0),l}function mapDateRanges(e,t){var r=e.length;if(!r){if(!t.hasProgramDateTime)return;var n=t.fragments[t.fragments.length-1];e.push(n),r++}for(var i=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=i.ref;for(var c=r;c--;){var d;if((null==(d=e[c])?void 0:d.sn)<t.startSN)break;var h=findFragmentWithStartDate(t,u,e,c,a);if(h){l.tagAnchor=h.ref;break}}}}function findFragmentWithStartDate(e,t,r,n,i){var a=r[n];if(a){var s,o=a.programDateTime;if(t>=o||0===n)if(t<=o+1e3*(((null==(s=r[n+1])?void 0:s.start)||i)-a.start)){var l=a.sn-e.startSN,u=e.fragments;if(l>=0&&l<u.length){if(u.length>r.length)for(var c=r[n+1]||u[u.length-1],d=Math.min(c.sn-e.startSN,u.length-1);d>l;d--){var h=u[d].programDateTime;if(t>=h&&t<h+1e3*u[d].duration)return u[d]}return u[l]}}}return null}function parseKey(e,t,r){var n,i,a=new AttrList(e,r),s=null!=(n=a.METHOD)?n:"",o=a.URI,l=a.hexadecimalInteger("IV"),u=a.KEYFORMATVERSIONS,c=null!=(i=a.KEYFORMAT)?i:"identity";o&&a.IV&&!l&&logger.error("Invalid IV: ".concat(a.IV));var d=o?M3U8Parser.resolve(o,t):"",h=(u||"1").split("/").map(Number).filter(Number.isFinite);return new LevelKey(s,d,c,h,l,a.KEYID)}function parseStartTimeOffset(e){var t=new AttrList(e).decimalFloatingPoint("TIME-OFFSET");return isFiniteNumber(t)?t:null}function setCodecs(e,t){var r=(e||"").split(/[ ,]+/).filter(function(e){return e});["video","audio","text","image"].forEach(function(e){var n=r.filter(function(t){return isCodecType(t,e)});n.length&&(t["".concat(e,"Codec")]=n.map(function(e){return e.split("/")[0]}).join(","),r=r.filter(function(e){return-1===n.indexOf(e)}))}),t.unknownCodecs=r}function assignCodec(e,t,r){var n=t[r];n&&(e[r]=n)}function backfillProgramDateTimes(e,t,r){if(r||(r=e[t]),r)for(var n=t;n--;){var i=e[n];if(!i)return;i.programDateTime=r.programDateTime-1e3*i.duration,r=i}}function assignProgramDateTime(e,t,r){e.rawProgramDateTime?r.push(e):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function setInitSegment(e,t,r,n){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=r,e.sn="initSegment",n&&(e.levelkeys=n),e.initSegment=null}function setFragLevelKeys(e,t,r){e.levelkeys=t;var n=r.encryptedFragments;n.length&&n[n.length-1].levelkeys===t||!Object.keys(t).some(function(e){return t[e].isCommonEncryption})||n.push(e)}function assignMultipleMediaPlaylistTagOccuranceError(e,t,r){e.playlistParsingError=new Error("#EXT-X-".concat(t," must not appear more than once (").concat(r[0],")"))}function assignMustAppearBeforeSegmentsError(e,t,r){e.playlistParsingError=new Error("#EXT-X-".concat(t," must appear before the first Media Segment (").concat(r[0],")"))}function updateFromToPTS(e,t){var r=t.startPTS;if(isFiniteNumber(r)){var n,i=0;t.sn>e.sn?(i=r-e.start,n=e):(i=e.start-r,n=t),n.duration!==i&&n.setDuration(i)}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 updateFragPTSDTS(e,t,r,n,i,a,s,o){n-r<=0&&(o.warn("Fragment should have a positive duration",t),n=r+t.duration,a=i+t.duration);var l=r,u=n,c=t.startPTS,d=t.endPTS;if(isFiniteNumber(c)){var h=Math.abs(c-r);e&&h>e.totalduration?o.warn("media timestamps and playlist times differ by ".concat(h,"s for level ").concat(t.level," ").concat(e.url)):isFiniteNumber(t.deltaPTS)?t.deltaPTS=Math.max(h,t.deltaPTS):t.deltaPTS=h,l=Math.max(r,c),r=Math.min(r,c),i=void 0!==t.startDTS?Math.min(i,t.startDTS):i,u=Math.min(n,d),n=Math.max(n,d),a=void 0!==t.endDTS?Math.max(a,t.endDTS):a}var f=r-t.start;0!==t.start&&t.setStart(r),t.setDuration(n-t.start),t.startPTS=r,t.maxStartPTS=l,t.startDTS=i,t.endPTS=n,t.minEndPTS=u,t.endDTS=a;var v,p=t.sn;if(!e||p<e.startSN||p>e.endSN)return 0;var g=p-e.startSN,y=e.fragments;for(y[g]=t,v=g;v>0;v--)updateFromToPTS(y[v],y[v-1]);for(v=g;v<y.length-1;v++)updateFromToPTS(y[v],y[v+1]);return e.fragmentHint&&updateFromToPTS(y[y.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,f}function mergeDetails(e,t,r){if(e!==t){for(var n,i=null,a=e.fragments,s=a.length-1;s>=0;s--){var o=a[s].initSegment;if(o){i=o;break}}e.fragmentHint&&delete e.fragmentHint.endPTS,mapFragmentIntersection(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}isFiniteNumber(e.startPTS)&&isFiniteNumber(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&&(n=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,i=e.initSegment)});var l=t.fragments,u=t.fragmentHint?l.concat(t.fragmentHint):l;if(i&&u.forEach(function(e){var t;!e||e.initSegment&&e.initSegment.relurl!==(null==(t=i)?void 0:t.relurl)||(e.initSegment=i)}),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=mergeDateRanges(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&&assignProgramDateTime(u[h],u[h-1],d);mapDateRanges(d,t)}t.endCC=l[l.length-1].cc}if(!t.startCC){var f,v=getFragmentWithSN(e,t.startSN-1);t.startCC=null!=(f=null==v?void 0:v.cc)?f:l[0].cc}if(mapPartIntersection(e.partList,t.partList,function(e,t){t.elementaryStreams=e.elementaryStreams,t.stats=e.stats,t.gap=e.gap||t.gap}),n){var p=t.iframesOnly&&n.type===PlaylistLevelType.MAIN;updateFragPTSDTS(t,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,p,r)}else adjustSliding(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 y=t.edge;t.driftStart||(t.driftStartTime=g,t.driftStart=y),t.driftEndTime=g,t.driftEnd=y}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;-1===t.requestScheduled&&(t.requestScheduled=e.requestScheduled)}}function mergeDateRanges(e,t,r){var n=t.dateRanges,i=t.recentlyRemovedDateranges,a=_extends({},e);i&&i.forEach(function(e){delete a[e]});var s=Object.keys(a).length;return s?(Object.keys(n).forEach(function(e){var t=a[e],i=new DateRange(n[e].attr,t);i.isValid?(a[e]=i,t||(i.tagOrder+=s)):r.warn('Ignoring invalid Playlist Delta Update DATERANGE tag: "'.concat(stringify(n[e].attr),'"'))}),a):n}function mapPartIntersection(e,t,r){if(e&&t)for(var n=0,i=0,a=e.length;i<a;i++){var s=e[i],o=t[i+n];s&&o&&s.index===o.index&&s.fragment.sn===o.fragment.sn?r(s,o):n--}}function mapFragmentIntersection(e,t,r){for(var n,i=t.skippedSegments,a=Math.max(e.startSN,t.startSN)-t.startSN,s=(e.fragmentHint?1:0)+(i?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,o=t.startSN-e.startSN,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,u=null!=(n=e.fragmentHint)&&n.duration?e.fragments.concat(e.fragmentHint):e.fragments,c=a;c<=s;c++){var d=u[o+c],h=l[c];if(i&&!h&&d&&(h=t.fragments[c]=d),d&&h){r(d,h,c,l);var f=d.relurl,v=h.relurl;if(f&&notEqualAfterStrippingQueries(f,v))return void(t.playlistParsingError=getSequenceError("media sequence mismatch ".concat(h.sn,":"),e,t,d,h));if(d.cc!==h.cc)return void(t.playlistParsingError=getSequenceError("discontinuity sequence mismatch (".concat(d.cc,"!=").concat(h.cc,")"),e,t,d,h))}}}function getSequenceError(e,t,r,n,i){return new Error("".concat(e," ").concat(i.url,"\nPlaylist starting @").concat(t.startSN,"\n").concat(t.m3u8,"\n\nPlaylist starting @").concat(r.startSN,"\n").concat(r.m3u8))}function adjustSliding(e,t){var r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0,i=t.startSN+t.skippedSegments-e.startSN,a=e.fragments,s=i>=0,o=0;if(s&&i<a.length)o=a[i].start,null==n||n.log("Aligning playlists based on SN ".concat(t.startSN," (diff: ").concat(o,")"));else if(s&&t.startSN===e.endSN+1)o=e.fragmentEnd,null==n||n.log("Aligning playlists based on first/last SN ".concat(t.startSN," (diff: ").concat(o,")"));else if(s&&r)o=e.fragmentStart+i*t.levelTargetDuration;else{if(t.skippedSegments||0!==t.fragmentStart)return o;o=e.fragmentStart,null==n||n.log("Aligning playlists based on first SN ".concat(t.startSN," (diff: ").concat(o,")"))}return addSliding(t,o),o}function addSliding(e,t){if(t){for(var r=e.fragments,n=e.skippedSegments;n<r.length;n++)r[n].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}function computeReloadInterval(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1/0,r=1e3*e.targetduration;if(e.updated){var n=e.fragments;if(n.length&&4*r>t){var i=1e3*n[n.length-1].duration;i>0&&i<r&&(r=i)}}else r/=2;return Math.round(r)}function getFragmentWithSN(e,t,r){var n;if(!e)return null;var i=e.fragments[t-e.startSN];return i||((null==(n=i=e.fragmentHint)?void 0:n.sn)===t?i:r&&t<e.startSN&&r.sn===t?r:null)}function getPartWith(e,t,r){return e?findPart(e.partList,t,r):null}function findPart(e,t,r){if(e)for(var n=e.length;n--;){var i=e[n];if(i.index===r&&i.fragment.sn===t)return i}return null}function reassignFragmentLevelIndexes(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 notEqualAfterStrippingQueries(e,t){return!(e===t||!t)&&stripQuery(e)!==stripQuery(t)}function stripQuery(e){return e.replace(/\?[^?]*$/,"")}function findFirstFragWithCC(e,t){for(var r=0,n=e.length;r<n;r++){var i;if((null==(i=e[r])?void 0:i.cc)===t)return e[r]}return null}function shouldAlignOnDiscontinuities(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}function adjustFragmentStart(e,t){var r=e.start+t;e.setStart(r)}function adjustSlidingStart(e,t){for(var r=t.fragments,n=0,i=r.length;n<i;n++)adjustFragmentStart(r[n],e);t.fragmentHint&&adjustFragmentStart(t.fragmentHint,e),t.alignedSliding=!0}function alignStream(e,t,r){e&&(alignDiscontinuities(t,e,r),t.alignedSliding||alignMediaPlaylistByPDT(t,e,r),t.alignedSliding||t.skippedSegments||adjustSliding(e,t,!1,r))}function alignDiscontinuities(e,t,r){if(shouldAlignOnDiscontinuities(t,e)){var n=Math.min(t.endCC,e.endCC),i=findFirstFragWithCC(t.fragments,n),a=findFirstFragWithCC(e.fragments,n);if(i&&a){var s=i.start-a.start;r.log("Aligning playlists using dicontinuity sequence ".concat(n," (diff: ").concat(s,")")),adjustSlidingStart(s,e)}}}function alignMediaPlaylistByPDT(e,t,r){if(e.hasProgramDateTime&&t.hasProgramDateTime){var n=e.fragments,i=t.fragments;if(n.length&&i.length){var a,s,o=Math.min(t.endCC,e.endCC);t.startCC<o&&e.startCC<o&&(a=findFirstFragWithCC(i,o),s=findFirstFragWithCC(n,o)),a&&s||(s=findFirstFragWithCC(n,(a=i[Math.floor(i.length/2)]||i.filter(function(e){return!!e})[0]).cc)||n[Math.floor(n.length/2)]);var l=a.programDateTime,u=s.programDateTime;if(l&&u){var c=(u-l)/1e3;if(Math.abs(c)>Math.max(60,e.totalduration))r.log("Cannot align playlists using PDT without overlap (".concat(Math.abs(c)," > ").concat(e.totalduration,")"));else{var d=c-(s.start-a.start);r.log("Aligning playlists using PDT (diff: ".concat(d,")")),adjustSlidingStart(d,e)}}}}}function addEventListener(e,t,r){removeEventListener(e,t,r),e.addEventListener(t,r)}function removeEventListener(e,t,r){e.removeEventListener(t,r)}function timeRangesToString(e){for(var t="",r=e.length,n=0;n<r;n++)t+="[".concat(e.start(n).toFixed(3),"-").concat(e.end(n).toFixed(3),"]");return t}var State={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"},BaseStreamController=function(){function e(t,r,n,i,a){var s;return _classCallCheck(this,e),(s=_callSuper(this,e,[i,t.logger])).hls=void 0,s.fragPrevious=null,s.fragCurrent=null,s.fragPlaying=null,s.fragmentTracker=void 0,s.transmuxer=null,s._state=State.STOPPED,s.playlistType=void 0,s.media=null,s.mediaBuffer=null,s.config=void 0,s.bitrateTest=!1,s.lastCurrentTime=0,s.nextLoadPosition=0,s.startPosition=-1,s.startTimeOffset=null,s.retryDate=0,s.levels=null,s.fragmentLoader=void 0,s.initFragmentLoader=void 0,s.keyLoader=void 0,s.levelLastLoaded=null,s.startFragRequested=!1,s.decrypter=void 0,s.initPTS=[],s.buffering=!0,s.loadingParts=!1,s.loopSn=void 0,s.onMediaSeeking=function(){var e=s,t=e.config,r=e.fragCurrent,n=e.media,i=e.mediaBuffer,a=e.state,o=n?n.currentTime:0,l=BufferHelper.bufferInfo(i||n,o,t.maxBufferHole),u=l.len;if(s.log("Media seeking to ".concat(o,", state: ").concat(a,", ").concat(u?"in":"out of"," buffer")),s.state===State.ENDED)s.resetLoadingState();else if(r){var c=t.maxFragLookUpTolerance,d=r.start-c,h=r.start+r.duration+c;if(!u||h<l.start||d>l.end){var f=o<d,v=o>h;(f||v)&&(!r.loader||!v&&s.isFragmentNearlyDownloaded(r)?s.fragPrevious=null:(s.log("Cancelling fragment load for seek (sn: ".concat(r.sn,") - ").concat(f?"backward":"forward"," seek")),r.abortRequests(),s.resetLoadingState()))}}if(n&&(s.fragmentTracker.removeFragmentsInRange(o,1/0,s.playlistType,!0),o>s.lastCurrentTime&&(s.lastCurrentTime=o),!s.loadingParts)){var p=Math.max(l.end,o),g=s.shouldLoadParts(s.getLevelDetails(),p);g&&(s.log("LL-Part loading ON after seeking to ".concat(o," with buffer @").concat(p)),s.loadingParts=g)}var y=!BufferHelper.isBuffered(n,o);s.hls.hasEnoughToStart&&!y||(s.log("Setting ".concat(y?"startPosition":"nextLoadPosition"," to ").concat(o," for seek without enough to start")),s.nextLoadPosition=o,y&&(s.startPosition=o)),u<1&&s.state===State.IDLE&&s.tickImmediate()},s.onMediaEnded=function(){s.log("setting startPosition to 0 because media ended"),s.startPosition=s.lastCurrentTime=0},s.playlistType=a,s.hls=t,s.fragmentLoader=new FragmentLoader(t.config),s.initFragmentLoader=new FragmentLoader(t.config),s.keyLoader=n,s.fragmentTracker=r,s.config=t.config,s.decrypter=new Decrypter(t.config),s}return _inherits(e,TaskLoop),_createClass(e,[{key:"registerListeners",value:function(){var e=this.hls;e.on(Events$2.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Events$2.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events$2.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events$2.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Events$2.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(Events$2.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Events$2.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events$2.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events$2.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Events$2.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!==State.STOPPED){this.fragmentLoader.abort(),this.initFragmentLoader.abort(),this.keyLoader.abort(this.playlistType);var e=this.fragCurrent;null!=e&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=State.STOPPED}}},{key:"startPositionValue",get:function(){var e=this.nextLoadPosition,t=this.startPosition;if(-1===t&&e){var r=this.getLevelDetails();return null!=r&&r.live?(this.hls.liveSyncPosition||r.fragmentStart)+this.timelineOffset:e}return t}},{key:"bufferingEnabled",get:function(){return this.buffering}},{key:"backtrackFragment",get:function(){},set:function(e){}},{key:"couldBacktrack",get:function(){return!1},set:function(e){}},{key:"pauseBuffering",value:function(){this.buffering=!1}},{key:"resumeBuffering",value:function(){this.buffering=!0}},{key:"inFlightFrag",get:function(){return{frag:this.fragCurrent,state:this.state}}},{key:"_streamEnded",value:function(e,t){if(t.live||!this.media)return!1;var r=e.end||0,n=this.config.timelineOffset||0;if(r<=n)return!1;var i=e.buffered;this.config.maxBufferHole&&i&&i.length>1&&(e=BufferHelper.bufferedInfo(i,e.start,0));var a=e.nextStart;if(a&&a>n&&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 BufferHelper.isBuffered(this.media,o.start+o.duration/2)}var l=t.fragments[t.fragments.length-1];return this.fragmentTracker.isEndListAppended(l.type)}},{key:"getLevelDetails",value:function(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}},{key:"timelineOffset",get:function(){var e,t=this.config.timelineOffset;return t?(null==(e=this.getLevelDetails())?void 0:e.appliedTimelineOffset)||t:0}},{key:"onMediaAttached",value:function(e,t){var r=this.media=this.mediaBuffer=t.media;addEventListener(r,"seeking",this.onMediaSeeking),addEventListener(r,"ended",this.onMediaEnded);var n=this.config;this.levels&&n.autoStartLoad&&this.state===State.STOPPED&&this.startLoad(n.startPosition)}},{key:"onMediaDetaching",value:function(e,t){this.fragPlaying=null;var r=!!t.transferMedia,n=this.media;if(null!==n){if(n.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),removeEventListener(n,"seeking",this.onMediaSeeking),removeEventListener(n,"ended",this.onMediaEnded),this.media=this.mediaBuffer=null,this.loopSn=void 0,r)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}},{key:"onManifestLoading",value:function(){this.initPTS=[],this.fragPlaying=this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=0,this.startPosition=-1,this.startFragRequested=!1}},{key:"onError",value:function(e,t){}},{key:"onManifestLoaded",value:function(e,t){this.startTimeOffset=t.startTimeOffset}},{key:"onHandlerDestroying",value:function(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),_superPropGet(e,"onHandlerDestroying",this)([]),this.hls=this.onMediaSeeking=this.onMediaEnded=null}},{key:"onHandlerDestroyed",value:function(){this.state=State.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.initFragmentLoader&&this.initFragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.decrypter=this.keyLoader=null,this.fragmentLoader=this.initFragmentLoader=this.fragmentTracker=null,_superPropGet(e,"onHandlerDestroyed",this)([])}},{key:"loadFragment",value:function(e,t,r){this.startFragRequested=!0,this._loadFragForPlayback(e,t,r)}},{key:"_loadFragForPlayback",value:function(e,t,r){var n=this;this._doFragLoad(e,t,r,function(e){var t=e.frag;if(n.fragContextChanged(t))return n.warn("".concat(t.type," sn: ").concat(t.sn).concat(e.part?" part: "+e.part.index:""," of ").concat(n.fragInfo(t,!1,e.part)," was dropped during download.")),void n.fragmentTracker.removeFragment(t);var r=++t.stats.chunkCount;n.log("load progress ".concat(t.type," sn: ").concat(t.sn).concat(e.part?" part: "+e.part.index:""," of ").concat(n.fragInfo(t,!1,e.part)," chunk: ").concat(r)),n._handleFragmentLoadProgress(e)}).then(function(e){if(e){var t=n.state,r=e.frag;n.fragContextChanged(r)?(t===State.FRAG_LOADING||!n.fragCurrent&&t===State.PARSING)&&(n.fragmentTracker.removeFragment(r),n.state=State.IDLE):("payload"in e&&(n.log("Loaded ".concat(r.type," sn: ").concat(r.sn," of ").concat(n.playlistLabel()," ").concat(r.level," (bytes ").concat(r.stats.loaded,")")),n.hls.trigger(Events$2.FRAG_LOADED,e)),n._handleFragmentLoadComplete(e))}}).catch(function(t){n.state!==State.STOPPED&&n.state!==State.ERROR&&(n.log("Frag error ".concat(e.type," sn:").concat(e.sn," cc:").concat(e.cc,": ").concat((null==t?void 0:t.message)||t)),n.resetFragmentLoading(e))})}},{key:"clearTrackerIfNeeded",value:function(e){var t,r=this.fragmentTracker;if(r.getState(e)===FragmentState.APPENDING){var n=e.type,i=this.getFwdBufferInfo(this.mediaBuffer,n),a=Math.max(e.duration,i?i.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)===FragmentState.PARTIAL&&r.removeFragment(e))}},{key:"checkLiveUpdate",value:function(e){if(e.updated&&!e.live){var t=this.fragmentTracker,r=e.fragments[e.fragments.length-1];if(r.endList&&!t.isEndListAppended(this.playlistType)){var n=t.getPartialFragment(r.end);n&&(t.removeFragment(n),t.fragBuffered(r,!0))}t.detectPartialFragments({frag:r,part:null,stats:r.stats,id:r.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}},{key:"waitForLive",value:function(e){var t=e.details;return(null==t?void 0:t.live)&&"EVENT"!==t.type&&(this.levelLastLoaded!==e||t.expired)}},{key:"flushMainBuffer",value:function(e,t){if(e-t){var r={startOffset:e,endOffset:t,type:arguments.length>2&&void 0!==arguments[2]?arguments[2]:null};this.hls.trigger(Events$2.BUFFER_FLUSHING,r)}}},{key:"_loadInitSegment",value:function(e){var t=this,r=this.hls;return this.initFragmentLoader.abort(),r.trigger(Events$2.FRAG_LOADING,{frag:e,targetBufferTime:0}),this.initFragmentLoader.load(e).then(function(e){var r,n=e.frag;if(!t.levels||!fragmentsAreEqual(n,null==(r=t.fragCurrent)?void 0:r.initSegment))throw new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.INTERNAL_ABORTED,error:new Error("init load aborted"),fatal:!1,frag:n,networkDetails:null});return e}).then(function(e){var n=e.frag,i=e.payload,a=n.decryptdata;if(i&&i.byteLength>0&&null!=a&&a.key&&a.iv&&isFullSegmentEncryption(a.method)){var s=self.performance.now(),o=getAESAdjustments(n,null,t.iframesOnly).decryptRange;return t.decrypter.decrypt(new Uint8Array(i),a.key.buffer,a.iv.buffer,getAesModeFromFullSegmentMethod(a.method),o).catch(function(e){throw r.trigger(Events$2.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:n}),t.fragmentLoader.abort(),e}).then(function(i){var a=self.performance.now();return r.trigger(Events$2.FRAG_DECRYPTED,{frag:n,part:null,payload:i,stats:{tstart:s,tdecrypt:a}}),e.payload=i,t.completeInitSegmentLoad(e)})}return t.completeInitSegmentLoad(e)})}},{key:"completeInitSegmentLoad",value:function(e){var t=e.frag.stats;e.frag.data=new Uint8Array(e.payload),t.parsing.start=t.buffering.start=self.performance.now(),t.parsing.end=t.buffering.end=self.performance.now()}},{key:"loadInitSegmentIfNeeded",value:function(e){var t,r=this,n=e.initSegment;if(!this.bitrateTest&&isMediaFragment(e)&&n&&!n.data)return(!n.encrypted||null!=(t=n.decryptdata)&&t.key?this._loadInitSegment(n):this.keyLoader.load(n).then(function(){return r._loadInitSegment(n)})).catch(function(t){if(r.state===State.STOPPED||r.state===State.ERROR)throw t;throw"data"in t&&(t.data.frag=e,r.fragmentLoader.abort(),r.handleFragLoadError(t)),r.resetFragmentLoading(e),t})}},{key:"unhandledEncryptionError",value:function(e,t){var r,n,i=e.tracks;if(i&&!t.encrypted&&(null!=(r=i.audio)&&r.encrypted||null!=(n=i.video)&&n.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(Events$2.ERROR,{type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.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||!fragmentsAreEqual(e,t)}},{key:"fragBufferedComplete",value:function(e,t){var r=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log("Buffered ".concat(e.type," sn: ").concat(e.sn).concat(t?" part: "+t.index:""," of ").concat(this.fragInfo(e,!1,t)," > buffer:").concat(r?timeRangesToString(BufferHelper.getBuffered(r)):"(detached)",")")),isMediaFragment(e)){var n;if(e.type!==PlaylistLevelType.SUBTITLE){var i=e.elementaryStreams;if(!Object.keys(i).some(function(e){return!!i[e]}))return void(this.state=State.IDLE)}var a=null==(n=this.levels)?void 0:n[e.level];null!=a&&a.fragmentError&&(t||this.fragmentTracker.getState(e)!==FragmentState.PARTIAL)&&(this.log("Resetting level fragment error count of ".concat(a.fragmentError," on frag buffered")),a.fragmentError=0,e.stats.retry=0)}this.state=State.IDLE}},{key:"_handleFragmentLoadComplete",value:function(e){var t=this.transmuxer;if(t){var r=e.frag,n=e.part,i=e.partsLoaded,a=!i||0===i.length||i.some(function(e){return!e}),s=getAESAdjustments(r,n).decryptRange,o=new ChunkMetadata(r.level,r.sn,r.stats.chunkCount+1,0,n?n.index:-1,!a,r.duration,this.iframesOnly,s);this.log("load complete ".concat(r.type," sn: ").concat(r.sn).concat(n?" part: "+n.index:""," of ").concat(this.fragInfo(r,!1,n))),t.flush(o)}}},{key:"_handleFragmentLoadProgress",value:function(e){}},{key:"loadKeyFor",value:function(e,t,r){var n,i=this,a=null;return!e.encrypted||null!=(n=e.decryptdata)&&n.key?e.encrypted||(a=this.keyLoader.loadClear(e,t.encryptedFragments,this.startFragRequested))&&this.log("[eme] blocking frag sn: ".concat(e.sn," load until media-keys acquired")):(this.log("Loading key for ".concat(e.sn," of [").concat(t.startSN,"-").concat(t.endSN,"], ").concat(this.playlistLabel()," ").concat(e.level)),this.state=State.KEY_LOADING,a=this.keyLoader.load(e,r).then(function(e){if(!i.fragContextChanged(e.frag))return i.hls.trigger(Events$2.KEY_LOADED,e),i.state===State.KEY_LOADING&&(i.state=State.IDLE),e}),this.hls.trigger(Events$2.KEY_LOADING,{frag:e})),a}},{key:"_doFragLoad",value:function(e,t){var r=this,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,i=arguments.length>3?arguments[3]:void 0;this.fragCurrent=e;var a=t.details;if(!this.levels||!a)throw new Error("frag load aborted, missing level".concat(a?"":" detail","s"));var s,o=this.fragPrevious;if(!mediaFragmentsAreEqual(e,o)){var l=this.shouldLoadParts(t.details,e.end);l!==this.loadingParts&&(this.log("LL-Part loading ".concat(l?"ON":"OFF"," loading sn ").concat(null==o?void 0:o.sn,"->").concat(e.sn)),this.loadingParts=l)}if(n=Math.max(e.start,n||0),this.loadingParts){var u=a.partList;if(u&&i){n>a.fragmentEnd&&a.fragmentHint&&(e=a.fragmentHint);var c=this.getNextPart(u,e,n);if(c>-1){var d=u[c];if(!mediaFragmentsAreEqual(e=this.fragCurrent=d.fragment,o)&&!this.shouldLoadParts(t.details,e.end))return this.log("LL-Part loading OFF @".concat(this.playhead," next part: ").concat(this.fragInfo(e,!1,d))),this.loadingParts=!1,Promise.resolve(null);if(!this.filterReplacedPrimary(d,t.details))return Promise.resolve(null);var h,f=this.loadKeyFor(e,a);if(this.fragContextChanged(e))return Promise.resolve(null);this.log("Loading ".concat(e.type," sn: ").concat(e.sn," part: ").concat(d.index," (").concat(c,"/").concat(u.length-1,") of ").concat(this.fragInfo(e,!1,d)," cc: ").concat(e.cc," [").concat(a.startSN,"-").concat(a.endSN,"], target: ").concat(n).concat(d.byteRange.length?" range:".concat(d.byteRange.join("-")):"")),this.nextLoadPosition=d.start+d.duration,this.state=State.FRAG_LOADING;var v=this.loadInitSegmentIfNeeded(e);if(f||v){var p=!!f;h=Promise.all([f,v]).then(function(n){var a=_slicedToArray(n,1)[0];return!p||a&&!r.fragContextChanged(a.frag)?r.doFragPartsLoad(e,d,t,i):null}).catch(function(e){return r.handleFragLoadError(e)})}else h=this.doFragPartsLoad(e,d,t,i).catch(function(e){return r.handleFragLoadError(e)});return this.hls.trigger(Events$2.FRAG_LOADING,{frag:e,part:d,targetBufferTime:n}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):h}if(!e.url||this.loadedEndOfParts(u,n))return Promise.resolve(null)}}if(this.loadingParts)this.log("LL-Part loading OFF after next part miss @".concat(n," Check buffer at sn: ").concat(e.sn," loaded parts: ").concat(null==(s=a.partList)?void 0:s.filter(function(e){return e.loaded}).map(function(e){return"[".concat(e.start,"-").concat(e.end,"]")}))),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);if(!this.filterReplacedPrimary(e,t.details))return Promise.resolve(null);var g,y=this.loadInitSegmentIfNeeded(e),m=this.loadKeyFor(e,a,y);if(this.fragContextChanged(e))return this.log("Context changed in KEY_LOADING sn: ".concat(e.sn," ").concat(e.relurl," > ").concat(null==(g=this.fragCurrent)?void 0:g.relurl)),null==y||y.catch(function(){return null}),null==m||m.catch(function(){return null}),Promise.resolve(null);this.log("Loading ".concat(e.type," sn: ").concat(e.sn," of ").concat(this.fragInfo(e,!1)," cc: ").concat(e.cc," ").concat("["+a.startSN+"-"+a.endSN+"]",", target: ").concat(n).concat(e.byteRange.length?" range:".concat(e.byteRange.join("-")):"")),isFiniteNumber(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=State.FRAG_LOADING;var E,S=this.config.progressive&&e.type!==PlaylistLevelType.SUBTITLE;return E=S&&m?m.then(function(t){return!t||r.fragContextChanged(t.frag)?null:r.fragmentLoader.load(e,r.iframesOnly,i,y)}).catch(function(e){return r.handleFragLoadError(e)}):Promise.all([this.fragmentLoader.load(e,this.iframesOnly,S?i:void 0,S?y:void 0),m,y]).then(function(e){var t=_slicedToArray(e,1)[0];return!S&&i&&i(t),t}).catch(function(e){return r.handleFragLoadError(e)}),this.hls.trigger(Events$2.FRAG_LOADING,{frag:e,targetBufferTime:n}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):Promise.all([E,y]).then(function(e){return _slicedToArray(e,1)[0]})}},{key:"doFragPartsLoad",value:function(e,t,r,n){var i=this;return new Promise(function(a,s){var o,l=[],u=null==(o=r.details)?void 0:o.partList,c=function(t){i.fragmentLoader.loadPart(e,t,n).then(function(n){l[t.index]=n;var s=n.part;i.hls.trigger(Events$2.FRAG_LOADED,n);var o=getPartWith(r.details,e.sn,t.index+1)||findPart(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===ErrorDetails.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===ErrorTypes.KEY_SYSTEM_ERROR&&!t.fatal&&(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)),this.hls.trigger(Events$2.ERROR,t)}else this.hls.trigger(Events$2.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}},{key:"_handleTransmuxerFlush",value:function(e){var t=this.getCurrentContext(e);if(t&&this.state===State.PARSING){var r=t.frag,n=t.part,i=t.level,a=self.performance.now();r.stats.parsing.end=a,n&&(n.stats.parsing.end=a);var s=this.getLevelDetails(),o=s&&r.sn>s.endSN||this.shouldLoadParts(s,r.end);o!==this.loadingParts&&(this.log("LL-Part loading ".concat(o?"ON":"OFF"," after parsing segment ending @").concat(r.end)),this.loadingParts=o),this.updateLevelTiming(r,n,i,e)}else this.fragCurrent||this.state===State.STOPPED||this.state===State.ERROR||(this.state=State.IDLE)}},{key:"shouldLoadParts",value:function(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList&&!this.iframesOnly){var r,n=e.partList[0];if(t>=n.end+((null==(r=e.fragmentHint)?void 0:r.duration)||0))if(this.playhead>n.start-n.fragment.duration)return!0}}return!1}},{key:"getCurrentContext",value:function(e){var t=this.levels,r=this.fragCurrent,n=e.level,i=e.sn,a=e.part;if(null==t||!t[n])return this.warn("Levels object was unset while buffering fragment ".concat(i," of ").concat(this.playlistLabel()," ").concat(n,". The current chunk will not be buffered.")),null;var s=t[n],o=s.details,l=a>-1?getPartWith(o,i,a):null,u=l?l.fragment:getFragmentWithSN(o,i,r);return u?(r&&r!==u&&(u.stats=r.stats),{frag:u,part:l,level:s}):null}},{key:"bufferFragmentData",value:function(e,t,r,n,i){if(this.state===State.PARSING){isMediaFragment(t)&&!this.fragContextChanged(t)&&(this.fragPrevious=t);var a=e.data1,s=e.data2,o=a;if(s&&(o=appendUint8Array(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:n,offset:u,parent:t.type,data:o};if(this.hls.trigger(Events$2.BUFFER_APPENDING,c),e.dropped&&e.independent&&!r){if(i)return;this.flushBufferGap(t)}}}}},{key:"flushBufferGap",value:function(e){var t=this.media;if(t)if(BufferHelper.isBuffered(t,t.currentTime)){var r=t.currentTime,n=BufferHelper.bufferInfo(t,r,0),i=e.duration,a=Math.min(2*this.config.maxFragLookUpTolerance,.25*i),s=Math.max(Math.min(e.start-a,n.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,n=this.playhead,i=this.lastCurrentTime>n||null!=(r=this.media)&&r.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,n,t,i)}},{key:"getFwdBufferInfoAtPos",value:function(e,t,r,n){var i=BufferHelper.bufferInfo(e,t,n);if(0===i.len&&void 0!==i.nextStart){var a=this.fragmentTracker.getBufferedFrag(t,r);if(a&&(i.nextStart<=a.end||a.gap)){var s=Math.max(Math.min(i.nextStart,a.end)-t,n);return BufferHelper.bufferInfo(e,t,s)}}return i}},{key:"getMaxBufferLength",value:function(e){var t,r=this.config;return t=e?Math.max(8*r.maxBufferSize/e,r.maxBufferLength):r.maxBufferLength,Math.min(t,r.maxMaxBufferLength)}},{key:"exceedsMaxBuffer",value:function(e,t,r){var n=e.nextStart;if(n&&r.start>n){var i=e.buffered;if(i){for(var a=e.len,s=e.bufferedIndex,o=i.length-1;o>s;o--)i[o].start<r.start&&(a+=i[o].end-i[o].start);return a>=t}}return!1}},{key:"reduceMaxBufferLength",value:function(e,t){var r=this.config,n=Math.max(Math.min(e-t,r.maxBufferLength),t/2),i=Math.max(e-3*t,r.maxMaxBufferLength/2,n);return i>=n&&(r.maxMaxBufferLength=i,this.warn("Reduce max buffer length to ".concat(i,"s")),!0)}},{key:"getAppendedFrag",value:function(e){var t=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,this.playlistType):null;return t&&"fragment"in t?t.fragment:t}},{key:"getNextFragment",value:function(e,t){var r=t.fragments,n=r.length;if(!n)return null;var i=this.config,a=t.fragmentStart,s=i.lowLatencyMode&&!!t.partList,o=null;if(t.live){var l=i.initialLiveManifestSize;if(n<l)return this.warn("Not enough fragments to start playback (have: ".concat(n,", need: ").concat(l,")")),null;if(this.startFragRequested||!s||this.loadingParts||(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),!t.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||e<a){var u;o=this.getInitialLiveFragment(t);var c,d,h=this.config.startPosition,f=this.hls.startPosition,v=this.hls.liveSyncPosition,p=(null==(u=o)?void 0:u.start)||0;if(-1!==f&&f>=a?(c=f,d=f===h?"config":"next load start"):v?(c=v,d="live edge"):(c=e,d="buffer pos"),c<p&&(c=p,d="live frag start"),c<a&&(c=a,d="playlist start"),this.startPosition!=c||this.nextLoadPosition!=c){var g=t.live&&!this.filterReplacedPrimary(o,t)?-1:c;this.log("Setting startPosition to ".concat(g," next load ").concat(c," ").concat(-1===f?"":"(from ".concat(h,") "),"based on ").concat(d,". live edge: ").concat(v," live frag start: ").concat(p," playlist start: ").concat(a," buffer pos: ").concat(e)),this.startPosition=g,this.nextLoadPosition=c}}}else e<=a&&(o=r[0]);if(!o){var y=this.loadingParts?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,y,t)}var m=this.filterReplacedPrimary(o,t);return!m&&o&&(m=getNextFrag(t,o.sn))&&(this.nextLoadPosition=m.start),m}},{key:"isLoopLoading",value:function(e,t){if(this.nextLoadPosition<=t)return!1;var r=this.fragmentTracker.getState(e);if(r===FragmentState.OK)return!0;if(r===FragmentState.PARTIAL){if(e.gap)return!0;if(e.stats.retry>1)return!0}return!1}},{key:"getNextFragmentLoopLoading",value:function(e,t,r,n,i){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,n,0);if(null!==s&&r.len+s.len>=i){var o=a.sn;return this.loopSn!==o&&(this.log('buffer full after gaps in "'.concat(n,'" playlist starting at sn: ').concat(o)),this.loopSn=o),null}}return this.loopSn=void 0,a}},{key:"primaryPrefetch",get:function(){var e;if(interstitialsEnabled(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(interstitialsEnabled(this.config)&&("type"in e?e:e.fragment).type!==PlaylistLevelType.SUBTITLE){var r=this.hls.interstitialsManager,n=null==r?void 0:r.bufferingItem;if(n){var i=n.event;if(i){if(!i.appendInPlace&&(Math.abs(e.start-n.start)>1||0===n.start))return null}else{if(e.end<=n.start&&!1===(null==t?void 0:t.live))return null;if(e.start>=n.end&&n.nextEvent&&(n.nextEvent.appendInPlace&&!n.nextEvent.hasPlayed||e.start-n.end>1))return null}}if(fragOverlapsQueuedInterstitial(e,null==r?void 0:r.playerQueue,this.playhead))return null}return e}},{key:"getNextPart",value:function(e,t,r){for(var n=-1,i=!1,a=!0,s=0,o=e.length;s<o;s++){var l=e[s];if(a=a&&!l.independent,n>-1&&r<l.start)break;var u=l.loaded||l.gap;u?n=-1:(i||(l.independent||a)&&l.fragment===t)&&(n=s),i=u&&!l.gap}var c=e[n];return c&&c.fragment!==t&&this.log("Need buffer at ".concat(r," but next unloaded part starts at ").concat(c.start," (sn: ").concat(t.sn," -> ").concat(c.fragment.sn,")")),n}},{key:"loadedEndOfParts",value:function(e,t){for(var r,n=e.length;n--;){if(!(r=e[n]).loaded)return!1;if(t>r.start)return!0}return!1}},{key:"getInitialLiveFragment",value:function(e){var t=e.fragments,r=this.fragPrevious,n=null;if(r){if(e.hasProgramDateTime&&(n=findFragmentByPDT(t,r.endProgramDateTime,this.config.maxFragLookUpTolerance))&&this.log("Live playlist, switching playlist, load frag with same PDT: ".concat(r.programDateTime)),!n){var i=r.sn+1;if(i>=e.startSN&&i<=e.endSN){var a=t[i-e.startSN];r.cc===a.cc&&(n=a,this.log("Live playlist, switching playlist, load frag with next SN: ".concat(n.sn)))}n||(n=findNearestWithCC(e,r.cc,r.end))&&this.log("Live playlist, switching playlist, load frag with same CC: ".concat(n.sn))}}else{var s=this.hls.liveSyncPosition;null!==s&&(n=this.getFragmentAtPosition(s,this.bitrateTest?e.fragmentEnd:e.edge,e))}return n}},{key:"getFragmentAtPosition",value:function(e,t,r){var n,i,a=this.config,s=this.fragPrevious,o=r.fragments,l=r.endSN,u=r.fragmentHint,c=a.maxFragLookUpTolerance,d=r.partList,h=!!(this.loadingParts&&null!=d&&d.length&&u);(h&&!this.bitrateTest&&d[d.length-1].fragment.sn===u.sn&&(o=o.concat(u),l=u.sn),s&&this.fragmentTracker.getState(s)===FragmentState.NOT_LOADED&&(s=null),e<t)?n=findFragmentByPTS(s,o,e,e<this.lastCurrentTime||e>t-c||null!=(i=this.media)&&i.paused||!this.startFragRequested?0:c):n=o[o.length-1];if(n){var f=n.sn-r.startSN,v=this.fragmentTracker.getState(n);if((v===FragmentState.OK||v===FragmentState.PARTIAL&&n.gap)&&(s=n),mediaFragmentsAreEqual(n,s)&&(!h||d[0].fragment.sn>n.sn||!r.live)){var p=o[f+1];n=n.sn<l&&this.fragmentTracker.getState(p)!==FragmentState.OK?p:null}}return n}},{key:"alignPlaylists",value:function(e,t,r){var n=e.fragments.length;if(!n)return this.warn("No fragments in live playlist"),0;var i=e.fragmentStart,a=!t,s=e.alignedSliding&&isFiniteNumber(i);if(a||!s&&!i){alignStream(r,e,this);var o=e.fragmentStart;return this.log("Live playlist sliding: ".concat(o," start-sn: ").concat(t?t.startSN:"na","->").concat(e.startSN," fragments: ").concat(n)),o}return i}},{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 n=this.timelineOffset;if(-1===r){var i=null!==this.startTimeOffset,a=i?this.startTimeOffset:e.startTimeOffset;if(null!==a&&isFiniteNumber(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(i?"multivariant":"media"," playlist")),this.startPosition=r;else if(e.live){var s=this.hls.liveSyncPosition;r=s||t,this.log("Setting startPosition to -1 to start at ".concat(s?"live edge":"playlist start"," ").concat(r)),this.startPosition=-1}else this.log("setting startPosition to 0 by default"),this.startPosition=r=0;this.lastCurrentTime=r+n}this.nextLoadPosition=r+n}},{key:"getLoadPosition",value:function(){var e,t=this.media,r=0;return null!=(e=this.hls)&&e.hasEnoughToStart&&t&&!this.iframesOnly?r=t.currentTime:this.nextLoadPosition>=0&&(r=this.nextLoadPosition),r}},{key:"playhead",get:function(){var e;if(null!=(e=this.hls)&&e.hasEnoughToStart){var t,r=null==(t=this.media)?void 0:t.currentTime;return isFiniteNumber(r)?r:this.lastCurrentTime}return this.getLoadPosition()}},{key:"iframesOnly",get:function(){var e;if(this.playlistType!==PlaylistLevelType.MAIN)return!1;var t=this.getLevelDetails();return t?t.iframesOnly:null==(e=this.levelLastLoaded)?void 0:e.iframes}},{key:"handleFragLoadAborted",value:function(e,t){this.transmuxer&&e.type===this.playlistType&&isMediaFragment(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===State.FRAG_LOADING_WAITING_RETRY)||(this.state=State.IDLE)}},{key:"onFragmentOrKeyLoadError",value:function(e,t){if(t.chunkMeta&&!t.frag){var r=this.getCurrentContext(t.chunkMeta);r&&(t.frag=r.frag)}var n=t.frag,i=t.part;if(n&&this.levels&&n.type===e)if(this.fragContextChanged(n)){var a;this.warn("Frag load error must match current frag to retry ".concat(n.relurl," > ").concat(null==(a=this.fragCurrent)?void 0:a.relurl))}else{var s=t.details===ErrorDetails.FRAG_GAP;s&&this.fragmentTracker.addAsGap(n);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===NetworkErrorAction.RetryRequest,p=f&&!o.resolved&&u&ErrorActionFlags.MoveAllAlternatesMatchingHost,g=this.hls.latestLevelDetails,y=null==g?void 0:g.live;if(!v&&p&&isMediaFragment(n)&&y&&n.sn<g.endSN&&!isUnusableKeyError(t))this.resetFragmentErrors(e),i?i.gap=!0:this.treatAsGap(n),o.resolved=!0;else if((v||p)&&d<h.maxNumRetry){var m,E=offlineHttpStatus(null==(m=t.response)?void 0:m.code),S=getRetryDelay(h,d);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+S,this.state=State.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,E)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(S,"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===NetworkErrorAction.RemoveAlternatePermanently||(o.resolved=!0)}else l===NetworkErrorAction.SendAlternateToPenaltyBox?this.state=State.WAITING_LEVEL:this.state=State.ERROR;this.tickImmediate()}else this.state=State.ERROR}}},{key:"checkRetryDate",value:function(){var e=self.performance.now(),t=this.retryDate,r=t===1/0;(!t||e>=t||r&&!offlineHttpStatus(0))&&(r&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=State.IDLE)}},{key:"reduceLengthAndFlushBuffer",value:function(e){if(this.state===State.PARSING||this.state===State.PARSED){var t=e.frag,r=e.parent,n=this.getFwdBufferInfo(this.mediaBuffer,r),i=n&&n.len>.5;i&&this.reduceMaxBufferLength(n.len,(null==t?void 0:t.duration)||10);var a=!i;return a?this.warn("Buffer full error while media.currentTime (".concat(this.playhead,") is not buffered, flush ").concat(r," buffer")):n.nextStart&&t&&n.nextStart>t.start&&this.flushMainBuffer(n.nextStart,Number.POSITIVE_INFINITY,r===PlaylistLevelType.AUDIO?r:void 0),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}},{key:"resetFragmentErrors",value:function(e){e===PlaylistLevelType.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==State.STOPPED&&(this.state=State.IDLE)}},{key:"afterBufferFlushed",value:function(e,t){if(e){var r=BufferHelper.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,this.playlistType),this.state===State.ENDED&&this.resetLoadingState()}}},{key:"resetLoadingState",value:function(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==State.STOPPED&&(this.state=State.IDLE)}},{key:"resetStartWhenNotLoaded",value:function(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;var e=this.getLevelDetails();null!=e&&e.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(e,e.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}},{key:"resetWhenMissingContext",value:function(e){this.log("Loading context changed while buffering sn ".concat(e.sn," of ").concat(this.playlistLabel()," ").concat(-1===e.level?"<removed>":e.level,". This chunk will not be buffered.")),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}},{key:"removeUnbufferedFrags",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}},{key:"updateLevelTiming",value:function(e,t,r,n){var i=this,a=r.details;if(a){this.log("update level timing ".concat(e.type," sn: ").concat(e.sn).concat(t?" part: "+t.index:""," of ").concat(this.fragInfo(e,!1,t)));var s=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 i.warn("Could not parse fragment ".concat(e.sn," ").concat(s," duration reliably (").concat(l,")")),t||!1;var u=n.partial?0:updateFragPTSDTS(a,e,o.startPTS,o.endPTS,o.startDTS,o.endDTS,i.iframesOnly,i);return i.hls.trigger(Events$2.LEVEL_PTS_UPDATED,{details:a,level:r,drift:u,type:s,frag:e,start:o.startPTS,end:o.endPTS}),!0}return t},!1);if(!s){var o,l,u,c,d=null===(null==(o=this.transmuxer)?void 0:o.error),h=null!=(null==(l=this.transmuxer)?void 0:l.error),f=(null!=(u=null==(c=this.levels)?void 0:c.length)?u:0)>1;if((0===r.fragmentError||d&&(r.fragmentError<2||e.endList)||h&&f)&&this.treatAsGap(e,r),d){var v=new Error("Found no media in ".concat(this.playlistLabel()," ").concat(e.level," ").concat(t?"part: ".concat(t.index," of "):"","sn: ").concat(e.sn," at playlist time: ").concat(e.start,". Resetting transmuxer to fallback to playlist timing"));if(this.warn(v.message),this.hls.trigger(Events$2.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_PARSING_ERROR,fatal:!1,error:v,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=State.PARSED,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(Events$2.FRAG_PARSED,{frag:e,part:t,chunkMeta:n})}else this.warn("level.details undefined")}},{key:"playlistLabel",value:function(){return"".concat(this.playlistType," playlist")}},{key:"fragInfo",value:function(e){var t,r,n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=arguments.length>2?arguments[2]:void 0;return"".concat(this.playlistLabel()," ").concat(e.level," (").concat(i?"part":"frag",":[").concat(null!=(t=n&&!i?e.startPTS:(i||e).start)?t:NaN,"-").concat(null!=(r=n&&!i?e.endPTS:(i||e).end)?r:NaN,"]").concat(i&&"main"===e.type?"INDEPENDENT="+(i.independent?"YES":"NO"):"",")")}},{key:"treatAsGap",value:function(e,t){t&&t.fragmentError++,this.fragmentTracker.addAsGap(e)}},{key:"resetTransmuxer",value:function(){var e;null==(e=this.transmuxer)||e.reset()}},{key:"isFragmentNearlyDownloaded",value:function(e){var t,r=null==(t=e.loader)?void 0:t.stats;if(!r)return!1;var n=r.loading.first>0,i=(r.total-r.loaded)/(this.hls.bandwidthEstimate||this.hls.config.abrEwmaDefaultEstimate);return n&&i<=.15}},{key:"recoverWorkerError",value:function(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}},{key:"state",get:function(){return this._state},set:function(e){var t=this._state;t!==e&&(this._state=e,this.log("".concat(t,"->").concat(e)))}},{key:"calculateOptimalSwitchPoint",value:function(e,t){var r=0,n=this.hls,i=this.media,a=this.config,s=this.levels,o=this.playlistType,l=this.getLevelDetails();if(i&&!i.paused&&s){var u,c=o===PlaylistLevelType.AUDIO?estimatedAudioBitrate(e.audioCodec,128e3):e.maxBitrate,d=1+n.ttfbEstimate/1e3,h=n.bandwidthEstimate*a.abrBandWidthUpFactor;r=d+c*(l&&(this.loadingParts?l.partTarget:l.averagetargetduration)||(null==(u=this.fragCurrent)?void 0:u.duration)||6)/h,e.details||(r+=d)}var f=this.playhead;return{fetchdelay:r,okToFlushForwardBuffer:!(null!=l&&l.live)||t.end-f>1.5*r}}},{key:"scheduleTrackSwitch",value:function(e,t,r){var n=this.media,i=this.playlistType;if(n&&e){var a=r?this.getBufferedFrag(this.playhead+t):null;if(a){var s=this.followingBufferedFrag(a);if(s){var o;this.abortCurrentFrag();var l=s.maxStartPTS?s.maxStartPTS:s.start,u=s.duration,c=Math.max(a.end,l+Math.min(Math.max(u-this.config.maxFragLookUpTolerance,u*(this.couldBacktrack?.5:.125)),u*(this.couldBacktrack?.75:.25)));if(((null==(o=this.getLevelDetails())?void 0:o.fragmentStart)||0)>c)return;var d=i===PlaylistLevelType.MAIN?null:"audio";this.flushMainBuffer(c,Number.POSITIVE_INFINITY,d),this.cleanupBackBuffer()}}}}},{key:"cleanupBackBuffer",value:function(){var e=this.media,t=this.playlistType;if(e){var r=this.getAppendedFrag(this.playhead);if(r&&r.start>1){var n=t===PlaylistLevelType.AUDIO;this.flushMainBuffer(0,r.start-(n?0:1),n?"audio":null)}}}},{key:"getBufferedFrag",value:function(e){return this.fragmentTracker.getBufferedFrag(e,this.playlistType)}},{key:"followingBufferedFrag",value:function(e){return e?this.getBufferedFrag(e.end+.5):null}},{key:"abortCurrentFrag",value:function(){var e=this.fragCurrent;switch(this.fragCurrent=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case State.KEY_LOADING:case State.FRAG_LOADING:case State.FRAG_LOADING_WAITING_RETRY:case State.PARSING:case State.PARSED:this.state=State.IDLE}this.nextLoadPosition=this.playhead}},{key:"checkFragPlaying",value:function(){var e=this.media,t=null;if(e&&e.readyState>1&&!1===e.seeking){var r=e.currentTime;if(BufferHelper.isBuffered(e,r)?t=this.getAppendedFrag(r):BufferHelper.isBuffered(e,r+.1)&&(t=this.getAppendedFrag(r+.1)),t&&(this.backtrackFragment=void 0,!mediaFragmentsAreEqual(t,this.fragPlaying)))return this.fragPlaying=t,!0}return!1}},{key:"getBufferOutput",value:function(){return null}},{key:"nextLevelSwitch",value:function(){var e=this.levels,t=this.media,r=this.hls,n=this.config,i=this.playlistType;if(null!=t&&t.readyState&&e&&r&&n){var a=this.getBufferOutput(),s=this.getFwdBufferInfo(a,i);if(!s)return;var o=e[i===PlaylistLevelType.AUDIO?r.nextAudioTrack:r.nextLoadLevel],l=this.calculateOptimalSwitchPoint(o,s),u=l.fetchdelay,c=l.okToFlushForwardBuffer;this.scheduleTrackSwitch(s,u,c)}this.tickImmediate()}}])}();function fragOverlapsQueuedInterstitial(e,t,r){if(t)for(var n=t.length;n--;){var i=t[n].interstitial,a=i.startTime,s=Math.min(a+i.duration,i.resumeTime);if(i.appendInPlace){if(e.start>=a&&e.end<=s)return!0;if(r>e.start&&e.end>a&&e.start<s)return!0}}return!1}function interstitialsEnabled(e){return!!e.interstitialsController&&!1!==e.enableInterstitialPlayback}var ChunkCache=function(){return _createClass(function e(){_classCallCheck(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]:concatUint8Arrays(t,r),this.reset(),e):new Uint8Array(0)}},{key:"reset",value:function(){this.chunks.length=0,this.dataLength=0}}])}();function concatUint8Arrays(e,t){for(var r=new Uint8Array(t),n=0,i=0;i<e.length;i++){var a=e[i];r.set(a,n),n+=a.length}return r}var hasRequiredEventemitter3,eventemitter3={exports:{}};function requireEventemitter3(){return hasRequiredEventemitter3||(hasRequiredEventemitter3=1,function(e){var t=Object.prototype.hasOwnProperty,r="~";function n(){}function i(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function a(e,t,n,a,s){if("function"!=typeof n)throw new TypeError("The listener must be a function");var o=new i(n,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 n:delete e._events[t]}function o(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),o.prototype.eventNames=function(){var e,n,i=[];if(0===this._eventsCount)return i;for(n in e=this._events)t.call(e,n)&&i.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i},o.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,a=n.length,s=new Array(a);i<a;i++)s[i]=n[i].fn;return s},o.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},o.prototype.emit=function(e,t,n,i,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,n),!0;case 4:return c.fn.call(c.context,t,n,i),!0;case 5:return c.fn.call(c.context,t,n,i,a),!0;case 6:return c.fn.call(c.context,t,n,i,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,n);break;case 4:c[u].fn.call(c[u].context,t,n,i);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,n,i){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||i&&!o.once||n&&o.context!==n||s(this,a);else{for(var l=0,u=[],c=o.length;l<c;l++)(o[l].fn!==t||i&&!o[l].once||n&&o[l].context!==n)&&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 n,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}(eventemitter3)),eventemitter3.exports}var eventemitter3Exports=requireEventemitter3(),EventEmitter=getDefaultExportFromCjs$1(eventemitter3Exports),version="1.7.3",workerStore={};function hasUMDWorker(){return"function"==typeof __HLS_WORKER_BUNDLE__}function injectWorker(){var e=workerStore[version];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),n={worker:new self.Worker(r),objectURL:r,clientCount:1};return workerStore[version]=n,n}function loadWorker(e){var t=workerStore[e];if(t)return t.clientCount++,t;var r=new self.URL(e,self.location.href).href,n={worker:new self.Worker(r),scriptURL:r,clientCount:1};return workerStore[e]=n,n}function removeWorkerFromStore(e){var t=workerStore[e||version];if(t&&1===t.clientCount--){var r=t.worker,n=t.objectURL;delete workerStore[e||version],n&&self.URL.revokeObjectURL(n),r.terminate()}}function getAudioConfig(e,t,r,n){var i=t[r+2],a=i>>2&15;if(!(a>12)){var s,o=1+(i>>6&3),l=t[r+3]>>6&3|(1&i)<<2,u=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][a],c=a;5!==o&&29!==o||(c-=3);var d=(14&c)>>1,h=(1&c)<<7|l<<3,f=0;if(1===o&&a>=6){var v=a-3;s=[(f=5)<<3|d,h|(14&v)>>1,(1&v)<<7|8,0]}else s=[o<<3|d,h];var p="mp4a.40."+(f||o);return logger.log("manifest codec:".concat(n,", parsed codec:").concat(p,", channels:").concat(l,", rate:").concat(u," (ADTS object type:").concat(o," sampling index:").concat(a," esds config:[").concat(s.join(","),"])")),{config:s,samplerate:u,channelCount:l,codec:p,parsedCodec:p,manifestCodec:n}}var g=new Error("invalid ADTS sampling index:".concat(a));e.emit(Events$2.ERROR,Events$2.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_PARSING_ERROR,fatal:!0,error:g,reason:g.message})}function isHeaderPattern$1(e,t){return 255===e[t]&&240==(246&e[t+1])}function getHeaderLength(e,t){return 1&e[t+1]?7:9}function getFullFrameLength(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function canGetFrameLength(e,t){return t+5<e.length}function isHeader$1(e,t){return t+1<e.length&&isHeaderPattern$1(e,t)}function canParse$1(e,t){return canGetFrameLength(e,t)&&isHeaderPattern$1(e,t)&&getFullFrameLength(e,t)<=e.length-t}function probe$1(e,t){if(isHeader$1(e,t)){var r=getHeaderLength(e,t);if(t+r>=e.length)return!1;var n=getFullFrameLength(e,t);if(n<=r)return!1;var i=t+n;return i===e.length||isHeader$1(e,i)}return!1}function initTrackConfig(e,t,r,n,i){if(!e.samplerate){var a=getAudioConfig(t,r,n,i);if(!a)return;_extends(e,a)}}function getFrameDuration(e){return 9216e4/e}function parseFrameHeader(e,t){var r=getHeaderLength(e,t);if(t+r<=e.length){var n=getFullFrameLength(e,t)-r;if(n>0)return{headerLength:r,frameLength:n}}}function appendFrame$2(e,t,r,n,i){var a,s=n+i*getFrameDuration(e.samplerate),o=parseFrameHeader(t,r);if(o){var l=o.frameLength,u=o.headerLength,c=u+l,d=Math.max(0,r+c-t.length);d?(a=new Uint8Array(c-u)).set(t.subarray(r+u,t.length),0):a=t.subarray(r+u,r+c);var h={unit:a,pts:s};return d||e.samples.push(h),{sample:h,length:c,missing:d}}var f=t.length-r;return(a=new Uint8Array(f)).set(t.subarray(r,t.length),0),{sample:{unit:a,pts:s},length:f,missing:-1}}var MetadataSchema=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 dummyTrack(){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 BaseAudioDemuxer=function(){return _createClass(function e(){_classCallCheck(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,n){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=appendUint8Array(this.cachedData,e),this.cachedData=null);var r,n=getId3Data(e,0),i=n?n.length:0,a=this._audioTrack,s=this._id3Track,o=n?getId3Timestamp(n):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&isFiniteNumber(o))&&(this.basePTS=initPTSFn(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),n&&n.length>0&&s.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:MetadataSchema.audioId3,duration:Number.POSITIVE_INFINITY});i<l;){if(this.canParse(e,i)){var u=this.appendFrame(a,e,i);u?(this.frameIndex++,this.lastPTS=u.sample.pts,r=i+=u.length):i=l}else canParseId3(e,i)?(n=getId3Data(e,i),s.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:MetadataSchema.audioId3,duration:Number.POSITIVE_INFINITY}),r=i+=n.length):i++;if(i===l&&r!==l){var c=e.slice(r);this.cachedData?this.cachedData=appendUint8Array(this.cachedData,c):this.cachedData=c}}return{audioTrack:a,videoTrack:dummyTrack(),id3Track:s,textTrack:dummyTrack()}}},{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:dummyTrack(),id3Track:this._id3Track,textTrack:dummyTrack()}}},{key:"destroy",value:function(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}])}(),initPTSFn=function(e,t,r){return isFiniteNumber(e)?90*e:9e4*t+(r?9e4*r.baseTime/r.timescale:0)},BitratesMap=[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],SamplingRateMap=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],SamplesCoefficients=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],BytesInSlot=[0,1,1,4];function appendFrame$1(e,t,r,n,i){if(!(r+24>t.length)){var a=parseHeader(t,r);if(a&&r+a.frameLength<=t.length){var s=n+i*(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 parseHeader(e,t){var r=e[t+1]>>3&3,n=e[t+1]>>1&3,i=e[t+2]>>4&15,a=e[t+2]>>2&3;if(1!==r&&0!==i&&15!==i&&3!==a){var s=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*BitratesMap[14*(3===r?3-n:3===n?3:4)+i-1],u=SamplingRateMap[3*(3===r?0:2===r?1:2)+a],c=3===o?1:2,d=SamplesCoefficients[r][n],h=BytesInSlot[n],f=8*d*h,v=Math.floor(d*l/u+s)*h,p=userAgentChromeVersion();return!!p&&p<=87&&2===n&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:u,channelCount:c,frameLength:v,samplesPerFrame:f}}}function isHeaderPattern(e,t){return!(255!==e[t]||224&~e[t+1]||!(6&e[t+1]))}function isHeader(e,t){return t+1<e.length&&isHeaderPattern(e,t)}function _canParse(e,t){return isHeaderPattern(e,t)&&4<=e.length-t}function _probe(e,t){if(t+1<e.length&&isHeaderPattern(e,t)){var r=parseHeader(e,t),n=4;null!=r&&r.frameLength&&(n=r.frameLength);var i=t+n;return i===e.length||isHeader(e,i)}return!1}var SampleAesDecrypter=function(){return _createClass(function e(t,r,n){_classCallCheck(this,e),this.keyData=void 0,this.decrypter=void 0,this.keyData=n,this.decrypter=new Decrypter(r,!0)},[{key:"decryptBuffer",value:function(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,DecrypterAesMode.cbc,{start:0,end:e.byteLength})}},{key:"decryptAacSample",value:function(e,t,r){var n=this,i=e[t].unit;if(!(i.length<=16)){var a=i.subarray(16,i.length-i.length%16),s=a.buffer.slice(a.byteOffset,a.byteOffset+a.length);this.decryptBuffer(s).then(function(a){var s=new Uint8Array(a);i.set(s,16),n.decrypter.isSync()||n.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),n=0,i=32;i<e.length-16;i+=160,n+=16)r.set(e.subarray(i,i+16),n);return r}},{key:"getAvcDecryptedUnit",value:function(e,t){for(var r=new Uint8Array(t),n=0,i=32;i<e.length-16;i+=160,n+=16)e.set(r.subarray(n,n+16),i);return e}},{key:"decryptAvcSample",value:function(e,t,r,n,i){var a=this,s=discardEPB(i.data),o=this.getAvcEncryptedData(s);this.decryptBuffer(o.buffer).then(function(o){i.data=a.getAvcDecryptedUnit(s,o),a.decrypter.isSync()||a.decryptAvcSamples(e,t,r+1,n)}).catch(n)}},{key:"decryptAvcSamples",value:function(e,t,r,n){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,r=0){if(t>=e.length)return void n();for(var i=e[t].units;!(r>=i.length);r++){var a=i[r];if(!(a.data.length<=48||1!==a.type&&5!==a.type||(this.decryptAvcSample(e,t,r,n,a),this.decrypter.isSync())))return}}}}])}(),AACDemuxer=function(){function e(t,r){var n;return _classCallCheck(this,e),(n=_callSuper(this,e)).observer=void 0,n.config=void 0,n.sampleAes=null,n.observer=t,n.config=r,n}return _inherits(e,BaseAudioDemuxer),_createClass(e,[{key:"resetInitSegment",value:function(t,r,n,i){_superPropGet(e,"resetInitSegment",this)([t,r,n,i]),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:r,duration:i,inputTimeScale:9e4,dropped:0}}},{key:"canParse",value:function(e,t){return canParse$1(e,t)}},{key:"appendFrame",value:function(e,t,r){initTrackConfig(e,this.observer,t,r,e.manifestCodec);var n=appendFrame$2(e,t,r,this.basePTS,this.frameIndex);if(0===(null==n?void 0:n.missing))return n}},{key:"demuxSampleAes",value:function(e,t,r){var n=this.demux(e,r),i=this.sampleAes=new SampleAesDecrypter(this.observer,this.config,t);return new Promise(function(e){i.decryptAacSamples(n.audioTrack.samples,0,function(){e(n)})})}}],[{key:"probe",value:function(e,t){if(!e)return!1;var r=getId3Data(e,0),n=(null==r?void 0:r.length)||0;if(_probe(e,n))return!1;for(var i=e.length;n<i;n++)if(probe$1(e,n))return t.log("ADTS sync word found !"),!0;return!1}}])}(),getAudioBSID=function(e,t){var r=0,n=5;t+=n;for(var i=new Uint32Array(1),a=new Uint32Array(1),s=new Uint8Array(1);n>0;){s[0]=e[t];var o=Math.min(n,8),l=8-o;a[0]=4278190080>>>24+l<<l,i[0]=(s[0]&a[0])>>l,r=r?r<<o|i[0]:i[0],t+=1,n-=o}return r},AC3Demuxer=function(){function e(t){var r;return _classCallCheck(this,e),(r=_callSuper(this,e)).observer=void 0,r.observer=t,r}return _inherits(e,BaseAudioDemuxer),_createClass(e,[{key:"resetInitSegment",value:function(t,r,n,i){_superPropGet(e,"resetInitSegment",this)([t,r,n,i]),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:r,duration:i,inputTimeScale:9e4,dropped:0}}},{key:"canParse",value:function(e,t){return t+64<e.length}},{key:"appendFrame",value:function(e,t,r){var n=_appendFrame(e,t,r,this.basePTS,this.frameIndex);if(-1!==n)return{sample:e.samples[e.samples.length-1],length:n,missing:0}}}],[{key:"probe",value:function(e){if(!e)return!1;var t=getId3Data(e,0);if(!t)return!1;var r=t.length;if(11===e[r]&&119===e[r+1]&&void 0!==getId3Timestamp(t)){if(getAudioBSID(e,r)<16)return!0;throw new Error("Containerless ec-3 is not supported")}return!1}}])}();function _appendFrame(e,t,r,n,i){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],p=new Uint8Array([a<<6|f<<1|v>>2,(3&v)<<6|u<<3|d<<2|o>>4,o<<4&224]),g=n+i*(1536/s*9e4),y=t.subarray(r,r+l);return e.config=p,e.channelCount=h,e.samplerate=s,e.samples.push({unit:y,pts:g}),l}var MP3Demuxer=function(){function e(){return _classCallCheck(this,e),_callSuper(this,e,arguments)}return _inherits(e,BaseAudioDemuxer),_createClass(e,[{key:"resetInitSegment",value:function(t,r,n,i){_superPropGet(e,"resetInitSegment",this)([t,r,n,i]),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:r,duration:i,inputTimeScale:9e4,dropped:0}}},{key:"canParse",value:function(e,t){return _canParse(e,t)}},{key:"appendFrame",value:function(e,t,r){if(null!==this.basePTS)return appendFrame$1(e,t,r,this.basePTS,this.frameIndex)}}],[{key:"probe",value:function(e){if(!e)return!1;var t=getId3Data(e,0),r=(null==t?void 0:t.length)||0;if(t&&11===e[r]&&119===e[r+1]&&void 0!==getId3Timestamp(t)&&getAudioBSID(e,r)<=16)return!1;for(var n=e.length;r<n;r++)if(_probe(e,r))return logger.log("MPEG Audio sync word found !"),!0;return!1}}])}(),emsgSchemePattern=/\/emsg[-/]ID3/i,MP4Demuxer=function(){return _createClass(function e(t,r,n){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:logger;_classCallCheck(this,e),this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.initData=void 0,this.logger=void 0,this.config=r,this.logger=i},[{key:"resetTimeStamp",value:function(){}},{key:"resetInitSegment",value:function(e,t,r,n){var i=this.videoTrack=dummyTrack("video",1),a=this.audioTrack=dummyTrack("audio",1),s=this.txtTrack=dummyTrack("text",1);if(this.id3Track=dummyTrack("id3",1),this.initData=void 0,this.timeOffset=0,null!=e&&e.byteLength){var o=this.initData=parseInitSegment(e);if(o.video){var l=o.video,u=l.id,c=l.timescale,d=l.codec,h=l.supplemental;i.id=u,i.timescale=s.timescale=c,i.codec=d,i.supplemental=h}if(o.audio){var f=o.audio,v=f.id,p=f.timescale,g=f.codec;a.id=v,a.timescale=p,a.codec=g}s.id=RemuxerTrackIdConfig.text,i.sampleDuration=0,i.duration=a.duration=n}}},{key:"resetContiguity",value:function(){this.remainderData=null}},{key:"demux",value:function(e,t,r){this.timeOffset=t;var n=e,i=this.videoTrack,a=this.txtTrack;if(this.config.progressive){this.remainderData&&(n=appendUint8Array(this.remainderData,e));var s=segmentValidRange(n);this.remainderData=s.remainder,i.samples=s.valid||new Uint8Array}else i.samples=n;var o=this.extractID3Track(i,t),l=this.parseFragment(i,a,t,r);return{videoTrack:i,audioTrack:this.audioTrack,id3Track:o,textTrack:this.txtTrack,initData:this.initData,sampleData:l}}},{key:"flush",value:function(e,t){var r=this.timeOffset,n=this.videoTrack,i=this.txtTrack;n.samples=this.remainderData||new Uint8Array,this.remainderData=null;var a=this.extractID3Track(n,this.timeOffset),s=this.parseFragment(n,i,r,t);return{videoTrack:n,audioTrack:dummyTrack(),id3Track:a,textTrack:dummyTrack(),initData:this.initData,sampleData:s}}},{key:"parseFragment",value:function(e,t,r,n){var i=this.initData;if(i&&n){var a=parseSamplesAndTiming(r,e,i,this.logger,n.iframe),s=a.samples,o=a.sampleData;return t.samples=s,o}t.samples=parseSamples(r,e)}},{key:"extractID3Track",value:function(e,t){var r=this,n=this.id3Track;if(e.samples.length){var i=findBox(e.samples,["emsg"]);i&&i.forEach(function(e){var i=parseEmsg(e);if(emsgSchemePattern.test(i.schemeIdUri)){var a=getEmsgStartTime(i,t),s=4294967295===i.eventDuration?Number.POSITIVE_INFINITY:i.eventDuration/i.timeScale;s<=.001&&(s=Number.POSITIVE_INFINITY);var o=i.payload;n.samples.push({data:o,len:o.byteLength,dts:a,pts:a,type:MetadataSchema.emsg,duration:s})}else if(r.config.enableEmsgKLVMetadata){var l=r.config.emsgKLVSchemaUri||MetadataSchema.misbklv;if(i.schemeIdUri.startsWith(l)){var u=getEmsgStartTime(i,t);n.samples.push({data:i.payload,len:i.payload.byteLength,dts:u,pts:u,type:MetadataSchema.misbklv,duration:Number.POSITIVE_INFINITY})}}})}return n}},{key:"demuxSampleAes",value:function(e,t,r){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}},{key:"destroy",value:function(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0,this.initData=void 0}}],[{key:"probe",value:function(e){return hasBoxData(e,"moof")}}])}();function getEmsgStartTime(e,t){return isFiniteNumber(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}var ANNEX_B_START_CODE_MARKER=1,MIN_START_CODE_ZERO_RUN=2,NAL_UNIT_TYPE_PENDING=-1,BaseVideoParser=function(){return _createClass(function e(){_classCallCheck(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,n=this.VideoSample;if(n&&0!==n.units.length||(n=e[e.length-1]),null!=(t=n)&&t.units){var i=n.units;r=i[i.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,n=r.length;if(!n)return void t.dropped++;var i=r[n-1];e.pts=i.pts,e.dts=i.dts}t.samples.push(e)}}},{key:"parseNALu",value:function(e,t,r){var n=t.byteLength;if(0===n)return[];var i=e.naluState||0,a=i===NAL_UNIT_TYPE_PENDING?0:i,s=[],o=0,l=0,u=-1,c=0;for(i===NAL_UNIT_TYPE_PENDING&&(u=0,c=this.getNALuType(t,0),l=1);l<n;){var d=t.indexOf(ANNEX_B_START_CODE_MARKER,l);if(-1===d)break;l=d+1;for(var h=d;h>0&&0===t[h-1];)h--;if(!(d-h+(0===h?a:0)<MIN_START_CODE_ZERO_RUN)){if(u>=0)s.push({data:t.subarray(u,h),type:c});else{var f=this.getLastNalUnit(e.samples);f&&(h>0?f.data=appendUint8Array(f.data,t.subarray(0,h)):a>0&&(f.data=f.data.subarray(0,f.data.byteLength-a)),f.state=0)}if(!(l<n)){o=NAL_UNIT_TYPE_PENDING,u=-1;break}u=l,c=this.getNALuType(t,l)}}if(o!==NAL_UNIT_TYPE_PENDING){for(var v=n;v>0&&0===t[v-1];)v--;o=n-v+(0===v?a:0)}if(u>=0)s.push({data:t.subarray(u),type:c,state:o});else if(0===s.length&&o!==NAL_UNIT_TYPE_PENDING){var p=this.getLastNalUnit(e.samples);p&&(p.data=appendUint8Array(p.data,t),p.state=o)}return e.naluState=o,s}}])}(),ExpGolomb=function(){return _createClass(function e(t){_classCallCheck(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,n=new Uint8Array(4),i=Math.min(4,t);if(0===i)throw new Error("no bytes available");n.set(e.subarray(r,r+i)),this.word=new DataView(n.buffer).getUint32(0),this.bitsAvailable=8*i,this.bytesAvailable-=i}},{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&&logger.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)}}])}(),AvcVideoParser=function(){function e(){return _classCallCheck(this,e),_callSuper(this,e,arguments)}return _inherits(e,BaseVideoParser),_createClass(e,[{key:"parsePES",value:function(e,t,r,n,i){var a,s=this,o=i.iframe,l=this.parseNALu(e,r.data,n),u=this.VideoSample,c=!1;r.data=null,u&&l.length&&!e.audFound&&(this.pushAccessUnit(u,e),u=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),l.forEach(function(n){var i,l;switch(n.type){case 1:if(o)break;var d=!1;a=!0;var h,f=n.data;if(c&&f.length>4){var v=s.readSliceType(f);2!==v&&4!==v&&7!==v&&9!==v||(d=!0)}if(d)null!=(h=u)&&h.frame&&!u.key&&(s.pushAccessUnit(u,e),u=s.VideoSample=null);u||(u=s.VideoSample=s.createVideoSample(!0,r.pts,r.dts)),u.frame=!0,u.key=d;break;case 5:a=!0,null!=(i=u)&&i.frame&&!u.key&&(s.pushAccessUnit(u,e),u=s.VideoSample=null),u||(u=s.VideoSample=s.createVideoSample(!0,r.pts,r.dts)),u.key=!0,u.frame=!0;break;case 6:if(o)break;a=!0,parseSEIMessageFromNALu(n.data,1,r.pts,t.samples);break;case 7:var p,g;a=!0,c=!0;var y=n.data,m=s.readSPS(y);if(!e.sps||e.width!==m.width||e.height!==m.height||(null==(p=e.pixelRatio)?void 0:p[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=[y];for(var E=y.subarray(1,4),S="avc1.",T=0;T<3;T++){var k=E[T].toString(16);k.length<2&&(k="0"+k),S+=k}e.codec=S}break;case 8:a=!0,e.pps=[n.data];break;case 9:a=!0,e.audFound=!0,null!=(l=u)&&l.frame&&(s.pushAccessUnit(u,e),u=null),u||(u=s.VideoSample=s.createVideoSample(!1,r.pts,r.dts));break;case 12:a=!0;break;default:a=!1}u&&a&&u.units.push(n)}),n&&u&&(this.pushAccessUnit(u,e),this.VideoSample=null)}},{key:"getNALuType",value:function(e,t){return 31&e[t]}},{key:"readSliceType",value:function(e){var t=new ExpGolomb(e);return t.readUByte(),t.readUEG(),t.readUEG()}},{key:"skipScalingList",value:function(e,t){for(var r=8,n=8,i=0;i<e;i++)0!==n&&(n=(r+t.readEG()+256)%256),r=0===n?r:n}},{key:"readSPS",value:function(e){var t,r,n,i=new ExpGolomb(e),a=0,s=0,o=0,l=0,u=i.readUByte.bind(i),c=i.readBits.bind(i),d=i.readUEG.bind(i),h=i.readBoolean.bind(i),f=i.skipBits.bind(i),v=i.skipEG.bind(i),p=i.skipUEG.bind(i),g=this.skipScalingList.bind(this);u();var y=u();if(c(5),f(3),u(),p(),100===y||110===y||122===y||244===y||44===y||83===y||86===y||118===y||128===y){var m=d();if(3===m&&f(1),p(),p(),f(1),h())for(r=3!==m?8:12,n=0;n<r;n++)h()&&g(n<6?16:64,i)}p();var E=d();if(0===E)d();else if(1===E)for(f(1),v(),v(),t=d(),n=0;n<t;n++)v();p(),f(1);var S=d(),T=d(),k=c(1);0===k&&f(1),f(1),h()&&(a=d(),s=d(),o=d(),l=d());var _=[1,1];if(h()&&h())switch(u()){case 1:_=[1,1];break;case 2:_=[12,11];break;case 3:_=[10,11];break;case 4:_=[16,11];break;case 5:_=[40,33];break;case 6:_=[24,11];break;case 7:_=[20,11];break;case 8:_=[32,11];break;case 9:_=[80,33];break;case 10:_=[18,11];break;case 11:_=[15,11];break;case 12:_=[64,33];break;case 13:_=[160,99];break;case 14:_=[4,3];break;case 15:_=[3,2];break;case 16:_=[2,1];break;case 255:_=[u()<<8|u(),u()<<8|u()]}return{width:Math.ceil(16*(S+1)-2*a-2*s),height:(2-k)*(T+1)*16-(k?2:4)*(o+l),pixelRatio:_}}}])}(),HevcVideoParser=function(){function e(){var t;_classCallCheck(this,e);for(var r=arguments.length,n=new Array(r),i=0;i<r;i++)n[i]=arguments[i];return(t=_callSuper(this,e,[].concat(n))).initVPS=null,t}return _inherits(e,BaseVideoParser),_createClass(e,[{key:"parsePES",value:function(e,t,r,n){var i,a=this,s=this.parseNALu(e,r.data,n),o=this.VideoSample,l=!1;r.data=null;var u=function(e){return o=a.VideoSample=a.createVideoSample(e,r.pts,r.dts)};s.forEach(function(n,s){var c,d;if(a.startsNewAccessUnit(o,e,n,s)){a.pushAccessUnit(o,e);var h=n.type>=16&&n.type<=23;o=u(h),l=!1}switch(n.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:o||(o=u(!1)),o.frame=!0,i=!0;break;case 16:case 17:case 18:case 21:case 22:case 23:var f;if(i=!0,l)null!=(f=o)&&f.frame&&!o.key&&(a.pushAccessUnit(o,e),o=a.VideoSample=null);o||(o=u(!0)),o.key=!0,o.frame=!0;break;case 19:case 20:i=!0,null!=(c=o)&&c.frame&&!o.key&&(a.pushAccessUnit(o,e),o=a.VideoSample=null),o||(o=u(!0)),o.key=!0,o.frame=!0;break;case 39:i=!0,parseSEIMessageFromNALu(n.data,2,r.pts,t.samples);break;case 32:i=!0,e.vps||("object"!==_typeof(e.params)&&(e.params={}),e.params=_extends(e.params,a.readVPS(n.data)),a.initVPS=n.data),e.vps=[n.data];break;case 33:if(i=!0,l=!0,void 0===e.vps||e.vps[0]===a.initVPS||void 0===e.sps||a.matchSPS(e.sps[0],n.data)||(a.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){var v=a.readSPS(n.data);for(var p in e.width=v.width,e.height=v.height,e.pixelRatio=v.pixelRatio,e.codec=v.codecString,e.sps=[],"object"!==_typeof(e.params)&&(e.params={}),v.params)e.params[p]=v.params[p]}a.pushParameterSet(e.sps,n.data,e.vps),o||(o=u(!1));break;case 34:if(i=!0,"object"===_typeof(e.params)){if(!e.pps){e.pps=[];var g=a.readPPS(n.data);for(var y in g)e.params[y]=g[y]}a.pushParameterSet(e.pps,n.data,e.vps)}break;case 35:i=!0,e.audFound=!0,null!=(d=o)&&d.frame&&(a.pushAccessUnit(o,e),o=null),o||(o=u(!1));break;default:i=!1}o&&i&&o.units.push(n)}),n&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}},{key:"pushParameterSet",value:function(e,t,r){(r&&r[0]===this.initVPS||!r&&!e.length)&&e.push(t)}},{key:"startsNewAccessUnit",value:function(e,t,r,n){if(!e)return!1;if(!t.audFound&&0===n)return!0;if(!e.frame)return!1;var i=r.type,a=r.data;return!!(i>=32&&i<=35||39===i||i>=41&&i<=44||i>=48&&i<=55)||i<=31&&a.length>2&&!!(128&a[2])}},{key:"getNALuType",value:function(e,t){return(126&e[t])>>>1}},{key:"ebsp2rbsp",value:function(e){for(var t=new Uint8Array(e.byteLength),r=0,n=0;n<e.byteLength;n++)n>=2&&3===e[n]&&0===e[n-1]&&0===e[n-2]||(t[r]=e[n],r++);return new Uint8Array(t.buffer,0,r)}},{key:"pushAccessUnit",value:function(t,r){_superPropGet(e,"pushAccessUnit",this)([t,r]),this.initVPS&&(this.initVPS=null)}},{key:"readVPS",value:function(e){var t=new ExpGolomb(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 ExpGolomb(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);var r=t.readBits(3);t.readBoolean();for(var n=t.readBits(2),i=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(),p=t.readUByte(),g=t.readUByte(),y=[],m=[],E=0;E<r;E++)y.push(t.readBoolean()),m.push(t.readBoolean());if(r>0)for(var S=r;S<8;S++)t.readBits(2);for(var T=0;T<r;T++)y[T]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),m[T]&&t.readUByte();t.readUEG();var k=t.readUEG();3==k&&t.skipBits(1);var _=t.readUEG(),A=t.readUEG(),b=t.readBoolean(),L=0,R=0,C=0,I=0;b&&(L+=t.readUEG(),R+=t.readUEG(),C+=t.readUEG(),I+=t.readUEG());for(var P=t.readUEG(),D=t.readUEG(),w=t.readUEG(),O=t.readBoolean()?0:r;O<=r;O++)t.skipUEG(),t.skipUEG(),t.skipUEG();if((t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean())&&t.readBoolean())for(var x=0;x<4;x++)for(var M=0;M<(3===x?2:6);M++){if(t.readBoolean()){var F=Math.min(64,1<<4+(x<<1));x>1&&t.readEG();for(var N=0;N<F;N++)t.readEG()}else t.readUEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());for(var U=t.readUEG(),B=0,G=0;G<U;G++){var H=!1;if(0!==G&&(H=t.readBoolean()),H){G===U&&t.readUEG(),t.readBoolean(),t.readUEG();for(var $=0,K=0;K<=B;K++){var V=t.readBoolean(),j=!1;V||(j=t.readBoolean()),(V||j)&&$++}B=$}else{var q=t.readUEG(),W=t.readUEG();B=q+W;for(var Y=0;Y<q;Y++)t.readUEG(),t.readBoolean();for(var z=0;z<W;z++)t.readUEG(),t.readBoolean()}}if(t.readBoolean())for(var X=t.readUEG(),Q=0;Q<X;Q++){for(var J=0;J<w+4;J++)t.readBits(1);t.readBits(1)}var Z=0,ee=1,te=1,re=!0,ne=1,ie=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(ne=t.readBits(32),ie=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=_,pe=A;if(b){var ge=1,ye=1;1===k?ge=ye=2:2==k&&(ge=2),ve=_-ge*R-ge*L,pe=A-ye*I-ye*C}for(var me=n?["A","B","C"][n]:"",Ee=s<<24|o<<16|l<<8|u,Se=0,Te=0;Te<32;Te++)Se=(Se|(Ee>>Te&1)<<31-Te)>>>0;var ke=Se.toString(16);1===a&&"2"===ke&&(ke="6");var _e=i?"H":"L";return{codecString:"hvc1.".concat(me).concat(a,".").concat(ke,".").concat(_e).concat(g,".B0"),params:{general_tier_flag:i,general_profile_idc:a,general_profile_space:n,general_profile_compatibility_flags:[s,o,l,u],general_constraint_indicator_flags:[c,d,h,f,v,p],general_level_idc:g,bit_depth:P+8,bit_depth_luma_minus8:P,bit_depth_chroma_minus8:D,min_spatial_segmentation_idc:Z,chroma_format_idc:k,frame_rate:{fixed:re,fps:ie/ne}},width:ve,height:pe,pixelRatio:[ee,te]}}},{key:"readPPS",value:function(e){var t=new ExpGolomb(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(),n=t.readBoolean(),i=1;return n&&r?i=0:n?i=3:r&&(i=2),{parallelismType:i}}},{key:"matchSPS",value:function(e,t){return bin2str(e).substring(3)===bin2str(t).substring(3)}}])}(),PACKET_LENGTH=188,TSDemuxer=function(){function e(t,r,n,i){_classCallCheck(this,e),this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this._klvPid=-1,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.videoIntegrityChecker=null,this.observer=t,this.config=r,this.typeSupported=n,this.logger=i,this.videoParser=null}return _createClass(e,[{key:"resetInitSegment",value:function(t,r,n,i,a,s){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=e.createTrack("video"),this._videoTrack.duration=i,this.videoIntegrityChecker="skip"===this.config.handleMpegTsVideoIntegrityErrors?new PacketsIntegrityChecker(this.logger):null,this._audioTrack=e.createTrack("audio",i),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=n,t&&this.demux(t,0,s,"SAMPLE-AES"===(null==a?void 0:a.method))}},{key:"resetTimeStamp",value:function(){}},{key:"resetContiguity",value:function(){var e=this._audioTrack,t=this._videoTrack,r=this._id3Track;e&&(e.pesData=null),t&&(t.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.remainderData=null}},{key:"demux",value:function(t,r,n){var i,a=arguments.length>3&&void 0!==arguments[3]&&arguments[3],s=arguments.length>4&&void 0!==arguments[4]&&arguments[4];a||(this.sampleAes=null);var o=this._videoTrack,l=this.videoIntegrityChecker,u=this._audioTrack,c=this._id3Track,d=this._txtTrack,h=n.iframe,f=o.pid,v=o.pesData,p=u.pid,g=c.pid,y=this._klvPid,m=u.pesData,E=c.pesData,S=null,T=null,k=this.pmtParsed,_=this._pmtId,A=t.length;if(this.remainderData&&(A=(t=appendUint8Array(this.remainderData,t)).length,this.remainderData=null),A<PACKET_LENGTH&&!s)return this.remainderData=t,{audioTrack:u,videoTrack:o,id3Track:c,textTrack:d};var b=Math.max(0,e.syncOffset(t));(A-=(A-b)%PACKET_LENGTH)<t.byteLength&&!s&&(this.remainderData=new Uint8Array(t.buffer,A,t.buffer.byteLength-A));for(var L=0,R=b;R<A;R+=PACKET_LENGTH)if(71===t[R]){var C=!!(64&t[R+1]),I=parsePID(t,R),P=void 0;if((48&t[R+3])>>4>1){if((P=R+5+t[R+4])===R+PACKET_LENGTH)continue}else P=R+4;switch(I){case f:C&&(!v||null!=l&&l.isCorrupted||!(i=parsePES(v,this.logger))||(this.readyVideoParser(o.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(o,d,i,!1,n)),v={data:[],size:0},null==l||l.reset(f)),null==l||l.handlePacket(t.subarray(R)),v&&(v.data.push(t.subarray(P,R+PACKET_LENGTH)),v.size+=R+PACKET_LENGTH-P);break;case p:if(h)break;if(C){if(m&&(i=parsePES(m,this.logger)))switch(u.segmentCodec){case"aac":this.parseAACPES(u,i,n);break;case"mp3":this.parseMPEGPES(u,i);break;case"ac3":this.parseAC3PES(u,i)}m={data:[],size:0}}m&&(m.data.push(t.subarray(P,R+PACKET_LENGTH)),m.size+=R+PACKET_LENGTH-P);break;case g:if(h)break;C&&(E&&(i=parsePES(E,this.logger))&&this.parseID3PES(c,i),E={data:[],size:0}),E&&(E.data.push(t.subarray(P,R+PACKET_LENGTH)),E.size+=R+PACKET_LENGTH-P);break;case y:if(h)break;C&&(S&&(i=parsePES(S,this.logger))&&this.parseKlvPES(c,i),S={data:[],size:0}),S&&(S.data.push(t.subarray(P,R+PACKET_LENGTH)),S.size+=R+PACKET_LENGTH-P);break;case 0:C&&(P+=t[P]+1),_=this._pmtId=parsePAT(t,P);break;case _:C&&(P+=t[P]+1);var D=parsePMT(t,P,this.typeSupported,a,this.observer,this.logger,this.config,n);(f=D.videoPid)>0&&(o.pid=f,o.segmentCodec=D.segmentVideoCodec),(p=D.audioPid)>0&&(u.pid=p,u.segmentCodec=D.segmentAudioCodec),(g=D.id3Pid)>0&&(c.pid=g),(y=D.klvPid)>0&&(this._klvPid=y),null===T||k||(this.logger.warn("MPEG-TS PMT found at ".concat(R," after unknown PID '").concat(T,"'. Backtracking to sync byte @").concat(b," to parse all TS packets.")),T=null,R=b-188),k=this.pmtParsed=!0;break;case 17:case 8191:break;default:T=I}}else L++;L>0&&emitParsingError(this.observer,new Error("Found ".concat(L," TS packet/s that do not start with 0x47")),n,void 0,this.logger),o.pesData=v,u.pesData=m,c.pesData=E;var w={audioTrack:u,videoTrack:o,id3Track:c,textTrack:d};return s&&this.extractRemainingSamples(w,n),w}},{key:"flush",value:function(e,t){var r,n=this.remainderData;return this.remainderData=null,r=n?this.demux(n,0,t,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(r,t),this.sampleAes?this.decrypt(r,this.sampleAes):r}},{key:"extractRemainingSamples",value:function(e,t){var r,n=e.audioTrack,i=e.videoTrack,a=e.id3Track,s=e.textTrack,o=i.pesData,l=n.pesData,u=a.pesData,c=this.videoIntegrityChecker;if(!o||null!=c&&c.isCorrupted||!(r=parsePES(o,this.logger))?i.pesData=o:(this.readyVideoParser(i.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(i,s,r,!0,t),i.pesData=null)),l&&(r=parsePES(l,this.logger))){switch(n.segmentCodec){case"aac":this.parseAACPES(n,r,t);break;case"mp3":this.parseMPEGPES(n,r);break;case"ac3":this.parseAC3PES(n,r)}n.pesData=null}else null!=l&&l.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),n.pesData=l;u&&(r=parsePES(u,this.logger))?(this.parseID3PES(a,r),a.pesData=null):a.pesData=u}},{key:"demuxSampleAes",value:function(e,t,r,n){var i=this.demux(e,r,n,!0,!this.config.progressive),a=this.sampleAes=new SampleAesDecrypter(this.observer,this.config,t);return this.decrypt(i,a)}},{key:"readyVideoParser",value:function(e){null===this.videoParser&&("avc"===e?this.videoParser=new AvcVideoParser:"hevc"===e&&(this.videoParser=new HevcVideoParser))}},{key:"decrypt",value:function(e,t){return new Promise(function(r){var n=e.audioTrack,i=e.videoTrack;n.samples&&"aac"===n.segmentCodec?t.decryptAacSamples(n.samples,0,function(){i.samples?t.decryptAvcSamples(i.samples,0,0,function(){r(e)}):r(e)}):i.samples&&t.decryptAvcSamples(i.samples,0,0,function(){r(e)})})}},{key:"destroy",value:function(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0,this.videoIntegrityChecker=null}},{key:"parseAACPES",value:function(e,t,r){var n,i,a,s=0,o=this.aacOverFlow,l=t.data;if(o){this.aacOverFlow=null;var u=o.missing,c=o.sample.unit.byteLength;if(-1===u)l=appendUint8Array(o.sample.unit,l);else{var d=c-u;o.sample.unit.set(l.subarray(0,u),d),e.samples.push(o.sample),s=o.missing}}for(n=s,i=l.length;n<i-1&&!isHeader$1(l,n);n++);if(n!==s){var h,f=n<i-1;if(h=f?"AAC PES did not start with ADTS header,offset:".concat(n):"No ADTS header found in AAC PES",emitParsingError(this.observer,new Error(h),r,f,this.logger),!f)return}if(initTrackConfig(e,this.observer,l,n,this.audioCodec),void 0!==t.pts)a=t.pts;else{if(!o)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");var v=getFrameDuration(e.samplerate);a=o.sample.pts+v}for(var p,g=0;n<i;){if(n+=(p=appendFrame$2(e,l,n,a,g)).length,p.missing){this.aacOverFlow=p;break}for(g++;n<i-1&&!isHeader$1(l,n);n++);}}},{key:"parseMPEGPES",value:function(e,t){var r=t.data,n=r.length,i=0,a=0,s=t.pts;if(void 0!==s)for(;a<n;)if(isHeader(r,a)){var o=appendFrame$1(e,r,a,s,i);if(!o)break;a+=o.length,i++}else a++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}},{key:"parseAC3PES",value:function(e,t){var r=t.data,n=t.pts;if(void 0!==n)for(var i,a=r.length,s=0,o=0;o<a&&(i=_appendFrame(e,r,o,n,s++))>0;)o+=i;else this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS")}},{key:"parseID3PES",value:function(e,t){if(void 0!==t.pts){var r=_extends({},t,{type:this._videoTrack?MetadataSchema.emsg:MetadataSchema.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(r)}else this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS")}},{key:"parseKlvPES",value:function(e,t){var r,n=null!=(r=t.pts)?r:t.dts;if(void 0!==n){var i=t.data;if(i.length<16)this.logger.warn("[tsdemuxer]: KLV PES payload too short");else for(var a=0;a<i.length;){var s;if(a+16>i.length)break;var o=a;if((a+=16)>=i.length)break;var l=i[a];a+=1;var u=0;if(128&l){var c=127&l;if(0===c||c>4||a+c>i.length){this.logger.warn("[tsdemuxer]: Invalid KLV length encoding");break}for(var d=0;d<c;d++)u=u<<8|i[a+d];a+=c}else u=l;if(a+u>i.length){this.logger.warn("[tsdemuxer]: KLV value extends beyond PES payload");break}var h=a+u,f=i.subarray(o,h),v={data:f,len:f.byteLength,pts:n,dts:null!=(s=t.dts)?s:n,type:MetadataSchema.misbklv,duration:Number.POSITIVE_INFINITY};e.samples.push(v),a=h}}else this.logger.warn("[tsdemuxer]: KLV PES unknown PTS and DTS")}}],[{key:"probe",value:function(t,r){var n=e.syncOffset(t);return n>0&&r.warn("MPEG2-TS detected but first sync word found @ offset ".concat(n)),-1!==n}},{key:"syncOffset",value:function(e){for(var t=e.length,r=Math.min(5*PACKET_LENGTH,t-PACKET_LENGTH)+1,n=0;n<r;){for(var i=!1,a=-1,s=0,o=n;o<t;o+=PACKET_LENGTH){if(71!==e[o]||t-o!==PACKET_LENGTH&&71!==e[o+PACKET_LENGTH]){if(s)return-1;break}if(s++,-1===a&&0!==(a=o)&&(r=Math.min(a+99*PACKET_LENGTH,e.length-PACKET_LENGTH)+1),i||(i=0===parsePID(e,o)),i&&s>1&&(0===a&&s>2||o+PACKET_LENGTH>r))return a}n++}return-1}},{key:"createTrack",value:function(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:RemuxerTrackIdConfig[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}}])}();function parsePID(e,t){return((31&e[t+1])<<8)+e[t+2]}function parsePAT(e,t){return(31&e[t+10])<<8|e[t+11]}function parsePMT(e,t,r,n,i,a,s,o){var l={audioPid:-1,videoPid:-1,id3Pid:-1,klvPid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},u=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t<u;){var c=parsePID(e,t),d=(15&e[t+3])<<8|e[t+4];switch(e[t]){case 207:if(!n){logEncryptedSamplesFoundInUnencryptedStream("ADTS AAC",a);break}case 15:-1===l.audioPid&&(l.audioPid=c);break;case 21:-1===l.id3Pid&&(l.id3Pid=c);break;case 219:if(!n){logEncryptedSamplesFoundInUnencryptedStream("H.264",a);break}case 27:-1===l.videoPid&&(l.videoPid=c);break;case 3:case 4:r.mpeg||r.mp3?-1===l.audioPid&&(l.audioPid=c,l.segmentAudioCodec="mp3"):a.log("MPEG audio found, not supported in this browser");break;case 193:if(!n){logEncryptedSamplesFoundInUnencryptedStream("AC-3",a);break}case 129:r.ac3?-1===l.audioPid&&(l.audioPid=c,l.segmentAudioCodec="ac3"):a.log("AC-3 audio found, not supported in this browser");break;case 6:if(d>0)for(var h=t+5,f=d;f>2;){switch(e[h]){case 106:-1===l.audioPid&&(!0!==r.ac3?a.log("AC-3 audio found, not supported in this browser for now"):(l.audioPid=c,l.segmentAudioCodec="ac3"));break;case 5:-1===l.klvPid&&s.enableEmsgKLVMetadata&&(l.klvPid=c,a.log("KLV metadata PID found: ".concat(c)))}var v=e[h+1]+2;h+=v,f-=v}break;case 194:case 135:return emitParsingError(i,new Error("Unsupported EC-3 in M2TS found"),o,void 0,a),l;case 36:-1===l.videoPid&&(l.videoPid=c,l.segmentVideoCodec="hevc",a.log("HEVC in M2TS found"))}t+=d+5}return l}function emitParsingError(e,t,r,n,i){i.warn("parsing error: ".concat(t.message)),e.emit(Events$2.ERROR,Events$2.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_PARSING_ERROR,fatal:!1,levelRetry:n,chunkMeta:r,error:t,reason:t.message})}function logEncryptedSamplesFoundInUnencryptedStream(e,t){t.log("".concat(e," with AES-128-CBC encryption found in unencrypted stream"))}function parsePES(e,t){var r,n,i,a,s,o=0,l=e.data;if(!e||0===e.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=appendUint8Array(l[0],l[1]),l.splice(1,1);if(1===((r=l[0])[0]<<16)+(r[1]<<8)+r[2]){if((n=(r[4]<<8)+r[5])&&n>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=(i=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 n&&(n-=i+3),{data:d,pts:a,dts:s,len:n}}return null}var _MP,PacketsIntegrityChecker=function(){return _createClass(function e(t){_classCallCheck(this,e),this.logger=void 0,this.pid=0,this.lastContinuityCounter=-1,this.integrityState="ok",this.logger=t},[{key:"isCorrupted",get:function(){return"ok"!==this.integrityState}},{key:"reset",value:function(e){this.pid=e,this.lastContinuityCounter=-1,this.integrityState="ok"}},{key:"handlePacket",value:function(e){if(!(e.byteLength<4)){var t=parsePID(e,0);if(t===this.pid){var r=(48&e[3])>>4;if(0!==r){var n=15&e[3],i=this.lastContinuityCounter;this.lastContinuityCounter=n;var a=!!(1&r);if(!(!!(2&r)&&0!=e[4]&&!!(128&e[5])||i<0)){var s=a?i+1&15:i;return n!==s?(this.logger.warn("MPEG-TS Continuity Counter check failed for PID='".concat(t,"', CC=").concat(n,", Expected-CC=").concat(s," Last-CC=").concat(i)),void(this.integrityState="cc-failed")):128&e[1]?(this.logger.warn("MPEG-TS Packet had TEI flag set for PID='".concat(t,"'")),void(this.integrityState="tei-bit")):void 0}}}else this.logger.debug("Packet PID mismatch, expected ".concat(this.pid," got ").concat(t))}}}])}(),AAC=function(){return _createClass(function e(){_classCallCheck(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])}}}])}(),HDLR_TYPES={video:new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),audio:new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0])},STCO=new Uint8Array([0,0,0,0,0,0,0,0]),STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),STSD=new Uint8Array([0,0,0,0,0,0,0,1]),majorBrand=new Uint8Array([105,115,111,109]),avc1Brand=new Uint8Array([97,118,99,49]),minorVersion=new Uint8Array([0,0,0,1]),MP4=function(){function e(){_classCallCheck(this,e)}return _createClass(e,null,[{key:"box",value:function(e){for(var t=8,r=arguments.length,n=new Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];for(var a=n.length,s=a;a--;)t+=n[a].byteLength;var o=new Uint8Array(t);for(writeUint32(o,0,t),writeUint32(o,4,e),a=0,t=8;a<s;a++)o.set(n[a],t),t+=n[a].byteLength;return o}},{key:"hdlr",value:function(t){return e.box(types.hdlr,HDLR_TYPES[t])}},{key:"mdat",value:function(t){return e.box(types.mdat,t)}},{key:"mdhd",value:function(t,r){r*=t;var n=Math.floor(r/(UINT32_MAX+1)),i=Math.floor(r%(UINT32_MAX+1));return e.box(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,n>>24,n>>16&255,n>>8&255,255&n,i>>24,i>>16&255,i>>8&255,255&i,85,196,0,0]))}},{key:"mdia",value:function(t){return e.box(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(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(types.minf,e.box(types.smhd,SMHD),e.DINF,e.stbl(t)):e.box(types.minf,e.box(types.vmhd,VMHD),e.DINF,e.stbl(t))}},{key:"moof",value:function(t,r,n){return e.box(types.moof,e.mfhd(t),e.traf(n,r))}},{key:"moov",value:function(t){for(var r=t.length,n=[];r--;)n[r]=e.trak(t[r]);return e.box.apply(null,[types.moov,e.mvhd(t[0].timescale||0,t[0].duration||0)].concat(n).concat(e.mvex(t)))}},{key:"mvex",value:function(t){for(var r=t.length,n=[];r--;)n[r]=e.trex(t[r]);return e.box.apply(null,[types.mvex].concat(n))}},{key:"mvhd",value:function(t,r){r*=t;var n=Math.floor(r/(UINT32_MAX+1)),i=Math.floor(r%(UINT32_MAX+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,n>>24,n>>16&255,n>>8&255,255&n,i>>24,i>>16&255,i>>8&255,255&i,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return e.box(types.mvhd,a)}},{key:"sdtp",value:function(t){var r,n,i=t.samples||[],a=new Uint8Array(4+i.length);for(r=0;r<i.length;r++)n=i[r].flags,a[r+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return e.box(types.sdtp,a)}},{key:"stbl",value:function(t){return e.box(types.stbl,e.stsd(t),e.box(types.stts,STCO),e.box(types.stsc,STCO),e.box(types.stsz,STSZ),e.box(types.stco,STCO))}},{key:"avc1",value:function(t){var r,n,i,a=[],s=[];for(r=0;r<t.sps.length;r++)i=(n=t.sps[r]).byteLength,a.push(i>>>8&255),a.push(255&i),a=a.concat(Array.prototype.slice.call(n));for(r=0;r<t.pps.length;r++)i=(n=t.pps[r]).byteLength,s.push(i>>>8&255),s.push(255&i),s=s.concat(Array.prototype.slice.call(n));var o=e.box(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(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(types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(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,r=t.length;return new Uint8Array([0,0,0,0,3,23+r,0,1,0,4,15+r,64,21,0,0,0,0,0,0,0,0,0,0,0,5,r].concat(_toConsumableArray(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(types.mp4a,e.audioStsd(t),e.box(types.esds,e.esds(t)))}},{key:"mp3",value:function(t){return e.box(types[".mp3"],e.audioStsd(t))}},{key:"ac3",value:function(t){return e.box(types["ac-3"],e.audioStsd(t),e.box(types.dac3,t.config))}},{key:"stsd",value:function(t){var r=t.segmentCodec;if("audio"===t.type){if("aac"===r)return e.box(types.stsd,STSD,e.mp4a(t));if("ac3"===r&&t.config)return e.box(types.stsd,STSD,e.ac3(t));if("mp3"===r&&"mp3"===t.codec)return e.box(types.stsd,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(types.stsd,STSD,e.avc1(t));if("hevc"===r&&t.vps)return e.box(types.stsd,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,n=(t.duration||0)*(t.timescale||0),i=t.width||0,a=t.height||0,s=Math.floor(n/(UINT32_MAX+1)),o=Math.floor(n%(UINT32_MAX+1));return e.box(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,i>>8&255,255&i,0,0,a>>8&255,255&a,0,0]))}},{key:"traf",value:function(t,r){var n=e.sdtp(t),i=t.id,a=Math.floor(r/(UINT32_MAX+1)),s=Math.floor(r%(UINT32_MAX+1));return e.box(types.traf,e.box(types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,255&i])),e.box(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,n.length+16+20+8+16+8+8),n)}},{key:"trak",value:function(t){return t.duration=t.duration||4294967295,e.box(types.trak,e.tkhd(t),e.mdia(t))}},{key:"trex",value:function(t){var r=t.id;return e.box(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 n,i,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),n=0;n<c;n++)a=(i=u[n]).duration,s=i.size,o=i.flags,l=i.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*n);return e.box(types.trun,h)}},{key:"initSegment",value:function(t){var r=e.moov(t);return appendUint8Array(e.FTYP,r)}},{key:"hvc1",value:function(t){for(var r=t.params,n=[t.vps,t.sps,t.pps],i=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),n.length]),a=i.length,s=0;s<n.length;s+=1){a+=3;for(var o=0;o<n[s].length;o+=1)a+=2+n[s][o].length}var l=new Uint8Array(a);l.set(i,0),a=i.length;for(var u=n.length-1,c=0;c<n.length;c+=1){l.set(new Uint8Array([32+c|(c===u?128:0),0,n[c].length]),a),a+=3;for(var d=0;d<n[c].length;d+=1)l.set(new Uint8Array([n[c][d].length>>8,255&n[c][d].length]),a),a+=2,l.set(n[c][d],a),a+=n[c][d].length}var h=e.box(types.hvcC,l),f=t.width,v=t.height,p=t.pixelRatio[0],g=t.pixelRatio[1];return e.box(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(types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(types.pasp,new Uint8Array([p>>24,p>>16&255,p>>8&255,255&p,g>>24,g>>16&255,g>>8&255,255&g])))}}])}();_MP=MP4,MP4.FTYP=_MP.box(types.ftyp,majorBrand,minorVersion,majorBrand,avc1Brand),MP4.DINF=_MP.box(types.dinf,_MP.box(types.dref,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1])));var MPEG_TS_CLOCK_FREQ_HZ=9e4;function toTimescaleFromBase(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 toTimescaleFromScale(e,t){return toTimescaleFromBase(e,t,1/(arguments.length>2&&void 0!==arguments[2]?arguments[2]:1),arguments.length>3&&void 0!==arguments[3]&&arguments[3])}function toMsFromMpegTsClock(e){return toTimescaleFromBase(e,1e3,1/MPEG_TS_CLOCK_FREQ_HZ,arguments.length>1&&void 0!==arguments[1]&&arguments[1])}function toMpegTsClockFromTimescale(e){return toTimescaleFromBase(e,MPEG_TS_CLOCK_FREQ_HZ,1/(arguments.length>1&&void 0!==arguments[1]?arguments[1]:1))}function timestampToString(e){var t=e.baseTime,r=e.timescale,n=e.trackId;return"".concat(t/r," (").concat(t,"/").concat(r,") trackId: ").concat(n)}var MAX_SILENT_FRAME_DURATION=1e4,AAC_SAMPLES_PER_FRAME=1024,MPEG_AUDIO_SAMPLE_PER_FRAME=1152,AC3_SAMPLES_PER_FRAME=1536,MPEG_TS_PTS_ROLLOVER=8589934592;function createMp4Sample(e,t,r,n){return{duration:t,size:r,cts:n,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1,paddingValue:0}}}var MP4Remuxer=function(){function e(t,r,n,i){var a;return _classCallCheck(this,e),(a=_callSuper(this,e,["mp4-remuxer",i])).observer=void 0,a.config=void 0,a.typeSupported=void 0,a.ISGenerated=!1,a._initPTS=null,a._initDTS=null,a.nextVideoTs=null,a.nextAudioTs=null,a.videoSampleDuration=null,a.isAudioContiguous=!1,a.isVideoContiguous=!1,a.videoTrackConfig=void 0,a.observer=t,a.config=r,a.typeSupported=n,a.ISGenerated=!1,a}return _inherits(e,Logger$1),_createClass(e,[{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?timestampToString(t):t," > ").concat(e?timestampToString(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,n=e.reduce(function(e,n){var i=n.pts,a=i-e;return a<-4294967296&&(t=!0,a=(i=normalizePts(i,r))-e),a>0?e:i},r);return t&&this.debug("PTS rollover detected"),n}},{key:"remux",value:function(e,t,r,n,i,a,s,o,l){var u,c,d,h,f,v,p=i,g=i,y=!l.iframe&&e.pid>-1,m=t.pid>-1,E=t.samples.length,S=e.samples.length>0,T=s&&E>0||E>1;if((!y||S)&&(!m||T)||this.ISGenerated||s){if(this.ISGenerated){var k,_,A,b,L=this.videoTrackConfig;(L&&(t.width!==L.width||t.height!==L.height||(null==(k=t.pixelRatio)?void 0:k[0])!==(null==(_=L.pixelRatio)?void 0:_[0])||(null==(A=t.pixelRatio)?void 0:A[1])!==(null==(b=L.pixelRatio)?void 0:b[1]))||!L&&T||null===this.nextAudioTs&&S)&&this.resetInitSegment()}this.ISGenerated||(d=this.generateIS(e,t,i,a));var R,C=this.isVideoContiguous,I=-1;if(T&&(I=findKeyframeIndex(t.samples),!C&&this.config.forceKeyFrameOnDiscontinuity))if(v=!0,I>0){this.warn("Dropped ".concat(I," out of ").concat(E," video samples due to a missing keyframe"));var P=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(I),t.dropped+=I,R=g+=(t.samples[0].pts-P)/t.inputTimeScale}else-1===I&&(this.warn("No keyframe found out of ".concat(E," video samples")),v=!1);if(this.ISGenerated){if(S&&T&&i){var D=this.getVideoStartPts(t.samples),w=(normalizePts(e.samples[0].pts,D)-D)/t.inputTimeScale;p+=Math.max(0,w),g+=Math.max(0,-w)}if(S){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),d=this.generateIS(e,t,i,a)),c=this.remuxAudio(e,p,this.isAudioContiguous,a,m||T||o===PlaylistLevelType.AUDIO?g:void 0,l),T){var O=c?c.endPTS-c.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),d=this.generateIS(e,t,i,a)),u=this.remuxVideo(t,g,C,O,l)}}else T&&(u=this.remuxVideo(t,g,C,0,l));u&&(u.firstKeyFrame=I,u.independent=-1!==I,u.firstKeyFramePTS=R)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(f=flushTextTrackMetadataCueSamples(r,i,this._initPTS,this._initDTS)),n.samples.length&&(h=flushTextTrackUserdataCueSamples(n,i,this._initPTS))),{audio:c,video:u,initSegment:d,independent:v,text:h,id3:f}}},{key:"computeInitPts",value:function(e,t,r,n){var i=Math.round(r*t),a=normalizePts(e,i);if(a<i)for(this.log("Adjusting PTS for rollover in timeline near ".concat((i-a)/t," ").concat(n));a<i;)a+=MPEG_TS_PTS_ROLLOVER;return a-i}},{key:"generateIS",value:function(e,t,r,n){var i,a,s,o=e.samples,l=t.samples,u=this.typeSupported,c={},d=this._initPTS,h=!d||n,f="audio/mp4",v=-1;if(h&&(i=a=1/0),e.config&&o.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":u.mpeg?(f="audio/mpeg",e.codec=""):u.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}if(c.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&u.mpeg?new Uint8Array(0):MP4.initSegment([e]),metadata:{channelCount:e.channelCount}},h){v=e.id,s=e.inputTimeScale;var p=this.computeInitPts(o[0].pts,s,r,"audio");(!d||s!==d.timescale||0===r&&p<d.baseTime)&&(i=a=p)}}if(t.sps&&t.pps&&l.length){if(t.timescale=t.inputTimeScale,c.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:MP4.initSegment([t]),metadata:{width:t.width,height:t.height}},h){v=t.id,s=t.inputTimeScale;var g=this.getVideoStartPts(l),y=normalizePts(l[0].dts,g),m=this.computeInitPts(y,s,r,"video"),E=this.computeInitPts(g,s,r,"video");(!d||s!==d.timescale||isFiniteNumber(i)||0===r&&E<d.baseTime)&&(a=Math.min(a,m),i=Math.min(i,m))}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(c).length)return this.ISGenerated=!0,h&&isFiniteNumber(i)?(d&&this.warn("Timestamps at playlist time: ".concat(n?"":"~").concat(r," ").concat(i/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(i/s," (").concat(i,"/").concat(s,") trackId: ").concat(v)),this._initPTS={baseTime:i,timescale:s,trackId:v},this._initDTS={baseTime:a,timescale:s,trackId:v}):i=s=void 0,{tracks:c,initPTS:i,timescale:s,trackId:v}}},{key:"remuxVideo",value:function(e,t,r,n,i){var a,s,o=e.inputTimeScale,l=e.samples,u=[],c=l.length,d=this._initPTS,h=d.baseTime*o/d.timescale,f=this.nextVideoTs,v=8,p=this.videoSampleDuration,g=Number.POSITIVE_INFINITY,y=Number.NEGATIVE_INFINITY,m=!1;if(!r||null===f){var E=h+t*o,S=l[0].pts-normalizePts(l[0].dts,l[0].pts);userAgentChromeVersion()&&null!==f&&Math.abs(E-S-(f+h))<15e3?r=!0:f=E-S-h}for(var T=f+h,k=0;k<c;k++){var _=l[k];_.pts=normalizePts(_.pts,T),_.dts=normalizePts(_.dts,T),_.dts<l[k>0?k-1:k].dts&&(m=!0)}m&&l.sort(function(e,t){var r=e.dts-t.dts,n=e.pts-t.pts;return r||n}),a=l[0].dts;var A=(s=l[l.length-1].dts)-a,b=A?Math.round(A/(c-1)):p||e.inputTimeScale/30;if(r){var L=a-T,R=L>b,C=L<-1;if((R||C)&&(R?this.warn("".concat((e.segmentCodec||"").toUpperCase(),": ").concat(toMsFromMpegTsClock(L,!0)," ms (").concat(L,"dts) hole between fragments detected at ").concat(t.toFixed(3))):this.warn("".concat((e.segmentCodec||"").toUpperCase(),": ").concat(toMsFromMpegTsClock(-L,!0)," ms (").concat(L,"dts) overlapping between fragments detected at ").concat(t.toFixed(3))),!C||T>=l[0].pts||userAgentChromeVersion())){a=T;var I=l[0].pts-L;if(R)l[0].dts=a,l[0].pts=I;else for(var P=!0,D=0;D<l.length&&!(l[D].dts>I&&P);D++){var w=l[D].pts;if(l[D].dts-=L,l[D].pts-=L,D<l.length-1){var O=l[D+1].pts;P=O<=l[D].pts==O<=w}}this.log("Video: Initial PTS/DTS adjusted: ".concat(toMsFromMpegTsClock(I,!0),"/").concat(toMsFromMpegTsClock(a,!0),", delta: ").concat(toMsFromMpegTsClock(L,!0)," ms"))}}for(var x=0,M=0,F=a=Math.max(0,a),N=0;N<c;N++){for(var U=l[N],B=U.units,G=B.length,H=0,$=0;$<G;$++)H+=B[$].data.length;M+=H,x+=G,U.length=H,U.dts<F?(U.dts=F,F+=b/4|0||1):F=U.dts,g=Math.min(U.pts,g),y=Math.max(U.pts,y)}s=l[c-1].dts;var K,V=M+4*x+8;try{K=new Uint8Array(V)}catch(ke){return void this.observer.emit(Events$2.ERROR,Events$2.ERROR,{type:ErrorTypes.MUX_ERROR,details:ErrorDetails.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:i,error:ke,bytes:V,reason:"fail allocating video mdat ".concat(V)})}writeUint32(K,0,V),writeUint32(K,4,types.mdat);for(var j=!1,q=Number.POSITIVE_INFINITY,W=Number.POSITIVE_INFINITY,Y=Number.NEGATIVE_INFINITY,z=Number.NEGATIVE_INFINITY,X=0;X<c;X++){for(var Q=l[X],J=Q.units,Z=0,ee=0,te=J.length;ee<te;ee++){var re=J[ee],ne=re.data,ie=re.data.byteLength;writeUint32(K,v,ie),v+=4,K.set(ne,v),v+=ie,Z+=4+ie}var ae=void 0;if(X<c-1)p=l[X+1].dts-Q.dts,ae=l[X+1].pts-Q.pts;else{var se=this.config,oe=X>0?Q.dts-l[X-1].dts:b;if(ae=X>0?Q.pts-l[X-1].pts:b,se.stretchShortVideoTrack&&null!==this.nextAudioTs){var le=Math.floor(se.maxBufferHole*o),ue=(n?g+n*o:this.nextAudioTs+h)-Q.pts;ue>le?((p=ue-oe)<0?p=oe:j=!0,this.log("It is approximately ".concat(ue/90," ms to the next segment; using duration ").concat(p/90," ms for the last video frame."))):p=oe}else p=oe}var ce=Math.round(Q.pts-Q.dts);if(q=Math.min(q,p),Y=Math.max(Y,p),W=Math.min(W,ae),z=Math.max(z,ae),!r&&0===X&&ce>p){var de=Math.round(ce/b)*b;de-ce===1&&(this.log("pad first CTS ".concat(ce," -> ").concat(de," of sn: ").concat(i.sn)),ce=de)}u.push(createMp4Sample(Q.key,p,Z,ce))}if(u.length){var he=userAgentChromeVersion();if(he){if(he<70){var fe=u[0].flags;fe.dependsOn=2,fe.isNonSync=0}}else if(userAgentSafariVersion()&&z-W<Y-q&&b/Y<.025&&0===u[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");for(var ve=a,pe=0,ge=u.length;pe<ge;pe++){var ye=ve+u[pe].duration,me=ve+u[pe].cts;if(pe<ge-1){var Ee=ye+u[pe+1].cts;u[pe].duration=Ee-me}else u[pe].duration=pe?u[pe-1].duration:b;u[pe].cts=0,ve=ye}}}var Se=s+(p=j||!p?b:p);this.nextVideoTs=f=Se-h,this.videoSampleDuration=p,this.isVideoContiguous=!0,i.iframe&&(1===u.length?(u[0].duration=p=i.duration*o,this.nextVideoTs=f=a+p-h):this.warn("Not adjusting IFrame duration (sample count ".concat(u.length,")")));var Te={data1:MP4.moof(i.sn,a,_extends(e,{samples:u})),data2:K,startPTS:(g-h)/o,endPTS:(y+p-h)/o,startDTS:(a-h)/o,endDTS:f/o,type:"video",hasAudio:!1,hasVideo:!0,nb:u.length,dropped:e.dropped};return e.samples=[],e.dropped=0,Te}},{key:"getSamplesPerFrame",value:function(e){switch(e.segmentCodec){case"mp3":return MPEG_AUDIO_SAMPLE_PER_FRAME;case"ac3":return AC3_SAMPLES_PER_FRAME;default:return AAC_SAMPLES_PER_FRAME}}},{key:"remuxAudio",value:function(e,t,r,n,i,a){var s=e.inputTimeScale,o=s/(e.samplerate?e.samplerate:s),l=this.getSamplesPerFrame(e),u=l*o,c=this._initPTS,d="mp3"===e.segmentCodec&&this.typeSupported.mpeg,h=[],f=void 0!==i,v=e.samples,p=d?0:8,g=this.nextAudioTs||-1,y=c.baseTime*s/c.timescale,m=y+t*s;if(this.isAudioContiguous=r=r||v.length&&g>0&&(n&&Math.abs(m-(g+y))<9e3||Math.abs(normalizePts(v[0].pts,m)-(g+y))<20*u),v.forEach(function(e){e.pts=normalizePts(e.pts,m)}),!r||g<0){var E=v.length;if(v=v.filter(function(e){return e.pts>=0}),E!==v.length&&this.warn("Removed ".concat(v.length-E," of ").concat(E," samples (initPTS ").concat(y," / ").concat(s,")")),!v.length)return;g=0===i?0:n&&!f?Math.max(0,m-y):v[0].pts-y}if("aac"===e.segmentCodec)for(var S=this.config.maxAudioFramesDrift,T=0,k=g+y;T<v.length;T++){var _=v[T],A=_.pts,b=A-k,L=Math.abs(1e3*b/s);if(b<=-S*u&&f)0===T&&(this.warn("Audio frame @ ".concat((A/s).toFixed(3),"s overlaps marker by ").concat(Math.round(1e3*b/s)," ms.")),this.nextAudioTs=g=A-y,k=A);else if(b>=S*u&&L<MAX_SILENT_FRAME_DURATION&&f){var R=Math.round(b/u);for(k=A-R*u;k<0&&R&&u;)R--,k+=u;0===T&&(this.nextAudioTs=g=k-y),this.warn("Injecting ".concat(R," audio frames @ ").concat(((k-y)/s).toFixed(3),"s due to ").concat(Math.round(1e3*b/s)," ms gap."));for(var C=0;C<R;C++){var I=AAC.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);I||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),I=_.unit.subarray()),v.splice(T,0,{unit:I,pts:k}),k+=u,T++}}_.pts=k,k+=u}for(var P,D=null,w=null,O=0,x=v.length;x--;)O+=v[x].unit.byteLength;for(var M=0,F=v.length;M<F;M++){var N=v[M],U=N.unit,B=N.pts;if(null!==w){h[M-1].duration=Math.round((B-w)/o)}else{if(r&&"aac"===e.segmentCodec&&(B=g+y),D=B,!(O>0))return;O+=p;try{P=new Uint8Array(O)}catch(W){return void this.observer.emit(Events$2.ERROR,Events$2.ERROR,{type:ErrorTypes.MUX_ERROR,details:ErrorDetails.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:a,error:W,bytes:O,reason:"fail allocating audio mdat ".concat(O)})}d||(writeUint32(P,0,O),writeUint32(P,4,types.mdat))}P&&P.set(U,p);var G=U.byteLength;p+=G,h.push(createMp4Sample(!0,l,G,0)),w=B}var H=h.length;if(H){var $=h[h.length-1];g=w-y,this.nextAudioTs=g+o*$.duration;var K=d?new Uint8Array(0):MP4.moof(e.sequenceNumber++,D/o,_extends({},e,{samples:h}));e.samples=[];var V=(D-y)/s,j=this.nextAudioTs/s,q={data1:K,data2:P,startPTS:V,endPTS:j,startDTS:V,endDTS:j,type:"audio",hasAudio:!0,hasVideo:!1,nb:H};return this.isAudioContiguous=!0,q}}}])}();function normalizePts(e,t){var r;if(null===t)return e;for(r=t<e?-MPEG_TS_PTS_ROLLOVER:MPEG_TS_PTS_ROLLOVER;Math.abs(e-t)>4294967296;)e+=r;return e}function findKeyframeIndex(e){for(var t=0;t<e.length;t++)if(e[t].key)return t;return-1}function flushTextTrackMetadataCueSamples(e,t,r,n){var i=e.samples.length;if(i){for(var a=e.inputTimeScale,s=0;s<i;s++){var o=e.samples[s];o.pts=normalizePts(o.pts-r.baseTime*a/r.timescale,t*a)/a,o.dts=normalizePts(o.dts-n.baseTime*a/n.timescale,t*a)/a}var l=e.samples;return e.samples=[],{samples:l}}}function flushTextTrackUserdataCueSamples(e,t,r){var n=e.samples.length;if(n){for(var i=e.inputTimeScale,a=0;a<n;a++){var s=e.samples[a];s.pts=normalizePts(s.pts-r.baseTime*i/r.timescale,t*i)/i}e.samples.sort(function(e,t){return e.pts-t.pts});var o=e.samples;return e.samples=[],{samples:o}}}var now,PassThroughRemuxer=function(){function e(t,r,n,i){var a;return _classCallCheck(this,e),(a=_callSuper(this,e,["passthrough-remuxer",i])).observer=void 0,a.emitInitSegment=!1,a.audioCodec=void 0,a.videoCodec=void 0,a.initData=void 0,a.initPTS=null,a.initTracks=void 0,a.lastEndTime=null,a.isVideoContiguous=!1,a.videoOnlyRemux=!1,a.decryptdata=null,a.pendingInitSegment=void 0,a.observer=t,a}return _inherits(e,Logger$1),_createClass(e,[{key:"destroy",value:function(){this.observer&&this.observer.removeAllListeners(),this.observer=null}},{key:"resetTimeStamp",value:function(e){this.lastEndTime=null;var t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}},{key:"resetNextTimestamp",value:function(){this.isVideoContiguous=!1,this.lastEndTime=null}},{key:"resetInitSegment",value:function(e,t,r,n){this.audioCodec=t,this.videoCodec=r,this.decryptdata=n,this.pendingInitSegment=e,this.videoOnlyRemux=!1,this.initTracks=void 0,this.initData=void 0,this.emitInitSegment=!0}},{key:"generateInitSegment",value:function(e,t,r){this.videoOnlyRemux=!1;var n=this.audioCodec,i=this.videoCodec;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);var a=this.initData=r||parseInitSegment(e),s=a.audio,o=a.video;if(t)patchEncyptionData(e,t);else{var l=s||o;null!=l&&l.encrypted&&this.warn('Init segment with encrypted track with has no key ("'.concat(l.codec,'")!'))}s&&(n=getParsedTrackCodec(s,ElementaryStreamTypes.AUDIO,this)),o&&(i=getParsedTrackCodec(o,ElementaryStreamTypes.VIDEO,this));var u={};s&&o?u.audiovideo={container:"video/mp4",codec:n+","+i,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:s?u.audio={container:"audio/mp4",codec:n,encrypted:s.encrypted,initSegment:e,id:"audio"}:o?u.video={container:"video/mp4",codec:i,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=u}},{key:"remux",value:function(e,t,r,n,i,a,s,o,l,u,c){var d,h,f=this.initPTS,v=this.lastEndTime,p={audio:void 0,video:void 0,text:void 0,id3:r,initSegment:void 0};isFiniteNumber(v)||(v=this.lastEndTime=i||0);var g=t.samples;if(!g.length)return p;var y=this.pendingInitSegment;y&&(this.pendingInitSegment=void 0,this.generateInitSegment(y,this.decryptdata,u));var m={initPTS:void 0,timescale:void 0,trackId:void 0},E=this.initData;if(null!=(d=E)&&d.length||(this.generateInitSegment(g),E=this.initData),null==(h=E)||!h.length)return this.warn("Failed to generate initSegment."),p;if(l.iframe&&E.audio&&E.video){var S,T,k=null==(S=this.initTracks)||null==(S=S.audiovideo)?void 0:S.initSegment,_=k?videoOnlyInitSegment(k):null;if(_)this.log("Converted muxed init segment to video-only for I-Frame playback"),this.generateInitSegment(_,this.decryptdata),null!=(T=this.initData)&&T.length&&(E=this.initData,this.emitInitSegment=!0,this.videoOnlyRemux=!0)}this.emitInitSegment&&(m.tracks=this.initTracks,p.initSegment=m,this.emitInitSegment=!1);var A=l.iframe,b=!c||A&&!c.includeSampleDetails?getSampleData(g,E,l,this,A):c.tracks,L=E.audio?b[E.audio.id]:null,R=E.video?b[E.video.id]:null,C=!!E.audio,I=!!E.video,P="";C&&(P+="audio"),I&&(P+="video");var D,w=toStartEndOrDefault(R,1/0),O=toStartEndOrDefault(L,1/0),x=toStartEndOrDefault(R,0,!0),M=toStartEndOrDefault(L,0,!0),F=0;R&&L&&E.audio&&(O>x||w>M)&&this.warn("audio and video track sample timestamps do not overlap. v: ".concat(w,"-").concat(x," a: ").concat(O,"-").concat(M,"}"),R,L);var N=!!L&&(!R||!f&&O<w||!!f&&f.trackId===E.audio.id),U=N?L:R;if(!U)return this.log("No media samples found in ".concat(o," ").concat(l.level," ").concat(-1===l.part?"":"part: ".concat(l.part," of")," sn: ").concat(l.sn," at playlist time: ").concat(i)),p;var B,G=g;if(R&&R.sampleCount>=1&&E.video&&l.iframe){var H,$=R.trun,K=R.start,V=1===$.length,j=$.length?V?$[0].samples:(H=$[0].samples).concat.apply(H,_toConsumableArray($.slice(1).map(function(e){return e.samples}))):[];if(j.length){for(var q=$[0],W=q,Y=$.length;Y--;)if($[Y].samples.length){W=$[Y];break}var z=W.lastSampleDurationOffset,X=q.defaultSampleDurationOffset,Q=Math.abs(l.duration-(x-w))>.05,J=j.length<R.sampleCount;if(Q||J||this.videoOnlyRemux||!V){var Z=J?W.sampleOffset+W.samples.reduce(function(e,t){return e+t.size},0):void 0,ee=Q?l.duration:x-w,te=computeIFrameDurationRewrite(j,ee*E.video.timescale,z,X),re=remuxVideoOnlyIFrameMoof(g,E.video.id,j.length,Z,te);re?(G=re,B=samplesPresentationEnd(K,j)):this.warn("IFrame remux skipped (sn ".concat(l.sn,"); using native sample duration")),F=re&&te?ee:x-w}else F=x-w}else this.warn("Could not remux IFrame track fragment (no samples in range, trun count ".concat($.length,")")),F=x-w}else F=N?M-O:x-w;if(this.videoOnlyRemux&&G===g)return this.warn("Dropping muxed I-Frame fragment that could not be remuxed to video-only (sn: ".concat(l.sn,")")),p;var ne=U.timescale,ie=U.start-i*ne,ae=N?E.audio.id:E.video.id;if(D=U.start/ne,(a||!f)&&(isInvalidInitPts(f,D,i,F)||ne!==f.timescale)){var se=!1,oe=N?"audio":"video";if(f){var le=0!==i?D/i:1+D/1;se=D>=0&&Math.abs(1-le)<.001,this.log("".concat(oe," timestamps in track ").concat(ae," at playlist time: ").concat(a?"":"~").concat(i," maps to ").concat(D," with initPTS: ").concat(f.baseTime/f.timescale," (").concat(ie/ne-f.baseTime/f.timescale,"s diff) (").concat(P,") drift estimate: ").concat(le," ").concat(se?"(ignoring drift)":"remapping timestamps (initPTS)"))}se||(this.log("Found initPTS in ".concat(oe," track ").concat(ae," at playlist time: ").concat(i," offset: ").concat(D-i," (").concat(ie,"/").concat(ne,")")),f=null,m.initPTS=ie,m.timescale=ne,m.trackId=ae)}f?(m.initPTS=f.baseTime,m.timescale=f.timescale,m.trackId=f.trackId):(m.timescale&&void 0!==m.trackId&&void 0!==m.initPTS||(this.warn("Could not set initPTS"),m.initPTS=D,m.timescale=1,m.trackId=-1),this.initPTS=f={baseTime:m.initPTS,timescale:m.timescale,trackId:m.trackId});var ue=D-f.baseTime/f.timescale,ce=ue+F,de=I&&void 0!==(null==U?void 0:U.ptsMin)?U.ptsMin/U.timescale-f.baseTime/f.timescale:ue,he=void 0!==B&&R?B/R.timescale-f.baseTime/f.timescale:I&&null!=U&&U.ptsMax?U.ptsMax/U.timescale-f.baseTime/f.timescale:ce;F>0?this.lastEndTime=ce:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());var fe={data1:G,data2:void 0,startPTS:de,startDTS:ue,endPTS:he,endDTS:ce,type:P,hasAudio:C,hasVideo:I,nb:1,dropped:0,encrypted:!!E.audio&&E.audio.encrypted||!!E.video&&E.video.encrypted};p.audio=C&&!I?fe:void 0,p.video=I?fe:void 0;var ve=this.isVideoContiguous,pe=null==R?void 0:R.sampleCount;if(pe){var ge=R.keyFrameIndex,ye=-1!==ge;fe.nb=pe,fe.dropped=0===ge||ve?0:ye?ge:pe,fe.independent=ye,fe.firstKeyFrame=ge,ye&&R.keyFrameStart&&(fe.firstKeyFramePTS=(R.keyFrameStart-f.baseTime)/f.timescale),ve||(p.independent=ye),this.isVideoContiguous||(this.isVideoContiguous=ye),fe.dropped&&this.warn("fmp4 does not start with IDR: firstIDR ".concat(ge,"/").concat(pe," dropped: ").concat(fe.dropped," start: ").concat(fe.firstKeyFramePTS||"NA"))}return p.initSegment=m,p.id3=flushTextTrackMetadataCueSamples(r,i,f,f),n.samples.length&&(p.text=flushTextTrackUserdataCueSamples(n,i,f)),p}}])}();function toStartEndOrDefault(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 samplesPresentationEnd(e,t){for(var r=e,n=e,i=0;i<t.length;i++){var a=t[i],s=a.cts,o=a.duration;n=Math.max(n,r+(s||0)+o),r+=o}return n}function computeIFrameDurationRewrite(e,t,r,n){if(void 0!==r){for(var i=e[e.length-1],a=t,s=0;s<e.length-1;s++)a-=e[s].duration;return a<=0&&(a=i.duration),i.duration=a,{durationOffset:r,value:a}}if(void 0!==n){for(var o=Math.round(t/e.length),l=0;l<e.length;l++)e[l].duration=o;return{durationOffset:n,value:o}}}function isInvalidInitPts(e,t,r,n){if(null===e)return!0;var i=Math.max(n,1),a=t-e.baseTime/e.timescale;return Math.abs(a-r)>=i}function getParsedTrackCodec(e,t,r){var n=e.codec;if(n&&n.length>4)return n;if(t===ElementaryStreamTypes.AUDIO){if("ec-3"===n||"ac-3"===n||"alac"===n)return n;if("fLaC"===n||"Opus"===n){return getCodecCompatibleName(n,!1)}return r.warn('Unhandled audio codec "'.concat(n,'" in mp4 MAP')),n||"mp4a"}return"mjpg"===n?n:(r.warn('Unhandled video codec "'.concat(n,'" in mp4 MAP')),n||"avc1")}try{now=self.performance.now.bind(self.performance)}catch(err){now=Date.now}var muxConfig=[{demux:MP4Demuxer,remux:PassThroughRemuxer},{demux:TSDemuxer,remux:MP4Remuxer},{demux:AACDemuxer,remux:MP4Remuxer},{demux:MP3Demuxer,remux:MP4Remuxer}];muxConfig.splice(2,0,{demux:AC3Demuxer,remux:MP4Remuxer});var Transmuxer=function(){return _createClass(function e(t,r,n,i,a,s){_classCallCheck(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=n,this.id=a,this.logger=s},[{key:"configure",value:function(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}},{key:"push",value:function(e,t,r,n){var i=this;if(!this.observer)return emptyResult(r);var a=r.transmuxing;a.executeStart=now();var s=new Uint8Array(e),o=this.currentTransmuxState,l=this.transmuxConfig;n&&(this.currentTransmuxState=n);var u=n||o,c=u.contiguous,d=u.discontinuity,h=u.trackSwitch,f=u.accurateTimeOffset,v=u.timeOffset,p=u.initSegmentChange,g=l.audioCodec,y=l.videoCodec,m=l.defaultInitPts,E=l.duration,S=l.initSegmentData,T=getEncryptionType(s,t);if(T&&isFullSegmentEncryption(T.method)){var k=this.getDecrypter(),_=getAesModeFromFullSegmentMethod(T.method);return this.asyncResult=!0,this.decryptionPromise=k.decrypt(s,T.key.buffer,T.iv.buffer,_,r.decryptRange).then(function(e){var t=i.push(e,null,r);return i.decryptionPromise=null,t}),this.decryptionPromise}var A=this.needsProbing(d,h);if(A){var b=r.iframe&&S&&TSDemuxer.probe(S,this.logger)?S:s,L=this.configureTransmuxer(b);if(L)return this.logger.warn("[transmuxer] ".concat(L.message)),this.observer.emit(Events$2.ERROR,Events$2.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_PARSING_ERROR,fatal:!1,error:L,reason:L.message}),a.executeEnd=now(),emptyResult(r)}(d||h||p||A)&&this.resetInitSegment(S,g,y,E,t,r),(d||p||A)&&this.resetInitialTimestamp(m),c||this.resetContiguity();var R=this.transmux(s,T,v,f,r);this.asyncResult=isPromise(R);var C=this.currentTransmuxState;return C.contiguous=!0,C.discontinuity=!1,C.trackSwitch=!1,a.executeEnd=now(),R}},{key:"flush",value:function(e){var t=this,r=e.transmuxing;r.executeStart=now();var n=this.decrypter,i=this.currentTransmuxState,a=this.decryptionPromise;if(a)return this.asyncResult=!0,a.then(function(){return t.flush(e)});var s=[],o=i.timeOffset;if(n){var l=n.flush();l&&s.push(this.push(l.buffer,null,e))}var u=this.demuxer,c=this.remuxer;if(!u||!c){r.executeEnd=now();var d=[emptyResult(e)];return this.asyncResult?Promise.resolve(d):d}var h=u.flush(o,e);return isPromise(h)?(this.asyncResult=!0,h.then(function(r){return t.flushRemux(s,r,e),s})):(this.flushRemux(s,h,e),this.asyncResult?Promise.resolve(s):s)}},{key:"flushRemux",value:function(e,t,r){if(this.remuxer){var n=t.audioTrack,i=t.videoTrack,a=t.id3Track,s=t.textTrack,o=this.currentTransmuxState,l=o.accurateTimeOffset,u=o.timeOffset;this.logger.log("[transmuxer.ts]: Flushed ".concat(this.id," sn: ").concat(r.sn).concat(r.part>-1?" part: "+r.part:""," of ").concat(this.id," playlist ").concat(r.level));var c=this.remuxer.remux(n,i,a,s,u,l,!0,this.id,r,t.initData,t.sampleData);e.push({remuxResult:c,chunkMeta:r}),r.transmuxing.executeEnd=now()}}},{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,n,i,a){var s=this.demuxer,o=this.remuxer;s&&o&&(s.resetInitSegment(e,t,r,n,i,a),o.resetInitSegment(e,t,r,i))}},{key:"destroy",value:function(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0),this.observer&&this.observer.removeAllListeners(),this.decryptionPromise=null,this.decrypter=this.observer=void 0,this.logger=this.config=this.probe=void 0}},{key:"transmux",value:function(e,t,r,n,i){return"SAMPLE-AES"===(null==t?void 0:t.method)?this.transmuxSampleAes(e,t,r,n,i):this.transmuxUnencrypted(e,r,n,i)}},{key:"transmuxUnencrypted",value:function(e,t,r,n){var i=this.demuxer,a=this.remuxer;if(!i||!a)return emptyResult(n);var s=i.demux(e,t,n,!1,!this.config.progressive),o=s.audioTrack,l=s.videoTrack,u=s.id3Track,c=s.textTrack;return{remuxResult:a.remux(o,l,u,c,t,r,!1,this.id,n,s.initData,s.sampleData),chunkMeta:n}}},{key:"transmuxSampleAes",value:function(e,t,r,n,i){var a=this;return this.demuxer?this.demuxer.demuxSampleAes(e,t,r,i).then(function(e){return{remuxResult:a.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,r,n,!1,a.id,i,e.initData,e.sampleData),chunkMeta:i}}):Promise.reject(new Error("no demuxer"))}},{key:"configureTransmuxer",value:function(e){var t=this.config,r=this.observer,n=this.typeSupported;if(r){var i;try{for(var a=0,s=muxConfig.length;a<s;a++){var o;if(null!=(o=muxConfig[a].demux)&&o.probe(e,this.logger)){i=muxConfig[a];break}}}catch(h){return h}if(!i)return new Error("Failed to find demuxer by probing fragment data");var l=this.demuxer,u=this.remuxer,c=i.demux,d=i.remux;l&&l instanceof c||(this.logger.log("Using ".concat(c.name)),this.demuxer=new c(r,t,n,this.logger),this.probe=c.probe),u&&u instanceof d||(this.logger.log("Using ".concat(d.name)),this.remuxer=new d(r,t,n,this.logger))}}},{key:"needsProbing",value:function(e,t){return!this.demuxer||!this.remuxer||e||t}},{key:"getDecrypter",value:function(){var e=this.decrypter;return e||(e=this.decrypter=new Decrypter(this.config)),e}}])}();function getEncryptionType(e,t){var r=null;return e.byteLength>0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(r=t),r}var emptyResult=function(e){return{remuxResult:{},chunkMeta:e}};function isPromise(e){return"then"in e&&e.then instanceof Function}var TransmuxConfig=_createClass(function e(t,r,n,i,a){_classCallCheck(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=n,this.duration=i,this.defaultInitPts=a||null}),TransmuxState=_createClass(function e(t,r,n,i,a,s){_classCallCheck(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=n,this.trackSwitch=i,this.timeOffset=a,this.initSegmentChange=s}),transmuxerInstanceCount=0,TransmuxerInterface=function(){return _createClass(function e(t,r,n,i){var a=this;_classCallCheck(this,e),this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=transmuxerInstanceCount++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=function(e){var t=e.data,r=a.hls;if(r&&null!=t&&t.event&&t.instanceNo===a.instanceNo)switch(t.event){case"init":var n,i=null==(n=a.workerContext)?void 0:n.objectURL;i&&self.URL.revokeObjectURL(i);break;case"transmuxComplete":a.handleTransmuxComplete(t.data);break;case"flush":a.onFlush(t.data);break;case"workerLog":r.logger[t.data.logType]&&r.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=a.frag,t.data.part=a.part,t.data.id=a.id,r.trigger(t.event,t.data)}},this.onWorkerError=function(e){if(a.hls){var t=new Error("".concat(e.message," (").concat(e.filename,":").concat(e.lineno,")"));a.hls.config.enableWorker=!1,a.hls.logger.warn('Error in "'.concat(a.id,'" Web Worker, fallback to inline')),a.hls.trigger(Events$2.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:t})}};var s=t.config;this.hls=t,this.id=r,this.useWorker=!!s.enableWorker,this.onTransmuxComplete=n,this.onFlush=i;var o=function(e,t){(t=t||{}).frag=a.frag||void 0,e===Events$2.ERROR&&(t.parent=a.id,t.part=a.part,a.error=t.error),a.hls.trigger(e,t)};this.observer=new EventEmitter,this.observer.on(Events$2.FRAG_DECRYPTED,o),this.observer.on(Events$2.ERROR,o);var l=getM2TSSupportedAudioTypes(s.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){var u=this.hls.logger;if(s.workerPath||hasUMDWorker()){try{s.workerPath?(u.log("loading Web Worker ".concat(s.workerPath,' for "').concat(r,'"')),this.workerContext=loadWorker(s.workerPath)):(u.log('injecting Web Worker for "'.concat(r,'"')),this.workerContext=injectWorker());var c=this.workerContext.worker;c.addEventListener("message",this.onWorkerMessage),c.addEventListener("error",this.onWorkerError),c.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:l,id:r,config:stringify(s)})}catch(err){u.warn('Error setting up "'.concat(r,'" Web Worker, fallback to inline'),err),this.terminateWorker(),this.error=null,this.transmuxer=new Transmuxer(this.observer,l,s,"",r,t.logger)}return}}this.transmuxer=new Transmuxer(this.observer,l,s,"",r,t.logger)},[{key:"reset",value:function(){if(this.frag=null,this.part=null,this.workerContext){var e=this.instanceNo;this.instanceNo=transmuxerInstanceCount++;var t=this.hls.config,r=getM2TSSupportedAudioTypes(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:r,id:this.id,config:stringify(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),removeWorkerFromStore(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,n,i,a,s,o,l,u){var c,d,h=this;l.transmuxing.start=self.performance.now();var f=this.instanceNo,v=this.transmuxer,p=a?a.start:i.start,g=i.decryptdata,y=this.frag,m=!y||i.cc!==y.cc,E=!y||l.level!==y.level,S=y?l.sn-y.sn:-1,T=this.part?l.part-this.part.index:-1,k=0===S&&l.id>1&&l.id===(null==y?void 0:y.stats.chunkCount),_=!E&&(1===S||0===S&&(1===T||k&&T<=0)),A=self.performance.now();(E||S||0===i.stats.parsing.start)&&(i.stats.parsing.start=A),!a||!T&&_||(a.stats.parsing.start=A);var b=!(y&&(null==(c=i.initSegment)?void 0:c.url)===(null==(d=y.initSegment)?void 0:d.url)),L=new TransmuxState(m,_,o,E,p,b);if(!_||m||b){this.hls.logger.log("[transmuxer-interface]: Starting new transmux session for ".concat(i.type," sn: ").concat(l.sn).concat(l.part>-1?" part: "+l.part:""," ").concat(this.id," playlist: ").concat(l.level," id: ").concat(l.id,"\n discontinuity: ").concat(m,"\n trackSwitch: ").concat(E,"\n contiguous: ").concat(_,"\n accurateTimeOffset: ").concat(o,"\n timeOffset: ").concat(p,"\n initSegmentChange: ").concat(b));var R=new TransmuxConfig(r,n,t,s,u);this.configureTransmuxer(R)}if(this.frag=i,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:g,chunkMeta:l,state:L},e instanceof ArrayBuffer?[e]:[]);else if(v){var C=v.push(e,g,l,L);isPromise(C)?C.then(function(e){h.handleTransmuxComplete(e)}).catch(function(e){h.transmuxerError(e,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(C)}}},{key:"flush",value:function(e){var t=this;e.transmuxing.start=self.performance.now();var r=this.instanceNo,n=this.transmuxer;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:r,cmd:"flush",chunkMeta:e});else if(n){var i=n.flush(e);isPromise(i)?i.then(function(r){t.handleFlushResult(r,e)}).catch(function(r){t.transmuxerError(r,e,"transmuxer-interface flush error")}):this.handleFlushResult(i,e)}}},{key:"transmuxerError",value:function(e,t,r){this.hls&&(this.error=e,this.hls.trigger(Events$2.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.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)}}])}(),TICK_INTERVAL$3=100,AudioStreamController=function(){function e(t,r,n){var i;return _classCallCheck(this,e),(i=_callSuper(this,e,[t,r,n,"audio-stream-controller",PlaylistLevelType.AUDIO])).mainAnchor=null,i.mainFragLoading=null,i.audioOnly=!1,i.bufferedTrack=null,i.switchingTrack=null,i.trackId=-1,i.nextTrackId=-1,i.waitingData=null,i.mainDetails=null,i.flushing=!1,i.bufferFlushed=!1,i.cachedTrackLoadedData=null,i.registerListeners(),i}return _inherits(e,BaseStreamController),_createClass(e,[{key:"onHandlerDestroying",value:function(){this.unregisterListeners(),_superPropGet(e,"onHandlerDestroying",this)([]),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(){_superPropGet(e,"registerListeners",this)([]);var t=this.hls;t.on(Events$2.LEVEL_LOADED,this.onLevelLoaded,this),t.on(Events$2.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(Events$2.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(Events$2.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(Events$2.BUFFER_RESET,this.onBufferReset,this),t.on(Events$2.BUFFER_CREATED,this.onBufferCreated,this),t.on(Events$2.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(Events$2.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(Events$2.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(Events$2.FRAG_LOADING,this.onFragLoading,this),t.on(Events$2.FRAG_BUFFERED,this.onFragBuffered,this)}},{key:"unregisterListeners",value:function(){var t=this.hls;t&&(_superPropGet(e,"unregisterListeners",this)([]),t.off(Events$2.LEVEL_LOADED,this.onLevelLoaded,this),t.off(Events$2.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(Events$2.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(Events$2.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(Events$2.BUFFER_RESET,this.onBufferReset,this),t.off(Events$2.BUFFER_CREATED,this.onBufferCreated,this),t.off(Events$2.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(Events$2.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(Events$2.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(Events$2.FRAG_LOADING,this.onFragLoading,this),t.off(Events$2.FRAG_BUFFERED,this.onFragBuffered,this))}},{key:"onInitPtsFound",value:function(e,t){var r=t.frag,n=t.id,i=t.initPTS,a=t.timescale,s=t.trackId,o=t.timestampOffsets;if(n===PlaylistLevelType.MAIN){var l=r.cc,u=this.fragCurrent;if(this.initPTS=o,this.log("InitPTS for cc: ".concat(l," found from main: ").concat(i/a," (").concat(i,"/").concat(a,") trackId: ").concat(s)),this.mainAnchor=r,this.state===State.WAITING_INIT_PTS){var c=this.waitingData;(!c&&!this.loadingParts||c&&c.frag.cc!==l)&&this.syncWithAnchor(r,null==c?void 0:c.frag)}else!this.hls.hasEnoughToStart&&u&&u.cc!==l?(u.abortRequests(),this.syncWithAnchor(r,u)):this.state===State.IDLE&&this.tick()}}},{key:"getLoadPosition",value:function(){var t;return!this.startFragRequested&&this.nextLoadPosition>=0&&!1!==(null==(t=this.switchingTrack)?void 0:t.flushImmediate)?this.nextLoadPosition:_superPropGet(e,"getLoadPosition",this)([])}},{key:"syncWithAnchor",value:function(e,t){var r,n=(null==(r=this.mainFragLoading)?void 0:r.frag)||null;if(!t||(null==n?void 0:n.cc)!==t.cc){var i=(n||e).cc,a=findNearestWithCC(this.getLevelDetails(),i,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===State.IDLE&&this.doTickIdle())}}},{key:"startLoad",value:function(e,t){if(!this.levels)return this.startPosition=e,void(this.state=State.STOPPED);var r=this.lastCurrentTime;this.stopLoad(),this.setInterval(TICK_INTERVAL$3),r>0&&-1===e&&!t&&this.initPTS.length&&(this.log("Override startPosition with lastCurrentTime @".concat(r.toFixed(3))),e=r),this.state=State.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,t||this.fragmentTracker.hasFragments(this.playlistType)||(this.startFragRequested=!1),this.tick()}},{key:"doTick",value:function(){switch(this.state){case State.IDLE:this.doTickIdle();break;case State.WAITING_TRACK:var t=this.levels,r=this.trackId,n=null==t?void 0:t[r],i=null==n?void 0:n.details;if(i&&!this.waitForLive(n)){if(this.waitForCdnTuneIn(i))break;this.state=State.WAITING_INIT_PTS}break;case State.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break;case State.WAITING_INIT_PTS: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=State.FRAG_LOADING;var d={frag:s,part:o,payload:l.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(d),u&&_superPropGet(e,"_handleFragmentLoadComplete",this)([d])}else c&&c.cc!==a.frag.cc&&this.syncWithAnchor(c,a.frag)}else this.state=State.IDLE}this.onTickEnd()}},{key:"resetLoadingState",value:function(){var t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null),_superPropGet(e,"resetLoadingState",this)([])}},{key:"onTickEnd",value:function(){var e=this.media;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime,this.checkFragmentChanged())}},{key:"doTickIdle",value:function(){var e,t=this.hls,r=this.levels,n=this.media,i=this.trackId,a=t.config;if(this.buffering&&(n||this.primaryPrefetch||!this.startFragRequested&&a.startFragPrefetch)&&null!=r&&r[i]){var s=r[i],o=s.details;if(!o||this.waitForLive(s)||this.waitForCdnTuneIn(o))return this.state=State.WAITING_TRACK,void(this.startFragRequested=!1);var l=this.getBufferOutput();this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,ElementaryStreamTypes.AUDIO));var u=this.getFwdBufferInfo();if(null!==u){if(!this.switchingTrack&&this._streamEnded(u,o))return t.trigger(Events$2.BUFFER_EOS,{type:"audio"}),void(this.state=State.ENDED);var c=u.len,d=t.maxBufferLength,h=o.fragments,f=h[0].start,v=this.getLoadPosition(),p=this.flushing||this.switchingTrack&&!this.switchingTrack.flushImmediate?v:u.end;if(this.switchingTrack&&n){var g=v;o.PTSKnown&&g<f&&g>=this.timelineOffset&&(u.end>f||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track ".concat(g," -> ").concat(f," + 0.05")),n.currentTime=f+.05)}if(!(c>=d&&!this.switchingTrack&&p<h[h.length-1].start)){var y=this.getNextFragment(p,o);if(y&&this.isLoopLoading(y,p)&&(y=this.getNextFragmentLoopLoading(y,o,u,PlaylistLevelType.MAIN,d)),y){if(!this.exceedsMaxBuffer(u,d,y)){var m=(null==(e=this.mainFragLoading)?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&m&&isMediaFragment(y)&&!y.endList&&(!o.live||!this.loadingParts&&p<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(m)===FragmentState.OK&&(this.mainFragLoading=m=null),m&&isMediaFragment(m))){if(y.start>m.end){var E=this.fragmentTracker.getFragAtPos(p,PlaylistLevelType.MAIN);E&&E.end>m.end&&(m=E,this.mainFragLoading={frag:E,targetBufferTime:null})}if(y.start>m.end)return}this.loadFragment(y,s,p)}}else this.bufferFlushed=!0}}}}},{key:"onMediaDetaching",value:function(t,r){this.bufferFlushed=this.flushing=!1,_superPropGet(e,"onMediaDetaching",this)([t,r])}},{key:"onAudioTracksUpdated",value:function(e,t){var r=t.audioTracks;this.resetTransmuxer(),this.levels=r.map(function(e){return new Level(e)})}},{key:"onAudioTrackSwitching",value:function(e,t){var r=!!t.url;this.trackId=t.id;var n=this.fragCurrent;n&&(n.abortRequests(),this.removeUnbufferedFrags(n.start)),this.resetLoadingState(),r?(this.switchingTrack=t,t.flushImmediate||(this.nextTrackId=t.id,this.nextLevelSwitch()),this.flushAudioIfNeeded(t),this.state!==State.STOPPED&&(this.setInterval(TICK_INTERVAL$3),this.state=State.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}},{key:"onManifestLoading",value:function(){_superPropGet(e,"onManifestLoading",this)([]),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(Events$2.AUDIO_TRACK_LOADED,r))}},{key:"onAudioTrackLoaded",value:function(e,t){var r,n=this.levels,i=t.details,a=t.id,s=t.groupId,o=t.track;if(n){var l=this.mainDetails;if(!l||i.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=t,void(this.state!==State.STOPPED&&(this.state=State.WAITING_TRACK));this.cachedTrackLoadedData=null,this.log("Audio track ".concat(a,' "').concat(o.name,'" of "').concat(s,'" loaded [').concat(i.startSN,",").concat(i.endSN,"]").concat(i.lastPartSn?"[part-".concat(i.lastPartSn,"-").concat(i.lastPartIndex,"]"):"",",duration:").concat(i.totalduration));var u=n[a],c=0;if(i.live||null!=(r=u.details)&&r.live){if(this.checkLiveUpdate(i),i.deltaUpdateFailed)return;var d;if(u.details)c=this.alignPlaylists(i,u.details,null==(d=this.levelLastLoaded)?void 0:d.details);i.alignedSliding||(alignStream(l,i,this),c=i.fragmentStart)}u.details=i,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(l,c),this.hls.trigger(Events$2.AUDIO_TRACK_UPDATED,{details:i,id:a,groupId:t.groupId}),this.state!==State.WAITING_TRACK||this.waitForCdnTuneIn(i)||(this.state=State.IDLE),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,n=e.part,i=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 TransmuxerInterface(this.hls,PlaylistLevelType.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));var h=this.initPTS[r.cc],f=null==(t=r.initSegment)?void 0:t.data;if(void 0!==h){var v=n?n.index:-1,p=-1!==v,g=new ChunkMetadata(r.level,r.sn,r.stats.chunkCount,i.byteLength,v,p,r.duration);d.push(i,f,c,"",r,n,u.totalduration,!1,g,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:n,cache:new ChunkCache,complete:!1}).cache.push(new Uint8Array(i)),this.state!==State.STOPPED&&(this.state=State.WAITING_INIT_PTS)}}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(t){this.waitingData?this.waitingData.complete=!0:_superPropGet(e,"_handleFragmentLoadComplete",this)([t])}},{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===PlaylistLevelType.MAIN&&isMediaFragment(t.frag)&&(this.mainFragLoading=t,this.state===State.IDLE&&this.tick())}},{key:"onFragBuffered",value:function(e,t){var r=t.frag,n=t.part;if(r.type===PlaylistLevelType.AUDIO)if(this.fragContextChanged(r))this.warn("Fragment ".concat(r.sn).concat(n?" p: "+n.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(isMediaFragment(r)){var i=this.switchingTrack;i&&(this.bufferedTrack=i)}this.fragBufferedComplete(r,n),this.media&&this.tick()}else this.audioOnly||r.type!==PlaylistLevelType.MAIN||r.elementaryStreams.video||r.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}},{key:"getFwdBufferInfo",value:function(){var t=this.getBufferOutput();return _superPropGet(e,"getFwdBufferInfo",this)([t,PlaylistLevelType.AUDIO])}},{key:"getBufferOutput",value:function(){return this.mediaBuffer?this.mediaBuffer:this.media}},{key:"checkFragmentChanged",value:function(){var e=this.fragPlaying;if(!this.checkFragPlaying())return!1;var t=this.fragPlaying,r=null==e?void 0:e.level;return t&&t.level===r||(e&&this.cleanupBackBuffer(),this.switchingTrack&&this.completeAudioSwitch(this.switchingTrack)),!0}},{key:"onError",value:function(t,r){var n;if(r.fatal)this.state=State.ERROR;else switch(r.details){case ErrorDetails.FRAG_GAP:case ErrorDetails.FRAG_PARSING_ERROR:case ErrorDetails.FRAG_DECRYPT_ERROR:case ErrorDetails.FRAG_LOAD_ERROR:case ErrorDetails.FRAG_LOAD_TIMEOUT:case ErrorDetails.KEY_LOAD_ERROR:case ErrorDetails.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(PlaylistLevelType.AUDIO,r);break;case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:case ErrorDetails.LEVEL_PARSING_ERROR:r.levelRetry||this.state!==State.WAITING_TRACK||(null==(n=r.context)?void 0:n.type)!==LoaderContextType.AUDIO_TRACK||(this.state=State.IDLE);break;case ErrorDetails.BUFFER_APPEND_NO_PROGRESS:if("audio"!==r.parent)return;r.frag&&(r.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn("Marking fragment ".concat(r.frag.sn," of track ").concat(r.frag.level," as a gap after ").concat(r.appendsWithoutProgress," appends without buffered range growth, to prevent loop loading")),this.fragmentTracker.addAsGap(r.frag));break;case ErrorDetails.BUFFER_ADD_CODEC_ERROR:case ErrorDetails.BUFFER_APPEND_ERROR:if("audio"!==r.parent)return;this.reduceLengthAndFlushBuffer(r)||this.resetLoadingState();break;case ErrorDetails.BUFFER_FULL_ERROR:if("audio"!==r.parent)return;this.reduceLengthAndFlushBuffer(r)&&(this.bufferedTrack=null,_superPropGet(e,"flushMainBuffer",this)([0,Number.POSITIVE_INFINITY,"audio"]));break;case ErrorDetails.INTERNAL_EXCEPTION:this.recoverWorkerError(r)}}},{key:"onBufferFlushing",value:function(e,t){t.type!==ElementaryStreamTypes.VIDEO&&(this.flushing=!0)}},{key:"onBufferFlushed",value:function(e,t){var r=t.type;if(r!==ElementaryStreamTypes.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===State.ENDED&&(this.state=State.IDLE);var n=this.getBufferOutput();n&&(this.afterBufferFlushed(n,r),this.tick())}}},{key:"_handleTransmuxComplete",value:function(t){var r,n="audio",i=this.hls,a=t.remuxResult,s=t.chunkMeta,o=this.getCurrentContext(s);if(o){var l=o.frag,u=o.part,c=o.level,d=c.details,h=a.audio,f=a.text,v=a.id3,p=a.initSegment;if(this.fragContextChanged(l)||!d)return this.fragmentTracker.removeFragment(l),void(null!=p&&p.tracks&&this.resetTransmuxer());if(this.state=State.PARSING,h&&this.switchingTrack&&!this.switchingTrack.flushImmediate){var g=this.config.nextAudioTrackBufferFlushForwardOffset,y=Math.max(this.getLoadPosition()+g,l.start);_superPropGet(e,"flushMainBuffer",this)([y,Number.POSITIVE_INFINITY,PlaylistLevelType.AUDIO])}if(null!=p&&p.tracks){var m=l.initSegment||l;if(this.unhandledEncryptionError(p,l))return;this._bufferInitSegment(c,p.tracks,m,s),i.trigger(Events$2.FRAG_PARSING_INIT_SEGMENT,{frag:m,id:n,tracks:p.tracks})}if(h){var E=h.startPTS,S=h.endPTS,T=h.startDTS,k=h.endDTS;u&&(u.elementaryStreams[ElementaryStreamTypes.AUDIO]={startPTS:E,endPTS:S,startDTS:T,endDTS:k}),l.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO,E,S,T,k),this.bufferFragmentData(h,l,u,s)}if(null!=v&&null!=(r=v.samples)&&r.length){var _=_extends({id:n,frag:l,details:d},v);i.trigger(Events$2.FRAG_PARSING_METADATA,_)}if(f){var A=_extends({id:n,frag:l,details:d},f);i.trigger(Events$2.FRAG_PARSING_USERDATA,A)}}else this.resetWhenMissingContext(s)}},{key:"_bufferInitSegment",value:function(e,t,r,n){if(this.state===State.PARSING&&(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,t.audio)){var i=t.audio;i.id=PlaylistLevelType.AUDIO;var a=e.audioCodec;this.log("Init audio buffer, container:".concat(i.container,", codecs[level/parsed]=[").concat(a,"/").concat(i.codec,"]")),1===(null==a?void 0:a.split(",").length)&&(i.levelCodec=a),this.hls.trigger(Events$2.BUFFER_CODECS,t);var s=i.initSegment;if(null!=s&&s.byteLength){var o={type:"audio",frag:r,part:null,chunkMeta:n,parent:r.type,data:s};this.hls.trigger(Events$2.BUFFER_APPENDING,o)}this.tickImmediate()}}},{key:"loadFragment",value:function(t,r,n){var i,a=this.fragmentTracker.getState(t);if(this.switchingTrack||a===FragmentState.NOT_LOADED||a===FragmentState.PARTIAL)if(null!=(i=r.details)&&i.live&&!this.initPTS[t.cc]){this.log("Waiting for video PTS in continuity counter ".concat(t.cc," of live stream before loading audio fragment ").concat(t.sn," of level ").concat(this.trackId)),this.state=State.WAITING_INIT_PTS;var s=this.mainDetails;s&&s.fragmentStart!==r.details.fragmentStart&&alignStream(s,r.details,this)}else _superPropGet(e,"loadFragment",this)([t,r,n]);else this.clearTrackerIfNeeded(t)}},{key:"flushAudioIfNeeded",value:function(t){if(this.media&&this.bufferedTrack&&t.flushImmediate){var r=this.bufferedTrack;matchesOption({name:r.name,lang:r.lang,assocLang:r.assocLang,characteristics:r.characteristics,audioCodec:r.audioCodec,channels:r.channels},t,audioMatchPredicate)||(useAlternateAudio(t.url,this.hls)?(this.log("Switching audio track : flushing all audio"),_superPropGet(e,"flushMainBuffer",this)([0,Number.POSITIVE_INFINITY,"audio"]),this.bufferedTrack=null):this.bufferedTrack=t)}}},{key:"completeAudioSwitch",value:function(e){var t=this.hls;this.bufferedTrack=e,this.switchingTrack=null,t.trigger(Events$2.AUDIO_TRACK_SWITCHED,_objectSpread2({},e))}},{key:"nextAudioTrack",get:function(){return this.nextTrackId}}])}(),BasePlaylistController=function(){function e(t,r){var n;return _classCallCheck(this,e),(n=_callSuper(this,e,[r,t.logger])).hls=void 0,n.canLoad=!1,n.timer=-1,n.loadingSync=!1,n.hls=t,n}return _inherits(e,Logger$1),_createClass(e,[{key:"destroy",value:function(){this.clearTimer(),this.hls=null}},{key:"clearTimer",value:function(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}},{key:"startLoad",value:function(){this.canLoad=!0,this.loadPlaylist()}},{key:"stopLoad",value:function(){this.canLoad=!1,this.clearTimer()}},{key:"switchParams",value:function(e,t,r){var n=null==t?void 0:t.renditionReports;if(n){for(var i=-1,a=0;a<n.length;a++){var s=n[a],o=void 0;try{o=new self.URL(s.URI,t.url).href}catch(f){this.warn("Could not construct new URL for Rendition Report: ".concat(f)),o=s.URI||""}if(o===e){i=a;break}o===e.substring(0,o.length)&&(i=a)}if(-1!==i){var l=n[i],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&&getSkipValue(r);return new HlsUrlParameters(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(r){this.warn("Could not construct new URL with HLS Delivery Directives: ".concat(r))}return e}},{key:"playlistLoaded",value:function(e,t,r){var n=t.details,i=t.stats,a=n.fragments,s=self.performance.now(),o=i.loading.first?Math.max(0,Math.floor(s-i.loading.first)):0;n.advancedDateTime=Date.now()-o;var l=this.hls.config.timelineOffset;if(l!==n.appliedTimelineOffset){var u=Math.max(l||0,0);n.appliedTimelineOffset=u,a.forEach(function(e){null==e||e.setStart(e.playlistOffset+u)})}if(n.live||null!=r&&r.live){var c,d="levelInfo"in t?t.levelInfo:t.track;n.reloaded(r);var h=null==(c=a[a.length-1])?void 0:c.type;if(n.misses>=this.hls.config.liveMaxUnchangedPlaylistRefresh){var f=new Error("".concat(h," playlist ").concat(d.id," hit max allowed unchanged reloads."));this.warn(f);var v=t.networkDetails,p=t.context;return void this.hls.trigger(Events$2.ERROR,{type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.PLAYLIST_UNCHANGED_ERROR,fatal:!1,url:n.url,error:f,reason:f.message,level:t.level,parent:h,context:p,networkDetails:v,stats:i})}if(r){mergeDetails(r,n,this);var g=n.playlistParsingError;if(g){this.warn(g);var y=this.hls;if(!y.config.ignorePlaylistParsingErrors){var m=t.networkDetails;return void y.trigger(Events$2.ERROR,{type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.LEVEL_PARSING_ERROR,fatal:!1,url:n.url,error:g,reason:g.message,level:t.level,parent:h,networkDetails:m,stats:i})}n.playlistParsingError=null}}-1===n.requestScheduled&&(n.requestScheduled=i.loading.start);var E=this.hls.mainForwardBufferInfo,S=E?E.end-E.len:0,T=computeReloadInterval(n,1e3*(n.edge-S));n.requestScheduled+T<s?n.requestScheduled=s:n.requestScheduled<=s&&(n.requestScheduled+=T);var k,_=t.deliveryDirectives;if(this.log("live playlist ".concat(e," ").concat(n.advanced?"REFRESHED ".concat(n.lastPartSn," - ").concat(n.lastPartIndex):n.updated?"UPDATED":"MISSED (received ".concat(n.lastPartSn," - ").concat(n.lastPartIndex).concat(_?" | requested ".concat(_.msn," - ").concat(_.part):"",")"))),!this.canLoad||!n.live)return;var A=void 0,b=void 0;if(n.canBlockReload&&n.advanced){var L=this.hls.config.lowLatencyMode,R=n.lastPartSn,C=n.endSN,I=n.lastPartIndex,P=R===C;-1!==I?P?(A=C+1,b=L?0:I):(A=R,b=L?I+1:n.maxPartIndex):A=C+1;var D=n.age,w=D+n.ageHeader,O=Math.min(w-n.partTarget,1.5*n.targetduration);if(O>0){if(w>3*n.targetduration)this.log("Playlist last advanced ".concat(D.toFixed(2),"s ago. Omitting segment and part directives.")),A=void 0,b=void 0;else if(null!=r&&r.tuneInGoal&&w-n.partTarget>r.tuneInGoal)this.warn("CDN Tune-in goal increased from: ".concat(r.tuneInGoal," to: ").concat(O," with playlist age: ").concat(n.age)),O=0;else{var x=Math.floor(O/n.targetduration);if(A+=x,void 0!==b)b+=Math.round(O%n.targetduration/n.partTarget);this.log("CDN Tune-in age: ".concat(n.ageHeader,"s last advanced ").concat(D.toFixed(2),"s goal: ").concat(O," skip sn ").concat(x," to part ").concat(b))}n.tuneInGoal=O}if(k=this.getDeliveryDirectives(n,t.deliveryDirectives,A,b),L||!P)return n.requestScheduled=s,void this.loadingPlaylist(d,k)}else(n.canBlockReload||n.canSkipUntil)&&(k=this.getDeliveryDirectives(n,t.deliveryDirectives,A,b));k&&void 0!==A&&n.canBlockReload&&(n.requestScheduled=i.loading.first+Math.max(T-2*o,T/2)),this.scheduleLoading(d,k,n)}else this.clearTimer()}},{key:"scheduleLoading",value:function(e,t,r){var n=this,i=r||e.details;if(i){var a=self.performance.now(),s=i.requestScheduled;if(a>=s&&!this.loadingSync)return this.loadingSync=!0,this.loadingPlaylist(e,t),void(this.loadingSync=!1);var o=Math.max(s-a,0);this.log("reload live playlist ".concat(e.name||e.bitrate+"bps"," in ").concat(Math.round(o)," ms")),this.clearTimer(),this.timer=self.setTimeout(function(){return n.loadingPlaylist(e,t)},o)}else this.loadingPlaylist(e,t)}},{key:"getDeliveryDirectives",value:function(e,t,r,n){var i=getSkipValue(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(r=t.msn,n=t.part,i=HlsSkip.No),new HlsUrlParameters(r,n,i)}},{key:"checkRetry",value:function(e){var t=this,r=e.details,n=isTimeoutError(e),i=e.errorAction,a=i||{},s=a.action,o=a.retryCount,l=void 0===o?0:o,u=a.retryConfig,c=!!i&&!!u&&(s===NetworkErrorAction.RetryRequest||!i.resolved&&s===NetworkErrorAction.SendAlternateToPenaltyBox);if(c){var d;if(l>=u.maxNumRetry)return!1;if(n&&null!=(d=e.context)&&d.deliveryDirectives)this.warn("Retrying playlist loading ".concat(l+1,"/").concat(u.maxNumRetry,' after "').concat(r,'" without delivery-directives')),this.loadPlaylist();else{var h,f=offlineHttpStatus(null==(h=e.response)?void 0:h.code);if(this.clearTimer(),f)this.log("Waiting for connection (offline)"),e.reason="offline",this.timer=self.setTimeout(function(){return t.checkOfflineStatus()},1e3);else{var v=getRetryDelay(u,l);this.warn("Retrying playlist loading ".concat(l+1,"/").concat(u.maxNumRetry,' after "').concat(r,'" in ').concat(v,"ms")),this.timer=self.setTimeout(function(){return t.loadPlaylist()},v)}}e.levelRetry=!0,i.resolved=!0}return c}},{key:"checkOfflineStatus",value:function(){var e=this;this.clearTimer(),offlineHttpStatus(0)?this.timer=self.setTimeout(function(){return e.checkOfflineStatus()},1e3):(this.log("Connection restored (online)"),this.loadPlaylist())}}])}();function subtitleOptionsIdentical(e,t){if(e.length!==t.length)return!1;for(var r=0;r<e.length;r++)if(!mediaAttributesIdentical(e[r].attrs,t[r].attrs))return!1;return!0}function mediaAttributesIdentical(e,t,r){var n=e["STABLE-RENDITION-ID"];return n&&!r?n===t["STABLE-RENDITION-ID"]:!(r||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(function(r){return e[r]!==t[r]})}var AudioTrackController=function(){function e(t){var r;return _classCallCheck(this,e),(r=_callSuper(this,e,[t,"audio-track-controller"])).tracks=[],r.groupIds=null,r.tracksInGroup=[],r.trackId=-1,r.currentTrack=null,r.selectDefaultTrack=!0,r.registerListeners(),r}return _inherits(e,BasePlaylistController),_createClass(e,[{key:"registerListeners",value:function(){var e=this.hls;e.on(Events$2.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events$2.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Events$2.LEVEL_LOADING,this.onLevelLoading,this),e.on(Events$2.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Events$2.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(Events$2.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(Events$2.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events$2.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Events$2.LEVEL_LOADING,this.onLevelLoading,this),e.off(Events$2.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Events$2.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(Events$2.ERROR,this.onError,this)}},{key:"destroy",value:function(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,_superPropGet(e,"destroy",this)([])}},{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,n=t.groupId,i=t.details,a=this.tracksInGroup[r];if(a&&a.groupId===n){var s=a.details;a.details=t.details,this.log("Audio track ".concat(r,' "').concat(a.name,'" lang:').concat(a.lang," group:").concat(n," loaded [").concat(i.startSN,"-").concat(i.endSN,"]")),r===this.trackId&&this.playlistLoaded(r,t,s)}else this.warn("Audio track with id:".concat(r," and group:").concat(n," 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,n=this.groupIds,i=this.currentTrack;if(!r||(null==n?void 0:n.length)!==(null==r?void 0:r.length)||null!=r&&r.some(function(e){return-1===(null==n?void 0:n.indexOf(e))})){this.groupIds=r,this.trackId=-1,this.currentTrack=null;var a=this.tracks.filter(function(e){return inGroupOrNone(e.groupId,r)});if(a.length)this.selectDefaultTrack&&!a.some(function(e){return e.default})&&(this.selectDefaultTrack=!1),a.forEach(function(e,t){e.id=t});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=a;var s=this.hls.config.audioPreference;if(!i&&s){var o=findMatchingOption(s,a,audioMatchPredicate);if(o>-1)i=a[o];else{var l=findMatchingOption(s,this.tracks);i=this.tracks[l]}}var u=this.findTrackId(i);-1===u&&i&&(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(Events$2.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(Events$2.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:f})}}}}},{key:"onError",value:function(e,t){!t.fatal&&t.context&&t.context.type===LoaderContextType.AUDIO_TRACK&&t.context.id===this.trackId&&inGroupOrNone(t.context.groupId,this.groupIds)&&this.checkRetry(t)}},{key:"allAudioTracks",get:function(){return this.tracks}},{key:"audioTracks",get:function(){return this.tracksInGroup}},{key:"audioTrack",get:function(){return this.trackId},set:function(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}},{key:"nextAudioTrack",get:function(){return this.trackId},set:function(e){this.selectDefaultTrack=!1,this.setAudioTrack(e,!1)}},{key:"setAudioOption",value:function(e){var t=this.hls;if(t.config.audioPreference=e,e){var r=this.allAudioTracks;if(this.selectDefaultTrack=!1,r.length){var n=this.currentTrack;if(n&&matchesOption(e,n,audioMatchPredicate))return n;var i=findMatchingOption(e,this.tracksInGroup,audioMatchPredicate);if(i>-1){var a=this.tracksInGroup[i];return this.setAudioTrack(i,"flushImmediate"in e&&e.flushImmediate),a}if(n){var s=t.loadLevel;-1===s&&(s=t.firstAutoLevel);var o=findClosestLevelWithAudioGroup(e,t.levels,r,s,audioMatchPredicate);if(-1===o)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){var l=findMatchingOption(e,r);if(l>-1)return r[l]}}}return null}},{key:"setAudioTrack",value:function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],r=this.tracksInGroup;if(e<0||e>=r.length)this.warn("Invalid audio track id: ".concat(e));else{this.selectDefaultTrack=!1;var n=this.currentTrack,i=r[e],a=i.details&&!i.details.live;if(!(e===this.trackId&&i===n&&a||(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(Events$2.AUDIO_TRACK_SWITCHING,_objectSpread2(_objectSpread2({},i),{},{flushImmediate:t})),a))){var s=this.switchParams(i.url,null==n?void 0:n.details,i.details);this.loadPlaylist(s)}}}},{key:"findTrackId",value:function(e){for(var t=this.tracksInGroup,r=0;r<t.length;r++){var n=t[r];if((!this.selectDefaultTrack||n.default)&&(!e||matchesOption(e,n,audioMatchPredicate)))return r}if(e){for(var i=e.name,a=e.lang,s=e.assocLang,o=e.characteristics,l=e.audioCodec,u=e.channels,c=0;c<t.length;c++){if(matchesOption({name:i,lang:a,assocLang:s,characteristics:o,audioCodec:l,channels:u},t[c],audioMatchPredicate))return c}for(var d=0;d<t.length;d++){var h=t[d];if(mediaAttributesIdentical(e.attrs,h.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return d}for(var f=0;f<t.length;f++){var v=t[f];if(mediaAttributesIdentical(e.attrs,v.attrs,["LANGUAGE"]))return f}}return-1}},{key:"loadPlaylist",value:function(t){_superPropGet(e,"loadPlaylist",this)([]);var r=this.currentTrack;this.shouldLoadPlaylist(r)&&useAlternateAudio(r.url,this.hls)&&this.scheduleLoading(r,t)}},{key:"loadingPlaylist",value:function(t,r){_superPropGet(e,"loadingPlaylist",this)([t,r]);var n=t.id,i=t.groupId,a=this.getUrlWithDirectives(t.url,r),s=t.details,o=null==s?void 0:s.age;this.log("Loading audio-track ".concat(n,' "').concat(t.name,'" lang:').concat(t.lang," group:").concat(i).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(Events$2.AUDIO_TRACK_LOADING,{url:a,id:n,groupId:i,deliveryDirectives:r||null,track:t})}}])}(),BufferOperationQueue=function(){return _createClass(function e(t){_classCallCheck(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 n=this.queues[t];n.push(e),1!==n.length||r||this.executeNext(t)}}},{key:"appendBlocker",value:function(e){var t=this;return new Promise(function(r){var n={label:"async-blocker",execute:r,onStart:function(){},onComplete:function(){},onError:function(){}};t.append(n,e)})}},{key:"prependBlocker",value:function(e){var t=this;return new Promise(function(r){if(t.queues){var n={label:"async-blocker-prepend",execute:r,onStart:function(){},onComplete:function(){},onError:function(){}};t.queues[e].unshift(n)}})}},{key:"removeBlockers",value:function(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(function(e){var t,r=null==(t=e[0])?void 0:t.label;"async-blocker"===r||"async-blocker-prepend"===r?(e[0].execute(),e.splice(0,1)):"block-audio"===r&&e.splice(0,1)})}},{key:"insertNext",value:function(e,t){var r;null!==this.queues&&(r=this.queues[t]).splice.apply(r,[1,0].concat(_toConsumableArray(e)))}},{key:"unblockAudio",value:function(){var e;null!==this.queues&&"block-audio"===(null==(e=this.current("audio"))?void 0:e.label)&&this.shiftAndExecuteNext("audio")}},{key:"audioBlocking",value:function(){return null!==this.queues&&this.queues.audio.some(function(e){return"block-audio"===e.label})}},{key:"executeNext",value:function(e){if(null!==this.queues&&null!==this.tracks){var t=this.queues[e];if(t.length){var r=t[0];try{r.execute()}catch(a){var n;if(r.onError(a),null===this.queues||null===this.tracks)return;var i=null==(n=this.tracks[e])?void 0:n.buffer;null!=i&&i.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],n=null==r?void 0:r.buffer;return n?"SourceBuffer".concat(n.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(", "))||""}}])}(),VIDEO_CODEC_PROFILE_REPLACE=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,TRACK_REMOVED_ERROR_NAME="HlsJsTrackRemovedError",LOOP_FLUSH_SAFETY_MARGIN=.25,MIN_BUFFERED_PROGRESS=.001,HlsJsTrackRemovedError=function(){function e(t){var r;return _classCallCheck(this,e),(r=_callSuper(this,e,[t])).name=TRACK_REMOVED_ERROR_NAME,r}return _inherits(e,_wrapNativeSuper(Error)),_createClass(e)}(),BufferController=function(){function e(t,r){var n;return _classCallCheck(this,e),(n=_callSuper(this,e,["buffer-controller",t.logger])).hls=void 0,n.fragmentTracker=void 0,n.fragmentAppendProgress=Object.create(null),n.appendsWithoutProgress=Object.create(null),n.details=null,n._objectUrl=null,n.operationQueue=null,n.bufferCodecEventsTotal=0,n.media=null,n.mediaSource=null,n.lastMpegAudioChunk=null,n.lastVideoAppendEnd=0,n.appendSource=void 0,n.transferData=void 0,n.overrides=void 0,n.appendErrors={audio:0,video:0,audiovideo:0},n.appendError=void 0,n._quotaEvictionPending={},n.tracks={},n.sourceBuffers=[[null,null],[null,null]],n._onEndStreaming=function(e){var t;n.hls&&"open"===(null==(t=n.mediaSource)?void 0:t.readyState)&&n.media&&!n.media.seeking&&n.hls.pauseBuffering()},n._onStartStreaming=function(e){n.hls&&n.hls.resumeBuffering()},n._onMediaSourceOpen=function(e){var t=n,r=t.media,i=t.mediaSource;e&&n.log("Media source opened"),r&&i&&(removeEventListener(i,"sourceopen",n._onMediaSourceOpen),removeEventListener(r,"emptied",n._onMediaEmptied),n.updateDuration(),n.hls.trigger(Events$2.MEDIA_ATTACHED,{media:r,mediaSource:i}),null!==n.mediaSource&&n.checkPendingTracks())},n._onMediaSourceClose=function(){if(n.log("Media source closed"),n.media){var e=n.media.error,t=n,r=t.appendError,i=t.appendErrors,a=!1;if(!r&&e)a=Math.max(++i.audio,++i.video,++i.audiovideo)>=n.hls.config.appendErrorMaxRetry;var s=new Error("MediaSource closed while media attached".concat(mediaErrorRecoveryMessage(a,e)));n.warn(s),n.hls.trigger(Events$2.ERROR,_extends({fatal:a},r,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.MEDIA_SOURCE_REQUIRES_RESET,error:s}))}},n._onMediaSourceEnded=function(){n.log("Media source ended")},n._onMediaEmptied=function(){var e=n,t=e.mediaSrc,r=e._objectUrl;t!==r&&n.error("Media element src was set while attaching MediaSource (".concat(r," > ").concat(t,")"))},n._onMediaError=function(){var e,t,r=n.media;r&&n.log("Media error (code: ".concat(null==(e=r.error)?void 0:e.code,"): ").concat(null==(t=r.error)?void 0:t.message))},n.hls=t,n.fragmentTracker=r,n.appendSource=isManagedMediaSource(_getMediaSource2(t.config.preferManagedMediaSource)),n.initTracks(),n.registerListeners(),n}return _inherits(e,Logger$1),_createClass(e,[{key:"hasSourceTypes",value:function(){return Object.keys(this.tracks).length>0}},{key:"destroy",value:function(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null,this._onMediaEmptied=this._onMediaError=null}},{key:"registerListeners",value:function(){var e=this.hls;e.on(Events$2.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Events$2.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events$2.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events$2.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Events$2.BUFFER_RESET,this.onBufferReset,this),e.on(Events$2.BUFFER_APPENDING,this.onBufferAppending,this),e.on(Events$2.BUFFER_CODECS,this.onBufferCodecs,this),e.on(Events$2.BUFFER_EOS,this.onBufferEos,this),e.on(Events$2.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Events$2.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Events$2.FRAG_PARSED,this.onFragParsed,this),e.on(Events$2.FRAG_CHANGED,this.onFragChanged,this),e.on(Events$2.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(Events$2.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Events$2.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events$2.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events$2.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Events$2.BUFFER_RESET,this.onBufferReset,this),e.off(Events$2.BUFFER_APPENDING,this.onBufferAppending,this),e.off(Events$2.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Events$2.BUFFER_EOS,this.onBufferEos,this),e.off(Events$2.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Events$2.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Events$2.FRAG_PARSED,this.onFragParsed,this),e.off(Events$2.FRAG_CHANGED,this.onFragChanged,this),e.off(Events$2.ERROR,this.onError,this)}},{key:"transferMedia",value:function(){var e=this,t=this.media,r=this.mediaSource;if(!t)return null;var n={};if(this.operationQueue){var i=this.isUpdating();i||this.operationQueue.removeBlockers();var a=this.isQueued();(i||a)&&this.warn("Transfering MediaSource with".concat(a?" operations in queue":"").concat(i?" updating SourceBuffer(s)":""," ").concat(this.operationQueue)),this.operationQueue.destroy()}var s=this.transferData;return s&&!this.sourceBufferCount&&s.mediaSource===r?_extends(n,s.tracks):this.sourceBuffers.forEach(function(t){var r=_slicedToArray(t,1)[0];r&&(n[r]=_extends({},e.tracks[r]),e.removeBuffer(r)),t[0]=t[1]=null}),{media:t,mediaSource:r,tracks:n}}},{key:"initTracks",value:function(){this.resetAppendProgress(),this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0}},{key:"onManifestLoading",value:function(){this.bufferCodecEventsTotal=0,this.details=null,this.resetAppendErrors(),this.resetAppendProgress()}},{key:"onManifestParsed",value:function(e,t){var r,n=2;(t.audio&&!t.video||!t.altAudio)&&(n=1),this.bufferCodecEventsTotal=n,this.log("".concat(n," bufferCodec event(s) expected.")),null!=(r=this.transferData)&&r.mediaSource&&this.sourceBufferCount&&n&&this.bufferCreated()}},{key:"onMediaAttaching",value:function(e,t){var r=this.media=t.media;this.transferData=this.overrides=void 0;var n=_getMediaSource2(this.appendSource);if(n){var i=!!t.mediaSource;(i||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);var a=this.mediaSource=t.mediaSource||new n;if(this.assignMediaSource(a),i)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,removeSourceChildren(r),addSource(r,s),r.load()}catch(l){r.src=s}else r.src=s}addEventListener(r,"emptied",this._onMediaEmptied),addEventListener(r,"error",this._onMediaError),this.appendSource&&addEventListener(r,"seeking",this._onStartStreaming)}}},{key:"assignMediaSource",value:function(e){var t,r;this.log("".concat((null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created"," media source: ").concat(null==(r=e.constructor)?void 0:r.name)),addEventListener(e,"sourceopen",this._onMediaSourceOpen),addEventListener(e,"sourceended",this._onMediaSourceEnded),addEventListener(e,"sourceclose",this._onMediaSourceClose),this.appendSource&&(addEventListener(e,"startstreaming",this._onStartStreaming),addEventListener(e,"endstreaming",this._onEndStreaming))}},{key:"attachTransferred",value:function(){var e=this,t=this.media,r=this.transferData;if(r&&t){var n=this.tracks,i=r.tracks,a=i?Object.keys(i):null,s=a?a.length:0,o=function(){Promise.resolve().then(function(){e.media&&e.mediaSourceOpenOrEnded&&e._onMediaSourceOpen()})};if(i&&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(stringify(n,function(e,t){return"initSegment"===e?void 0:t}),";\ntransfer tracks: ").concat(stringify(i,function(e,t){return"initSegment"===e?void 0:t}),"}")),!isCompatibleTrackChange(i,n)){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(i),'"->"').concat(Object.keys(n),'") start time: ').concat(c," currentTime: ").concat(l)),this.onMediaDetaching(Events$2.MEDIA_DETACHING,{}),this.onMediaAttaching(Events$2.MEDIA_ATTACHING,r),void(t.currentTime=c))}this.transferData=void 0,a.forEach(function(t){var r=t,n=i[r];if(n){var a=n.buffer;if(a){var s=e.fragmentTracker,o=n.id;if(s.hasFragments(o)||s.hasParts(o)){var l=BufferHelper.getBuffered(a);s.detectEvictedFragments(r,l,o,null,null,!0)}var u=sourceBufferNameToIndex(r),c=[r,a];e.sourceBuffers[u]=c,a.updating&&e.operationQueue&&e.operationQueue.prependBlocker(r),e.trackSourceBuffer(r,n)}}}),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,n=!!t.transferMedia;this.transferData=this.overrides=void 0;var i=this.media,a=this.mediaSource,s=this._objectUrl;if(a){if(this.log("media source ".concat(n?"transferring":"detaching")),n)this.sourceBuffers.forEach(function(e){var t=_slicedToArray(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(err){this.warn("onMediaDetaching: ".concat(err.message," while calling endOfStream"))}}this.sourceBufferCount&&this.onBufferReset()}removeEventListener(a,"sourceopen",this._onMediaSourceOpen),removeEventListener(a,"sourceended",this._onMediaSourceEnded),removeEventListener(a,"sourceclose",this._onMediaSourceClose),this.appendSource&&(removeEventListener(a,"startstreaming",this._onStartStreaming),removeEventListener(a,"endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}i&&(removeEventListener(i,"emptied",this._onMediaEmptied),removeEventListener(i,"error",this._onMediaError),removeEventListener(i,"seeking",this._onStartStreaming),n||(s&&self.URL.revokeObjectURL(s),this.mediaSrc===s?(i.removeAttribute("src"),this.appendSource&&removeSourceChildren(i),i.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null)}},{key:"onBufferReset",value:function(){var e=this;this.sourceBuffers.forEach(function(t){var r=_slicedToArray(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 n;null!=(n=this.mediaSource)&&n.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(r)}catch(err){this.warn("onBufferReset ".concat(e),err)}delete this.tracks[e]}},{key:"removeBuffer",value:function(e){this.removeBufferListeners(e),this.sourceBuffers[sourceBufferNameToIndex(e)]=[null,null];var t=this.tracks[e];t&&(this.clearBufferAppendTimeoutId(t),t.buffer=void 0)}},{key:"resetQueue",value:function(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new BufferOperationQueue(this.tracks)}},{key:"onBufferCodecs",value:function(e,t){var r,n=this,i=this.tracks,a=Object.keys(t);this.log('BUFFER_CODECS: "'.concat(a,'" (current SB count ').concat(this.sourceBufferCount,")"));var s="audiovideo"in t&&(i.audio||i.video)||i.audiovideo&&("audio"in t||"video"in t),o=!s&&this.sourceBufferCount&&this.media&&a.some(function(e){return!i[e]});s||o?this.warn('Unsupported transition between "'.concat(Object.keys(i),'" 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=i[e],v=null==(r=n.transferData)||null==(r=r.tracks)?void 0:r[e],p=null!=v&&v.buffer?v:f,g=(null==p?void 0:p.pendingCodec)||(null==p?void 0:p.codec),y=null==p?void 0:p.levelCodec;f||(f=i[e]={buffer:void 0,listeners:[],codec:l,supplemental:h,container:c,levelCodec:u,metadata:d,id:o});var m=pickMostCompleteCodecName(g,y),E=null==m?void 0:m.replace(VIDEO_CODEC_PROFILE_REPLACE,"$1"),S=pickMostCompleteCodecName(l,u),T=null==(a=S)?void 0:a.replace(VIDEO_CODEC_PROFILE_REPLACE,"$1");S&&m&&E!==T&&("audio"===e.slice(0,5)&&(S=getCodecCompatibleName(S,n.appendSource)),n.log("switching codec ".concat(g," to ").concat(S)),S!==(f.pendingCodec||f.codec)&&(f.pendingCodec=S),f.container=c,n.appendChangeType(e,c,S))}),(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 n=e.tracks[r];return t[r]={id:n.id,container:n.container,codec:n.codec,levelCodec:n.levelCodec},t},{})}},{key:"appendChangeType",value:function(e,t,r){var n=this,i="".concat(t,";codecs=").concat(r),a={label:"change-type=".concat(i),execute:function(){var a=n.tracks[e];if(a){var s=a.buffer;null!=s&&s.changeType&&(n.log("changing ".concat(e," sourceBuffer type to ").concat(i)),s.changeType(i),a.codec=r,a.container=t)}n.shiftAndExecuteNext(e)},onStart:function(){},onComplete:function(){},onError:function(t){n.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,n=e.start,i=n+.05*e.duration;if(!(!0===(null==(t=this.fragmentTracker.getAppendedFrag(n,PlaylistLevelType.MAIN))?void 0:t.gap))){var a={label:"block-audio",execute:function(){var e,t;(r.lastVideoAppendEnd>i||BufferHelper.isBuffered(null==(e=r.tracks.video)?void 0:e.buffer,i)||!0===(null==(t=r.fragmentTracker.getAppendedFrag(i,PlaylistLevelType.MAIN))?void 0:t.gap))&&r.unblockAudio()},onStart:function(){},onComplete:function(){},onError:function(e){r.warn("Error executing block-audio operation",e)}};this.append(a,"audio",!0)}}},{key:"unblockAudio",value:function(){this.operationQueue&&this.operationQueue.unblockAudio()}},{key:"onBufferAppending",value:function(e,t){var r=this,n=this.tracks,i=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=isMediaFragment(o)&&!l&&!o.gap&&!u.partial&&!u.iframe,f=null,v=!1,p=o.sn,g=o.cc,y=self.performance.now();d.start=y;var m=o.stats.buffering,E=l?l.stats.buffering:null;0===m.start&&(m.start=y),0===(null==E?void 0:E.start)&&(E.start=y);var S=n.audio,T=!1;"audio"===a&&"audio/mpeg"===(null==S?void 0:S.container)&&(T=!this.lastMpegAudioChunk||1===u.id||this.lastMpegAudioChunk.sn!==u.sn,this.lastMpegAudioChunk=u);var k=n.video,_=null==k?void 0:k.buffer;if(_&&"initSegment"!==p&&void 0!==c){var A=null==S?void 0:S.buffer,b=l||o;if("audio"===a&&"main"!==s&&!k.ending&&!k.ended&&A&&BufferHelper.getBuffered(A).length){var L=b.start+.05*b.duration,R=BufferHelper.getBuffered(_),C=this.currentOp("video");R.length||C?!BufferHelper.isBuffered(_,L)&&this.lastVideoAppendEnd<L&&this.blockAudio(b):this.blockAudio(b)}else if("video"===a){var I=b.end,P=this.lastVideoAppendEnd-I;this.lastVideoAppendEnd=I,P<0||P>b.duration?this.unblockAudio():this.isAudioBlocked()&&this.executeNext("audio")}}var D=(l||o).start,w={label:"append-".concat(a),execute:function(){var e;d.executeStart=self.performance.now();var t=null==(e=r.tracks[a])?void 0:e.buffer;t&&(h&&(f=BufferHelper.timeRangesToArray(BufferHelper.getBuffered(t)),v=isFragmentFullyBuffered(fragmentBufferedCoverage(f,o),o)),T?r.updateTimestampOffset(t,D,.1,a,p,g):void 0!==c&&isFiniteNumber(c)&&r.updateTimestampOffset(t,c,1e-6,a,p,g)),r.appendExecutor(i,a)},onStart:function(){},onComplete:function(){r.clearBufferAppendTimeoutId(r.tracks[a]);var e=self.performance.now();d.executeEnd=d.end=e,0===m.first&&(m.first=e),0===(null==E?void 0:E.first)&&(E.first=e);var t={};if(r.sourceBuffers.forEach(function(e){var r=_slicedToArray(e,2),n=r[0],i=r[1];n&&(t[n]=BufferHelper.getBuffered(i))}),h){var n=r.getFragmentAppendProgress(o),i=t[a];if(i&&f){var c=fragmentBufferedCoverage(BufferHelper.timeRangesToArray(i),o);n.progressed||(n.progressed=c-fragmentBufferedCoverage(f,o)>MIN_BUFFERED_PROGRESS);var p=v&&isFragmentFullyBuffered(c,o);n.fullyBuffered[a]=(void 0===n.fullyBuffered[a]||n.fullyBuffered[a])&&p}}r.hls.trigger(Events$2.BUFFER_APPENDED,{type:a,frag:o,part:l,chunkMeta:u,parent:s,timeRanges:t})},onError:function(e){var t;r.clearBufferAppendTimeoutId(r.tracks[a]);var n=e.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==e.name||"quota"in e;if(n&&!r._quotaEvictionPending[a]){var c=r.getBackBufferEvictionTarget(a,i.byteLength,o.type);if(c>0){r._quotaEvictionPending[a]=!0,r.log('QuotaExceededError on "'.concat(a,'" append sn: ').concat(p," - evicting back buffer to ").concat(c.toFixed(3),"s and retrying"));var d=r.getFlushOp(a,0,c),f=r.getClearEvictionPendingOp(a);return void r.insertNext([d,w,f],a)}r.warn('QuotaExceededError on "'.concat(a,'" sn: ').concat(p," - no back buffer available to evict"))}h&&(r.getFragmentAppendProgress(o).errored=!0);var v={type:ErrorTypes.MEDIA_ERROR,parent:s,details:ErrorDetails.BUFFER_APPEND_ERROR,sourceBufferName:a,frag:o,part:l,chunkMeta:u,error:e,err:e,fatal:!1},g=null==(t=r.media)?void 0:t.error;if(e.name!==TRACK_REMOVED_ERROR_NAME||0!==r.sourceBufferCount||r.media&&0!==r.pendingTrackCount){var y;n&&(v.details=ErrorDetails.BUFFER_FULL_ERROR);var m=++r.appendErrors[a],E=r.hls.config.appendErrorMaxRetry;r.warn("Failed ".concat(m,"/").concat(E+1,' times to append segment in "').concat(a,'" sourceBuffer with error: ').concat(e.message)),m>=E&&(v.fatal=!n);var S=null==(y=r.mediaSource)?void 0:y.readyState;("ended"===S||"closed"===S||g)&&(r.warn('MediaSource readyState "'.concat(S,'" during SourceBuffer').concat(mediaErrorRecoveryMessage(v.fatal,g))),v.details=ErrorDetails.MEDIA_SOURCE_REQUIRES_RESET)}else v.errorAction=createDoNothingErrorAction(!0);r.appendError=v,r.hls.trigger(Events$2.ERROR,v),n&&r.hls&&r.trimBuffers(o.start,1)}};this.log('queuing "'.concat(a,'" append sn: ').concat(p).concat(l?" p: "+l.index:""," of ").concat(s," playlist ").concat(o.level," cc: ").concat(g," offset: ").concat(c," bytes: ").concat(i.byteLength)),this.append(w,a,this.isPending(this.tracks[a]))}},{key:"getClearEvictionPendingOp",value:function(e){var t=this;return{label:"clear",execute:function(){t._quotaEvictionPending[e]=!1,t.shiftAndExecuteNext(e)},onStart:function(){},onComplete:function(){},onError:function(){}}}},{key:"getFlushOp",value:function(e,t,r){var n=this;return this.log('queuing "'.concat(e,'" remove ').concat(t,"-").concat(r)),{label:"remove",execute:function(){n.removeExecutor(e,t,r)},onStart:function(){},onComplete:function(){var i,a=null==(i=n.tracks[e])?void 0:i.buffer;n.log("Remove request ".concat(t,"-").concat(r," from ").concat(e," Source Buffer complete > buffer: ").concat(a?timeRangesToString(BufferHelper.getBuffered(a)):"(detached)")),n.hls.trigger(Events$2.BUFFER_FLUSHED,{type:e,start:t,end:r})},onError:function(i){n.warn("Failed to remove ".concat(t,"-").concat(r,' from "').concat(e,'" SourceBuffer'),i),n.hls.trigger(Events$2.BUFFER_FLUSHED,{type:e,start:0,end:0,error:i})}}}},{key:"onBufferFlushing",value:function(e,t){var r=this,n=t.type,i=t.startOffset,a=t.endOffset;n&&"audio"!==n||this.unblockAudio(),n?this.append(this.getFlushOp(n,i,a),n):this.sourceBuffers.forEach(function(e){var t=_slicedToArray(e,1)[0];t&&r.append(r.getFlushOp(t,i,a),t)})}},{key:"onFragParsed",value:function(e,t){var r=this,n=t.frag,i=t.part,a=t.chunkMeta,s=[],o=i?i.elementaryStreams:n.elementaryStreams;o[ElementaryStreamTypes.AUDIOVIDEO]?s.push("audiovideo"):(o[ElementaryStreamTypes.AUDIO]&&s.push("audio"),o[ElementaryStreamTypes.VIDEO]&&s.push("video"));0===s.length&&this.log("Fragments must have at least one ElementaryStreamType set. ".concat(n.type," ").concat(n.level," ").concat(i?"part: ".concat(i.index," of "):"","sn: ").concat(n.sn)),this.blockBuffers(function(){var e=self.performance.now();n.stats.buffering.end=e,i&&(i.stats.buffering.end=e);var t=i?i.stats:n.stats;r.checkAppendProgress(n,i,a,s),r.hls&&(r.hls.trigger(Events$2.FRAG_BUFFERED,{frag:n,part:i,stats:t,id:n.type,chunkMeta:a}),!i&&n.gap&&t.retry&&r.log("Nothing buffered for ".concat(n.type," level: ").concat(n.level," sn: ").concat(n.sn," retries ").concat(t.retry)))},s).catch(function(e){r.warn("Fragment buffered callback ".concat(e.message)),r.stepOperationQueue(r.sourceBufferTypes)})}},{key:"onFragChanged",value:function(e,t){var r,n,i=this,a=null==(r=this.hls)?void 0:r.config;if(a){var s=a.backBufferLength,o=a.frontBufferFlushThreshold;this.trimBuffers(o,s,t.frag,t.previousFrag);var l=t.frag.elementaryStreams,u=this.appendErrors,c=null==(n=this.appendError)?void 0:n.sourceBufferName;Object.keys(l).forEach(function(e){l[e]&&(u[e]=0,e===c&&(i.appendError=void 0),"audio"===e||"video"===e?(u.audiovideo=0,"audiovideo"===c&&(i.appendError=void 0)):(u.audio=0,u.video=0,"audiovideo"!==c&&(i.appendError=void 0)))})}}},{key:"bufferedToEnd",get:function(){var e=this;return this.sourceBufferCount>0&&!this.sourceBuffers.some(function(t){var r=_slicedToArray(t,1)[0];if(r){var n=e.tracks[r];if(n)return!n.ended||n.ending}return!1})}},{key:"onBufferEos",value:function(e,t){var r,n=this;this.sourceBuffers.forEach(function(e){var r=_slicedToArray(e,1)[0];if(r){var i=n.tracks[r];t.type&&t.type!==r||(i.ending=!0,i.ended||(i.ended=!0,n.log("".concat(r," buffer reached EOS"))))}});var i=!1!==(null==(r=this.overrides)?void 0:r.endOfStream),a=this.sourceBufferCount>0&&!this.sourceBuffers.some(function(e){var t,r=_slicedToArray(e,1)[0];return r&&!(null!=(t=n.tracks[r])&&t.ended)});a?(this.unblockAudio(),i?(this.log("Queueing EOS"),this.blockUntilOpen(function(){n.tracksEnded();var e=n.mediaSource;"open"===(null==e?void 0:e.readyState)?(n.log("Calling mediaSource.endOfStream()"),e.endOfStream(),n.hls.trigger(Events$2.BUFFERED_TO_END,void 0)):e&&n.log("Could not call mediaSource.endOfStream(). mediaSource.readyState: ".concat(e.readyState))})):(this.tracksEnded(),this.hls.trigger(Events$2.BUFFERED_TO_END,void 0))):"video"===t.type&&this.unblockAudio()}},{key:"tracksEnded",value:function(){var e=this;this.sourceBuffers.forEach(function(t){var r=_slicedToArray(t,1)[0];if(null!==r){var n=e.tracks[r];n&&(n.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===ErrorDetails.BUFFER_APPEND_ERROR&&t.frag){var r,n=null==(r=t.errorAction)?void 0:r.nextAutoLevel;isFiniteNumber(n)&&n!==t.frag.level&&this.resetAppendErrors()}}},{key:"getBackBufferEvictionTarget",value:function(e,t,r){var n=this.media;return n?this.fragmentTracker.getBackBufferEvictionEnd(n.currentTime,r,t):0}},{key:"getFragmentAppendProgress",value:function(e){var t,r=appendProgressKey(e),n=this.fragmentAppendProgress[r];return(null==(t=n)?void 0:t.stats)!==e.stats&&(n={stats:e.stats,progressed:!1,errored:!1,fullyBuffered:Object.create(null)},this.fragmentAppendProgress[r]=n),n}},{key:"checkAppendProgress",value:function(e,t,r,n){if(!(t||!isMediaFragment(e)||e.gap||r.iframe||r.partial)){var i=appendProgressKey(e),a=this.fragmentAppendProgress[i];delete this.fragmentAppendProgress[i];var s=e.stats.buffering;if(!s.start||s.first){var o=(null==a?void 0:a.stats)===e.stats?a:void 0;if(null==o||!o.errored){var l=n.length>0&&n.every(function(e){return!0===(null==o?void 0:o.fullyBuffered[e])});if(null!=o&&o.progressed||l)delete this.appendsWithoutProgress[i];else if(o||0!==n.length){var u=(this.appendsWithoutProgress[i]||0)+1,c=this.hls;u>=c.config.appendErrorMaxRetry?delete this.appendsWithoutProgress[i]:this.appendsWithoutProgress[i]=u,this.warn("Fragment ".concat(e.sn," of ").concat(e.type," playlist ").concat(e.level," appended ").concat(u," time").concat(u>1?"s":""," without buffered range growth")),c.trigger(Events$2.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_APPEND_NO_PROGRESS,fatal:!1,frag:e,chunkMeta:r,parent:e.type,appendsWithoutProgress:u,error:new Error("Fragment append did not increase buffered coverage (".concat(u,")"))})}}}}}},{key:"resetAppendProgress",value:function(){this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null)}},{key:"resetAppendErrors",value:function(){this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0}},{key:"trimBuffers",value:function(e,t,r,n){var i=this.hls,a=this.details,s=this.media;if(s&&null!==a&&this.sourceBufferCount){var o=i.config,l=s.currentTime,u=a.levelTargetDuration;t=a.live&&null!==o.liveBackBufferLength?o.liveBackBufferLength:t;var c=-1/0;if(isFiniteNumber(t)&&t>=0){var d=Math.max(t,u);c=Math.floor(l/u)*u-d}if(r){var h=this.getLoopBackBufferFlushEnd(r,null!=n?n:null);h>0&&(c=Math.max(c,h))}if(c>0&&this.flushBackBuffer(l,u,c),isFiniteNumber(e)&&e>0){var f=Math.max(o.maxBufferLength,e),v=Math.max(f,u),p=Math.floor(l/u)*u+v;this.flushFrontBuffer(l,u,p)}}}},{key:"getLoopBackBufferFlushEnd",value:function(e,t){var r,n=this.media;if(!1===(null==(r=this.hls)?void 0:r.config.loopBackBufferFlush)||null==n||!n.loop||!t||e.level<=t.level)return 0;var i=e.elementaryStreams,a=i.video,s=i.audiovideo;if(null!=a&&a.partial||null!=s&&s.partial)return 0;var o=this.getEarliestElementaryStreamStart(e)-LOOP_FLUSH_SAFETY_MARGIN;return o<=0?0:(this.log("Flushing lower quality back buffer for loop: level ".concat(e.level,", range [0-").concat(o.toFixed(3),"]")),o)}},{key:"getEarliestElementaryStreamStart",value:function(e){var t=e.elementaryStreams,r=t.audio,n=t.video,i=t.audiovideo,a=e.start;return i?a=Math.min(a,i.startDTS):(r&&(a=Math.min(a,r.startDTS)),n&&(a=Math.min(a,n.startDTS))),a}},{key:"flushBackBuffer",value:function(e,t,r){var n=this;this.sourceBuffers.forEach(function(e){var t=_slicedToArray(e,2),i=t[0],a=t[1];if(a){var s=BufferHelper.getBuffered(a);if(s.length>0&&r>s.start(0)){var o,l,u;n.hls.trigger(Events$2.BACK_BUFFER_REACHED,{bufferEnd:r});var c=n.tracks[i];if(null!=(o=n.details)&&o.live)n.hls.trigger(Events$2.LIVE_BACK_BUFFER_REACHED,{bufferEnd:r});else if(null!=c&&c.ended&&(null==(l=n.media)||!l.loop||!1===(null==(u=n.hls)?void 0:u.config.loopBackBufferFlush)))return void n.log("Cannot flush ".concat(i," back buffer while SourceBuffer is in ended state"));n.hls.trigger(Events$2.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:i})}}})}},{key:"flushFrontBuffer",value:function(e,t,r){var n=this;this.sourceBuffers.forEach(function(t){var i=_slicedToArray(t,2),a=i[0],s=i[1];if(s){var o=BufferHelper.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;n.hls.trigger(Events$2.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 n=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&r.setLiveSeekableRange){var i=Math.max(0,t.fragmentStart);return{duration:1/0,start:i,end:Math.max(i,n)}}return{duration:1/0}}var a=null==(e=this.overrides)?void 0:e.duration;if(a)return isFiniteNumber(a)?{duration:a}:null;var s=this.media.duration;return n>(isFiniteNumber(r.duration)?r.duration:0)&&n>s||!isFiniteNumber(s)?{duration:n}:null}},{key:"updateMediaSource",value:function(e){var t=e.duration,r=e.start,n=e.end,i=this.mediaSource;i&&this.media&&"open"===i.readyState&&(i.duration!==t&&(isFiniteNumber(t)&&this.log("Updating MediaSource duration to ".concat(t.toFixed(3))),i.duration=t),void 0!==r&&void 0!==n&&(this.log("MediaSource duration is set to ".concat(i.duration,". Setting seekable range to ").concat(r,"-").concat(n,".")),i.setLiveSeekableRange(r,n)))}},{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(stringify(r))),this.tracksReady){var n,i=null==(n=this.transferData)?void 0:n.tracks;i&&Object.keys(i).length?this.attachTransferred():this.createSourceBuffers()}}},{key:"bufferCreated",value:function(){var e=this;if(this.sourceBufferCount){var t={};this.sourceBuffers.forEach(function(r){var n=_slicedToArray(r,2),i=n[0],a=n[1];if(i){var s=e.tracks[i];t[i]={buffer:a,container:s.container,codec:s.codec,supplemental:s.supplemental,levelCodec:s.levelCodec,id:s.id,metadata:s.metadata}}}),this.hls.trigger(Events$2.BUFFER_CREATED,{tracks:t}),this.log("SourceBuffers created. Running queue: ".concat(this.operationQueue)),this.sourceBuffers.forEach(function(t){var r=_slicedToArray(t,1)[0];e.executeNext(r)})}else{var r=new Error("could not create source buffer for media codec(s)");this.hls.trigger(Events$2.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.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 n in e){var i=n,a=e[i];if(this.isPending(a)){var s=this.getTrackCodec(a,i),o="".concat(a.container,";codecs=").concat(s);a.codec=s,this.log("creating sourceBuffer(".concat(o,")").concat(this.currentOp(i)?" Queued":""," ").concat(stringify(a)));try{var l=r.addSourceBuffer(o),u=sourceBufferNameToIndex(i),c=[i,l];t[u]=c,a.buffer=l}catch(h){var d;return this.error("error while trying to add sourceBuffer: ".concat(h.message)),this.shiftAndExecuteNext(i),null==(d=this.operationQueue)||d.removeBlockers(),delete this.tracks[i],void this.hls.trigger(Events$2.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:h,sourceBufferName:i,mimeType:o,parent:a.id})}this.trackSourceBuffer(i,a)}}this.bufferCreated()}},{key:"clearBufferAppendTimeoutId",value:function(e){e&&(self.clearTimeout(e.bufferAppendTimeoutId),e.bufferAppendTimeoutId=void 0)}},{key:"getTrackCodec",value:function(e,t){var r=e.supplemental,n=e.codec;r&&("video"===t||"audiovideo"===t)&&areCodecsMediaSourceSupported(r,"video")&&(n=replaceVideoCodec(n,r));var i=pickMostCompleteCodecName(n,e.levelCodec);return i?"audio"===t.slice(0,5)?getCodecCompatibleName(i,this.appendSource):i:""}},{key:"trackSourceBuffer",value:function(e,t){var r=this,n=t.buffer;if(n){var i=this.getTrackCodec(t,e);this.tracks[e]={buffer:n,codec:i,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",function(e,t){var n=t.removedRanges;null!=n&&n.length&&(r.log("".concat(e," buffer removed ").concat(timeRangesToString(n))),r.hls.trigger(Events$2.BUFFER_FLUSHED,{type:e,start:n.start(0),end:n.end(n.length-1)}))})}}},{key:"mediaSrc",get:function(){var e,t,r=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==r?void 0:r.src}},{key:"onSBUpdateStart",value:function(e){var t=this.currentOp(e);t&&t.onStart()}},{key:"onSBUpdateEnd",value:function(e){var t,r,n=this;if("closed"!==(null==(t=this.mediaSource)?void 0:t.readyState)){var i=this.currentOp(e);if(i){if(i.onComplete(),null==(r=this.tracks[e])||null==(r=r.buffer)?void 0:r.updating)return this.log("".concat(e,' SourceBuffer updating on "updateend"')),void this.blockUntilOpen(function(){n.shiftAndExecuteNext(e)});this.shiftAndExecuteNext(e)}}else this.resetBuffer(e)}},{key:"onSBUpdateError",value:function(e,t){var r,n=null==(r=this.mediaSource)?void 0:r.readyState,i=new Error("".concat(e," SourceBuffer error. MediaSource readyState: ").concat(n));this.error("".concat(i.message),t),this.hls.trigger(Events$2.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});var a=this.currentOp(e);a&&a.onError(i)}},{key:"updateTimestampOffset",value:function(e,t,r,n,i,a){var s=t-e.timestampOffset;Math.abs(s)>=r&&(this.log("Updating ".concat(n," SourceBuffer timestampOffset to ").concat(t," (sn: ").concat(i," cc: ").concat(a,")")),e.timestampOffset=t)}},{key:"removeExecutor",value:function(e,t,r){var n=this.media,i=this.mediaSource,a=this.tracks[e],s=null==a?void 0:a.buffer;if(!n||!i||!s)throw new Error("Attempting to remove from the ".concat(e," SourceBuffer, but it does not exist"));var o,l=isFiniteNumber(n.duration)?n.duration:1/0,u=isFiniteNumber(i.duration)?i.duration:1/0,c=Math.max(0,t);if(c>=u)return null==(o=this.currentOp(e))||o.onComplete(),void this.shiftAndExecuteNext(e);var d=Math.min(r,l,u);if(!(d>c)||a.ending&&!a.ended)throw new Error("Cannot remove ".concat(d<=c?"invalid range (".concat(c," >= ").concat(d,") "):"","from the ").concat(e," SourceBuffer").concat(a.ending?" while track ending":""));a.ended=!1,this.log("Removing [".concat(c,",").concat(d,"] from the ").concat(e," SourceBuffer")),s.remove(c,d)}},{key:"appendExecutor",value:function(e,t){var r=this,n=this.tracks[t],i=null==n?void 0:n.buffer;if(!i)throw new HlsJsTrackRemovedError("Attempting to append to the ".concat(t," SourceBuffer, but it does not exist"));if(n.ending=!1,n.ended=!1,this.hls.config.appendTimeout!==1/0){var a=this.calculateAppendTimeoutTime(i);n.bufferAppendTimeoutId=self.setTimeout(function(){return r.appendTimeoutHandler(t,i,a)},a)}i.appendBuffer(e)}},{key:"appendTimeoutHandler",value:function(e,t,r){this.log("Received timeout after ".concat(r,"ms for append on ").concat(e," source buffer. Aborting and triggering error."));try{t.abort()}catch(i){this.log("Failed to abort append on ".concat(e," source buffer after timeout."))}var n=this.currentOp(e);n&&n.onError(new Error("".concat(e,"-append-timeout")))}},{key:"calculateAppendTimeoutTime",value:function(e){var t=DEFAULT_TARGET_DURATION;this.details&&(t=this.details.levelTargetDuration);var r=2*t*1e3;if(null===this.media)return r;var n=BufferHelper.bufferInfo(e,this.media.currentTime,0);return n.len?(r=Math.max(1e3*n.len,r),Math.max(this.hls.config.appendTimeout,r)):r}},{key:"blockUntilOpen",value:function(e){var t=this;if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(function(e){t.warn("SourceBuffer blocked callback ".concat(e)),t.stepOperationQueue(t.sourceBufferTypes)});else try{e()}catch(r){this.warn("Callback run without blocking ".concat(this.operationQueue," ").concat(r))}}},{key:"isUpdating",value:function(){return this.sourceBuffers.some(function(e){var t=_slicedToArray(e,2),r=t[0],n=t[1];return r&&n.updating})}},{key:"isQueued",value:function(){var e=this;return this.sourceBuffers.some(function(t){var r=_slicedToArray(t,1)[0];return r&&!!e.currentOp(r)})}},{key:"isPending",value:function(e){return!!e&&!e.buffer}},{key:"isAudioBlocked",value:function(){var e;return"block-audio"===(null==(e=this.currentOp("audio"))?void 0:e.label)}},{key:"isAudioBlocking",value:function(){return!!this.operationQueue&&this.operationQueue.audioBlocking()}},{key:"blockBuffers",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.sourceBufferTypes;if(!r.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);var n=this.operationQueue,i=2===r.length&&this.isAudioBlocking()?[this.appendBlocker("video")]:r.map(function(e){return t.appendBlocker(e)});return Promise.all(i).then(function(r){n===t.operationQueue&&(e(),t.stepOperationQueue(t.sourceBufferTypes))})}},{key:"stepOperationQueue",value:function(e){var t=this;e.forEach(function(e){var r,n=null==(r=t.tracks[e])?void 0:r.buffer;!n||n.updating||"audio"===e&&t.isAudioBlocked()||t.shiftAndExecuteNext(e)})}},{key:"append",value:function(e,t,r){this.operationQueue&&this.operationQueue.append(e,t,r)}},{key:"insertNext",value:function(e,t){this.operationQueue&&this.operationQueue.insertNext(e,t)}},{key:"appendBlocker",value:function(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}},{key:"currentOp",value:function(e){return this.operationQueue?this.operationQueue.current(e):null}},{key:"executeNext",value:function(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}},{key:"shiftAndExecuteNext",value:function(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}},{key:"pendingTrackCount",get:function(){var e=this;return Object.keys(this.tracks).reduce(function(t,r){return t+(e.isPending(e.tracks[r])?1:0)},0)}},{key:"sourceBufferCount",get:function(){return this.sourceBuffers.reduce(function(e,t){return e+(_slicedToArray(t,1)[0]?1:0)},0)}},{key:"sourceBufferTypes",get:function(){return this.sourceBuffers.map(function(e){return _slicedToArray(e,1)[0]}).filter(function(e){return!!e})}},{key:"addBufferListener",value:function(e,t,r){var n=this.tracks[e];if(n){var i=n.buffer;if(i){var a=r.bind(this,e);n.listeners.push({event:t,listener:a}),addEventListener(i,t,a)}}}},{key:"removeBufferListeners",value:function(e){var t=this.tracks[e];if(t){var r=t.buffer;r&&(t.listeners.forEach(function(e){removeEventListener(r,e.event,e.listener)}),t.listeners.length=0)}}}])}();function removeSourceChildren(e){var t=e.querySelectorAll("source");[].slice.call(t).forEach(function(t){e.removeChild(t)})}function addSource(e,t){var r=self.document.createElement("source");r.type="video/mp4",r.src=t,e.appendChild(r)}function sourceBufferNameToIndex(e){return"audio"===e?1:0}function mediaErrorRecoveryMessage(e,t){return"".concat(e?"":" - triggering recovery").concat(t?" with HTMLMediaElement Error: "+t.message:"")}function appendProgressKey(e){return"".concat(e.type,"_").concat(e.sn,"_").concat(e.level)}function fragmentBufferedCoverage(e,t){for(var r=t.start,n=t.end,i=0,a=0;a<e.length;a++){var s=e[a];if(s.start>=n)break;var o=Math.max(r,s.start),l=Math.min(n,s.end);l>o&&(i+=l-o)}return i}function isFragmentFullyBuffered(e,t){return t.duration-e<=.05}var CapLevelController=function(){function e(t){_classCallCheck(this,e),this.hls=null,this.autoLevelCapping=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.observer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.media=null,this.restrictedLevels=[],this.clientRect=null,this.registerListeners()}return _createClass(e,[{key:"setStreamController",value:function(e){this.streamController=e}},{key:"destroy",value:function(){this.hls&&this.unregisterListener(),(this.timer||this.observer)&&this.stopCapping(),this.media=this.clientRect=this.hls=null,this.streamController=void 0}},{key:"registerListeners",value:function(){var e=this.hls;e&&(e.on(Events$2.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(Events$2.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Events$2.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Events$2.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Events$2.BUFFER_CODECS,this.onBufferCodecs,this),e.on(Events$2.MEDIA_DETACHING,this.onMediaDetaching,this))}},{key:"unregisterListener",value:function(){var e=this.hls;e&&(e.off(Events$2.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(Events$2.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Events$2.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Events$2.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Events$2.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Events$2.MEDIA_DETACHING,this.onMediaDetaching,this))}},{key:"onFpsDropLevelCapping",value:function(e,t){if(this.hls){var r=this.hls.levels[t.droppedLevel];this.isLevelAllowed(r)&&this.restrictedLevels.push({bitrate:r.bitrate,height:r.height,width:r.width})}}},{key:"onMediaAttaching",value:function(e,t){var r=t.media;this.clientRect=null,this.hls&&(r instanceof HTMLVideoElement?(this.media=r,this.hls.config.capLevelToPlayerSize&&this.observe()):this.media=null,(this.timer||this.observer)&&this.hls.levels.length>1&&this.detectPlayerSize())}},{key:"onManifestParsed",value:function(e,t){this.restrictedLevels=[],t.video&&this.startCapping(),this.onLevelsUpdated()}},{key:"onLevelsUpdated",value:function(){if(this.hls)if((this.timer||this.observer)&&(isFiniteNumber(this.autoLevelCapping)||this.clientRect))this.detectPlayerSize();else if(void 0===this.observer&&void 0===this.timer){var e=this.hls.levels;e.length>1&&e.some(function(e){return!!e.videoCodec})&&this.startCapping()}}},{key:"onBufferCodecs",value:function(e,t){t.video&&this.startCapping()}},{key:"onMediaDetaching",value:function(){this.stopCapping(),this.media=null}},{key:"detectPlayerSize",value:function(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0||!this.hls)return void(this.clientRect=null);var e=this.hls.levels;if(e.length>1){var t=this.hls,r=this.getMaxLevel(e.length-1);r!==this.autoLevelCapping&&t.logger.log("Setting autoLevelCapping to ".concat(r,": ").concat(e[r].height,"p@").concat(e[r].bitrate," for media ").concat(this.mediaWidth,"x").concat(this.mediaHeight)),t.autoLevelCapping=r,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}else 1===e.length&&this.stopCapping()}}},{key:"getMaxLevel",value:function(t){var r=this;if(!this.hls)return-1;var n=this.hls.levels;if(!n.length)return-1;var i=n.filter(function(e,n){return r.isLevelAllowed(e)&&n<=t});return this.observer||(this.clientRect=null),e.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}},{key:"observe",value:function(){var e=this,t=self.ResizeObserver;t&&(this.observer=new t(function(t){var r,n=null==(r=t[0])?void 0:r.contentRect;n&&(e.clientRect=n,e.detectPlayerSize())})),this.observer&&this.media&&this.observer.observe(this.media)}},{key:"startCapping",value:function(){var e;this.timer||this.observer||null==(e=this.hls)||!e.config.capLevelToPlayerSize||(self.clearInterval(this.timer),this.timer=void 0,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.observe(),this.observer||(this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3)),this.detectPlayerSize())}},{key:"stopCapping",value:function(){this.restrictedLevels=[],this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0),this.observer&&(this.observer.disconnect(),this.observer=void 0)}},{key:"getDimensions",value:function(){if(this.clientRect)return this.clientRect;var e=this.media,t={width:0,height:0};if(e){var r=e.getBoundingClientRect();t.width=r.width,t.height=r.height,t.width||t.height||(t.width=r.right-r.left||e.width||0,t.height=r.bottom-r.top||e.height||0)}return this.clientRect=t,t}},{key:"mediaWidth",get:function(){return this.getDimensions().width*this.contentScaleFactor}},{key:"mediaHeight",get:function(){return this.getDimensions().height*this.contentScaleFactor}},{key:"contentScaleFactor",get:function(){var e=1;if(!this.hls)return e;var t=this.hls.config,r=t.ignoreDevicePixelRatio,n=t.maxDevicePixelRatio;if(!r)try{e=self.devicePixelRatio}catch(i){}return Math.min(e,n)}},{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 n=function(e,t){return!t||(e.width!==t.width||e.height!==t.height)},i=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)&&n(o,e[s+1])){i=s;break}}return i}}])}(),SfItem=_createClass(function e(t,r){_classCallCheck(this,e),Array.isArray(t)&&(t=t.map(function(t){return t instanceof e?t:new e(t)})),this.value=t,this.params=r}),DICT="Dict";function format(e){return Array.isArray(e)?JSON.stringify(e):e instanceof Map?"Map{}":e instanceof Set?"Set{}":"object"===_typeof(e)?JSON.stringify(e):String(e)}function throwError(e,t,r,n){return new Error("failed to ".concat(e,' "').concat(format(t),'" as ').concat(r),{cause:n})}var BARE_ITEM="Bare Item",BOOLEAN="Boolean",BYTES="Byte Sequence",DECIMAL="Decimal",INTEGER="Integer";function isInvalidInt(e){return e<-999999999999999||999999999999999<e}var STRING="String",STRING_REGEX=/[\x00-\x1f\x7f]+/,SfToken=_createClass(function e(t){_classCallCheck(this,e),this.description=t}),TOKEN="Token",KEY="Key";function serializeError(e,t,r){return throwError("serialize",e,t,r)}function serializeBoolean(e){if("boolean"!=typeof e)throw serializeError(e,BOOLEAN);return e?"?1":"?0"}function serializeByteSequence(e){if(!1===ArrayBuffer.isView(e))throw serializeError(e,BYTES);return":".concat(encodeBase64(e),":")}function serializeInteger(e){if(isInvalidInt(e))throw serializeError(e,INTEGER);return e.toString()}function serializeDate(e){return"@".concat(serializeInteger(e.getTime()/1e3))}function serializeDecimal(e){var t=roundToEven(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw serializeError(e,DECIMAL);var r=t.toString();return r.includes(".")?r:"".concat(r,".0")}function serializeString(e){if(STRING_REGEX.test(e))throw serializeError(e,STRING);return'"'.concat(e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),'"')}function symbolToStr(e){return e.description||e.toString().slice(7,-1)}function serializeToken(e){var t=symbolToStr(e);if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t))throw serializeError(t,TOKEN);return t}function serializeBareItem(e){switch(_typeof(e)){case"number":if(!isFiniteNumber(e))throw serializeError(e,BARE_ITEM);return Number.isInteger(e)?serializeInteger(e):serializeDecimal(e);case"string":return serializeString(e);case"symbol":return serializeToken(e);case"boolean":return serializeBoolean(e);case"object":if(e instanceof Date)return serializeDate(e);if(e instanceof Uint8Array)return serializeByteSequence(e);if(e instanceof SfToken)return serializeToken(e);default:throw serializeError(e,BARE_ITEM)}}function serializeKey(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw serializeError(e,KEY);return e}function serializeParams(e){return null==e?"":Object.entries(e).map(function(e){var t=_slicedToArray(e,2),r=t[0],n=t[1];return!0===n?";".concat(serializeKey(r)):";".concat(serializeKey(r),"=").concat(serializeBareItem(n))}).join("")}function serializeItem(e){return e instanceof SfItem?"".concat(serializeBareItem(e.value)).concat(serializeParams(e.params)):serializeBareItem(e)}function serializeInnerList(e){return"(".concat(e.value.map(serializeItem).join(" "),")").concat(serializeParams(e.params))}function serializeDict(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{whitespace:!0};if("object"!==_typeof(e)||null==e)throw serializeError(e,DICT);var r=e instanceof Map?e.entries():Object.entries(e),n=null!=t&&t.whitespace?" ":"";return Array.from(r).map(function(e){var t=_slicedToArray(e,2),r=t[0],n=t[1];n instanceof SfItem==!1&&(n=new SfItem(n));var i=serializeKey(r);return!0===n.value?i+=serializeParams(n.params):(i+="=",Array.isArray(n.value)?i+=serializeInnerList(n):i+=serializeItem(n)),i}).join(",".concat(n))}function encodeSfDict(e,t){return serializeDict(e,t)}var _excluded$1=["url"],_excluded2=["version","eventTargets","sid","transmissionMode"],_excluded3=["customData","headers"],roundValue=function(e){return e instanceof SfItem?new SfItem(Math.round(e.value),e.params):Math.round(e)},toRounded=function(e){return Array.isArray(e)?e.map(roundValue):roundValue(e)},_toUrlSafe=function(e,t){return Array.isArray(e)?e.map(function(e){return _toUrlSafe(e,t)}):e instanceof SfItem&&"string"==typeof e.value?new SfItem(_toUrlSafe(e.value,t),e.params):(t.baseUrl&&(e=urlToRelativePath(e,getBaseUrl(t.baseUrl))),1===t.version?encodeURIComponent(e):e)},hundredValue=function(e){return e instanceof SfItem?new SfItem(100*Math.round(e.value/100),e.params):100*Math.round(e/100)},toHundred=function(e){return Array.isArray(e)?e.map(hundredValue):hundredValue(e)},nor=function(e,t){var r=e;return t.version>=2&&(e instanceof SfItem&&"string"==typeof e.value?r=new SfItem([e]):"string"==typeof e&&(r=[e])),_toUrlSafe(r,t)},CMCD_FORMATTER_MAP={br:toRounded,d:toRounded,bl:toHundred,dl:toHundred,mtp:toHundred,nor:nor,rtp:toHundred,tb:toRounded},CMCD_V2=2,CMCD_EVENT_BITRATE_CHANGE="bc",CMCD_EVENT_PLAY_STATE="ps",CMCD_EVENT_PLAYBACK_RATE="pr",CMCD_EVENT_ERROR="e",CMCD_EVENT_TIME_INTERVAL="t",CMCD_EVENT_CONTENT_ID="c",CMCD_EVENT_BACKGROUNDED_MODE="b",CMCD_EVENT_RESPONSE_RECEIVED="rr",CMCD_EVENT_CUSTOM_EVENT="ce",CmcdEventType={BITRATE_CHANGE:CMCD_EVENT_BITRATE_CHANGE,ERROR:CMCD_EVENT_ERROR,RESPONSE_RECEIVED:CMCD_EVENT_RESPONSE_RECEIVED,CUSTOM_EVENT:CMCD_EVENT_CUSTOM_EVENT},CMCD_STATE_EVENT_FIELDS=new Map([[CMCD_EVENT_PLAY_STATE,"sta"],[CMCD_EVENT_PLAYBACK_RATE,"pr"],[CMCD_EVENT_CONTENT_ID,"cid"],[CMCD_EVENT_BACKGROUNDED_MODE,"bg"],[CMCD_EVENT_BITRATE_CHANGE,"br"]]),CMCD_EVENT_MODE="event",CMCD_REQUEST_MODE="request",CMCD_EVENT_KEYS=["cen","e","h","ts"],CMCD_REQUEST_KEYS=["ab","bg","bl","br","bs","bsa","bsd","bsda","cdn","cid","cs","d","dfa","dl","ec","lab","lb","ltc","msd","mtp","nor","nr","ot","pb","pr","pt","rtp","sf","sid","sn","st","sta","su","tab","tb","tbl","tpb","v"],CUSTOM_KEY_REGEX=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function isCmcdCustomKey(e){return CUSTOM_KEY_REGEX.test(e)}var CMCD_REQUEST_KEY_SET=new Set(CMCD_REQUEST_KEYS);function isCmcdRequestKey(e){return CMCD_REQUEST_KEY_SET.has(e)||isCmcdCustomKey(e)}var CMCD_RESPONSE_KEYS=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],CMCD_RESPONSE_KEY_SET=new Set(CMCD_RESPONSE_KEYS);function isCmcdResponseReceivedKey(e){return CMCD_RESPONSE_KEY_SET.has(e)}var CMCD_EVENT_KEY_SET=new Set(CMCD_EVENT_KEYS);function isCmcdEventKey(e){return isCmcdRequestKey(e)||isCmcdResponseReceivedKey(e)||CMCD_EVENT_KEY_SET.has(e)}var CMCD_INNER_LIST_KEYS=new Set(["ab","bl","br","bsa","bsd","bsda","lab","lb","mtp","pb","tab","tb","tbl","tpb"]),CMCD_V1_KEYS=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"],CMCD_V1_KEY_SET$1=new Set(CMCD_V1_KEYS);function isCmcdV1Key(e){return CMCD_V1_KEY_SET$1.has(e)||isCmcdCustomKey(e)}var TOKEN_FIELDS=new Set(["ot","sf","st","e","sta"]);function isTokenField(e){return TOKEN_FIELDS.has(e)}function isValid(e){return"number"==typeof e?isFiniteNumber(e):null!=e&&""!==e&&!1!==e}var filterMap=_defineProperty$1(_defineProperty$1({},CMCD_EVENT_MODE,isCmcdEventKey),CMCD_REQUEST_MODE,isCmcdRequestKey);function unwrapValue(e,t){var r;return Array.isArray(e)?(t&&(r=e.find(function(e){var r;return(null==(r=e.params)?void 0:r.ot)===t})),r||(r=e[0]),unwrapValue(r)):e instanceof SfItem?e.value:e}function downConvertToV1(e){for(var t={},r=0,n=Object.entries(e);r<n.length;r++){var i=_slicedToArray(n[r],2),a=i[0],s=i[1];if(null!=s)if("nor"===a){var o,l=(Array.isArray(s)?s:[s])[0];if(l instanceof SfItem)t.nor=l.value,null!=(o=l.params)&&o.r&&(t.nrr=l.params.r);else t.nor=l}else CMCD_INNER_LIST_KEYS.has(a)?t[a]=unwrapValue(s,e.ot):t[a]=s;else t[a]=s}return t}function prepareCmcdData(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r={};if(null==e||"object"!==_typeof(e))return r;var n=t.version||e.v||CMCD_V2,i=t.reportingMode||CMCD_REQUEST_MODE,a=1===n?downConvertToV1(e):e,s=1===n?isCmcdV1Key:filterMap[i],o=Object.keys(a).filter(s);a.e&&a.e!==CMCD_EVENT_RESPONSE_RECEIVED&&(o=o.filter(function(e){return!isCmcdResponseReceivedKey(e)}));var l=t.filter;"function"==typeof l&&(o=o.filter(l));var u=i===CMCD_EVENT_MODE;if(u){var c=a.e;o.includes("e")||null==c||o.push("e"),o.includes("ts")||o.push("ts"),o.includes("cen")||null==a.cen||c!==CMCD_EVENT_CUSTOM_EVENT||o.push("cen");var d=c?CMCD_STATE_EVENT_FIELDS.get(c):void 0;d&&null!=a[d]&&!o.includes(d)&&o.push(d)}if(0===o.length)return r;n>1&&!o.includes("v")&&o.push("v");var h={version:n,reportingMode:i,baseUrl:t.baseUrl};o.sort();var f,v=_createForOfIteratorHelper(o);try{for(v.s();!(f=v.n()).done;){var p,g,y=f.value,m=a[y],E=null!=(p=null==(g=t.formatters)?void 0:g[y])?p:CMCD_FORMATTER_MAP[y];if("function"==typeof E&&(m=E(m,h)),"v"===y){if(1===n)continue;m=n}if("pr"!==y||1!==m||u&&a.e===CMCD_EVENT_PLAYBACK_RATE){u&&"ts"===y&&!isFiniteNumber(m)&&(m=Date.now());var S=u&&!1===m&&"bg"===y&&a.e===CMCD_EVENT_BACKGROUNDED_MODE;(isValid(m)||S)&&(isTokenField(y)&&"string"==typeof m&&(m=new SfToken(m)),r[y]=m)}}}catch(err){v.e(err)}finally{v.f()}return r}var CMCD_OBJECT="CMCD-Object",CMCD_REQUEST="CMCD-Request",CMCD_SESSION="CMCD-Session",CMCD_STATUS="CMCD-Status",CmcdHeaderField={REQUEST:CMCD_REQUEST},CMCD_HEADER_MAP={ab:CMCD_OBJECT,br:CMCD_OBJECT,d:CMCD_OBJECT,lab:CMCD_OBJECT,lb:CMCD_OBJECT,ot:CMCD_OBJECT,tab:CMCD_OBJECT,tb:CMCD_OBJECT,tpb:CMCD_OBJECT,bl:CMCD_REQUEST,cs:CMCD_REQUEST,dfa:CMCD_REQUEST,dl:CMCD_REQUEST,ltc:CMCD_REQUEST,mtp:CMCD_REQUEST,nor:CMCD_REQUEST,nrr:CMCD_REQUEST,pb:CMCD_REQUEST,sn:CMCD_REQUEST,sta:CMCD_REQUEST,su:CMCD_REQUEST,tbl:CMCD_REQUEST,cid:CMCD_SESSION,msd:CMCD_SESSION,sf:CMCD_SESSION,sid:CMCD_SESSION,st:CMCD_SESSION,v:CMCD_SESSION,bg:CMCD_STATUS,bs:CMCD_STATUS,bsa:CMCD_STATUS,bsd:CMCD_STATUS,bsda:CMCD_STATUS,cdn:CMCD_STATUS,ec:CMCD_STATUS,nr:CMCD_STATUS,pr:CMCD_STATUS,pt:CMCD_STATUS,rtp:CMCD_STATUS};function createHeaderMap(e){return Object.keys(e).reduce(function(t,r){var n;return null==(n=e[r])||n.forEach(function(e){return t[e]=r}),t},{})}function groupCmcdHeaders(e,t){var r={};if(!e)return r;for(var n=Object.keys(e),i=t?createHeaderMap(t):{},a=0,s=n;a<s.length;a++){var o,l=s[a],u=CMCD_HEADER_MAP[l]||i[l]||CmcdHeaderField.REQUEST;(null!=(o=r[u])?o:r[u]={})[l]=e[l]}return r}function toPreparedCmcdHeaders(e,t){for(var r={},n=groupCmcdHeaders(e,t),i=0,a=Object.entries(n);i<a.length;i++){var s=_slicedToArray(a[i],2),o=s[0],l=encodeSfDict(s[1],{whitespace:!1});l&&(r[o]=l)}return r}var CMCD_PARAM="CMCD";function encodePreparedCmcd(e){return encodeSfDict(e,{whitespace:!1})}function encodeCmcd(e){return e?encodePreparedCmcd(prepareCmcdData(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})):""}var CMCD_DEFAULT_TIME_INTERVAL=30,CMCD_KEYS=[].concat(CMCD_V1_KEYS,CMCD_REQUEST_KEYS,CMCD_RESPONSE_KEYS,CMCD_EVENT_KEYS).filter(function(e,t,r){return r.indexOf(e)===t}),CMCD_MIME_TYPE="application/cmcd",CMCD_V1=1,CmcdObjectType={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},CmcdPlayerState={STARTING:"s",PLAYING:"p",SEEKING:"k",REBUFFERING:"r",PAUSED:"a",ENDED:"e",FATAL_ERROR:"f",PRELOADING:"d"},CMCD_QUERY="query",CMCD_HEADERS="headers";function createEncodingOptions(e,t,r){var n,i=new Set(null!=(n=t.enabledKeys)?n:[]);return{version:t.version||CMCD_V2,reportingMode:e,filter:function(e){return i.has(e)},baseUrl:r}}function cmcdObjectTypeListEqual(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(var r=0;r<e.length;r++){var n=e[r],i=t[r];if(n!==i){if("number"==typeof n||"number"==typeof i)return!1;if(n.value!==i.value)return!1;var a=n.params,s=i.params,o=a&&Object.keys(a)[0],l=s&&Object.keys(s)[0];if(o!==l)return!1;if(void 0!==o&&void 0!==l&&a&&s&&a[o]!==s[l])return!1}}return!0}var equal=Object.is,identity=function(e){return e},STATE_FIELDS=Array.from(CMCD_STATE_EVENT_FIELDS,function(e){var t=_slicedToArray(e,2),r=t[0],n=t[1];return"br"===n?{event:r,field:n,equal:function(e,t){return void 0===e||void 0===t?e===t:cmcdObjectTypeListEqual(e,t)},snapshot:function(e){return e.slice()}}:{event:r,field:n,equal:equal,snapshot:identity}}),STATE_FIELDS_BY_EVENT=new Map(STATE_FIELDS.map(function(e){return[e.event,e]}));function defaultRequester(e){var t=e.url,r=_objectWithoutProperties(e,_excluded$1);return fetch(t,r)}function createCmcdReporterConfig(e){var t=e.version,r=void 0===t?CMCD_V2:t,n=e.eventTargets,i=void 0===n?[]:n,a=e.sid,s=void 0===a?uuid():a,o=e.transmissionMode,l=void 0===o?CMCD_QUERY:o;return _objectSpread2(_objectSpread2({},_objectWithoutProperties(e,_excluded2)),{},{version:r,transmissionMode:l,sid:s,eventTargets:i.reduce(function(e,t){var r,n,i;return null!=t&&t.url&&null!=(r=t.events)&&r.length&&e.push({version:t.version||CMCD_V2,enabledKeys:(null==(n=t.enabledKeys)?void 0:n.slice())||[],url:t.url,events:t.events.slice(),interval:null!=(i=t.interval)?i:CMCD_DEFAULT_TIME_INTERVAL,batchSize:t.batchSize||1}),e},[])})}var CmcdReporter=function(){return _createClass(function e(t){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:defaultRequester;_classCallCheck(this,e),this.timeOrigin=performance.timeOrigin||(null==(r=performance.timing)?void 0:r.fetchStart)||Date.now()-performance.now(),this.data={},this.msd=NaN,this.eventTargets=new Map,this.lastEmitted={},this.requestTarget={sn:0,msdSent:!1},this.config=createCmcdReporterConfig(t),this.data={cid:this.config.cid,sid:this.config.sid,v:this.config.version},this.requester=n;var i,a=_createForOfIteratorHelper(this.config.eventTargets);try{for(a.s();!(i=a.n()).done;){var s=i.value;this.eventTargets.set(s,{intervalId:void 0,sn:0,msdSent:!1,queue:[]})}}catch(err){a.e(err)}finally{a.f()}},[{key:"start",value:function(){var e=this;this.eventTargets.forEach(function(t,r){if(e.disarmInterval(t),0!==r.interval&&r.events.includes(CMCD_EVENT_TIME_INTERVAL)){var n=function(){e.recordTargetEvent(t,r,CMCD_EVENT_TIME_INTERVAL),e.processEventTargets()};t.intervalId=setInterval(n,1e3*r.interval),n()}})}},{key:"stop",value:function(){var e=this;arguments.length>0&&void 0!==arguments[0]&&arguments[0]&&this.flush(),this.eventTargets.forEach(function(t){e.disarmInterval(t)})}},{key:"flush",value:function(){this.processEventTargets(!0)}},{key:"update",value:function(e){e.sid&&e.sid!==this.data.sid&&this.resetSession(),e.msd&&!isNaN(e.msd)&&(this.msd=e.msd),this.data=_objectSpread2(_objectSpread2(_objectSpread2({},this.data),e),{},{msd:void 0});for(var t=0,r=STATE_FIELDS;t<r.length;t++){var n=r[t];n.field in e&&!n.equal(this.data[n.field],this.lastEmitted[n.field])&&this.recordEvent(n.event)}}},{key:"recordEvent",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=STATE_FIELDS_BY_EVENT.get(e);if(n){var i=n.field,a=r[i];void 0!==a&&_extends(this.data,_defineProperty$1({},i,a));var s=this.data[i];if(void 0===s)return;if(n.equal(s,this.lastEmitted[i]))return;_extends(this.lastEmitted,_defineProperty$1({},i,n.snapshot(s)))}this.eventTargets.forEach(function(n,i){t.recordTargetEvent(n,i,e,r)}),this.processEventTargets()}},{key:"recordTargetEvent",value:function(e,t,r){var n,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};if(t.events.includes(r)){var a=_objectSpread2(_objectSpread2(_objectSpread2({},this.data),i),{},{e:r,ts:null!=(n=i.ts)?n:Date.now(),sn:e.sn++});isNaN(this.msd)||e.msdSent||(a.msd=this.msd,e.msdSent=!0),e.queue.push(a)}}},{key:"recordResponseReceived",value:function(e){var t,r,n,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=e.request,s=null!=(t=i.url)?t:null==a?void 0:a.url;if(s){var o=new URL(s);o.searchParams.delete(CMCD_PARAM);var l={url:o.toString(),rc:e.status},u=e.resourceTiming;u&&(null!=u.startTime&&(l.ts=Math.round(this.timeOrigin+u.startTime),null!=u.responseStart&&(l.ttfb=Math.round(u.responseStart-u.startTime))),null!=u.duration&&(l.ttlb=Math.round(u.duration)));var c=null!=(r=null==(n=a.customData)?void 0:n.cmcd)?r:{};this.recordEvent(CMCD_EVENT_RESPONSE_RECEIVED,_objectSpread2(_objectSpread2(_objectSpread2({},c),l),i))}}},{key:"applyRequestReport",value:function(e){var t;return null!=(t=this.createRequestReport(e))?t:e}},{key:"isRequestReportingEnabled",value:function(){var e;return!(null==(e=this.config.enabledKeys)||!e.length)}},{key:"createRequestReport",value:function(e,t){var r,n=e.customData,i=void 0===n?{}:n,a=e.headers,s=void 0===a?{}:a,o=_objectSpread2(_objectSpread2({},_objectWithoutProperties(e,_excluded3)),{},{headers:_objectSpread2({},s),customData:_objectSpread2(_objectSpread2({},i),{},{cmcd:{}})});if(null==(r=this.config.enabledKeys)||!r.length||!o.url)return o;var l=new URL(o.url),u=_objectSpread2(_objectSpread2(_objectSpread2({},this.data),t),{},{sn:this.requestTarget.sn++}),c=createEncodingOptions(CMCD_REQUEST_MODE,this.config,o.url);isNaN(this.msd)||this.requestTarget.msdSent||(u.msd=this.msd,this.requestTarget.msdSent=!0);var d=o.customData.cmcd=prepareCmcdData(u,c);switch(this.config.transmissionMode){case CMCD_QUERY:var h=encodePreparedCmcd(d);h&&(l.searchParams.set(CMCD_PARAM,h),o.url=l.toString());break;case CMCD_HEADERS:_extends(o.headers,toPreparedCmcdHeaders(d,c.customHeaderMap))}return o}},{key:"processEventTargets",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],r=!1;this.eventTargets.forEach(function(n,i){var a=n.queue;if(a.length&&(!(a.length<i.batchSize)||t)){var s=t?a.length:i.batchSize,o=a.splice(0,s);e.sendEventReport(i,o).catch(function(){var e;(e=n.queue).unshift.apply(e,_toConsumableArray(o))}),r||(r=a.length>0)}}),r&&this.processEventTargets()}},{key:"sendEventReport",value:(e=_asyncToGenerator(_regenerator().m(function e(t,r){var n,i,a;return _regenerator().w(function(e){for(;;)switch(e.n){case 0:return n=createEncodingOptions(CMCD_EVENT_MODE,t),e.n=1,this.requester({url:t.url,method:"POST",headers:{"Content-Type":CMCD_MIME_TYPE},body:r.map(function(e){return encodeCmcd(e,n)}).join("\n")+"\n"});case 1:if(i=e.v,410!==(a=i.status)){e.n=2;break}this.disposeEventTarget(t),e.n=3;break;case 2:if(!(429===a||a>499&&a<600)){e.n=3;break}throw new Error("Event report failed with status ".concat(a));case 3:return e.a(2)}},e,this)})),function(t,r){return e.apply(this,arguments)})},{key:"disarmInterval",value:function(e){clearInterval(e.intervalId),e.intervalId=void 0}},{key:"disposeEventTarget",value:function(e){var t=this.eventTargets.get(e);t&&(this.disarmInterval(t),this.eventTargets.delete(e))}},{key:"resetSession",value:function(){this.eventTargets.forEach(function(e){return e.sn=0}),this.requestTarget.sn=0,this.lastEmitted={}}}]);var e}(),CmcdStreamingFormat={HLS:"h"},CmcdStreamType={VOD:"v",LIVE:"l",LOW_LATENCY:"ll"};function toCmcdValue(e,t){return new SfItem(e,t)}new Set(CMCD_V1_KEYS),new Set(CMCD_KEYS);var _excluded=["includeKeys"];function validateCmcdCustomData(e){return Object.keys(e).every(isCmcdCustomKey)}var CMCDController=function(){return _createClass(function e(t){var r=this;_classCallCheck(this,e),this.hls=void 0,this.config=void 0,this.media=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.playerState=void 0,this.reporter=void 0,this.playheadLevel=void 0,this.onWaiting=function(){r.initialized&&(r.starved=!0,r.setPlayerState(CmcdPlayerState.REBUFFERING)),r.buffering=!0},this.onPlay=function(){r.initialized||r.setPlayerState(CmcdPlayerState.STARTING)},this.onPlaying=function(){r.initialized||(r.initialized=!0),r.buffering=!1,r.setPlayerState(CmcdPlayerState.PLAYING)},this.onPause=function(){r.media&&!r.media.ended&&r.setPlayerState(CmcdPlayerState.PAUSED)},this.onSeeking=function(){r.initialized&&r.setPlayerState(CmcdPlayerState.SEEKING)},this.onSeeked=function(){var e;r.initialized&&null!=(e=r.media)&&e.paused&&r.setPlayerState(CmcdPlayerState.PAUSED)},this.onRateChange=function(){r.reporter&&r.media&&r.reporter.update({pr:r.media.playbackRate})},this.applyPlaylistData=function(e){try{r.apply(e,{ot:CmcdObjectType.MANIFEST,su:!r.initialized})}catch(t){r.hls.logger.warn("Could not generate manifest CMCD data.",t)}},this.applyFragmentData=function(e){try{var t=e.frag,n=e.part,i=r.hls.levels[t.level],a=r.getObjectType(t,i),s={d:1e3*(n||t).duration,ot:a};if(a===CmcdObjectType.VIDEO||a===CmcdObjectType.AUDIO||a===CmcdObjectType.MUXED||null==a&&("main"===t.type||"audio"===t.type)){var o,l=i.bitrate/1e3;s.br=[l];var u=r.config.cmcd,c=null!=(o=null==u?void 0:u.rtpSafetyFactor)?o:5;if(s.rtp=100*Math.round(l*c/100),a===CmcdObjectType.MUXED||null==a&&"main"===t.type){var d=r.getTopBandwidth()/1e3;isFiniteNumber(d)&&(s.tb=[d]);var h=r.getLowestBandwidth()/1e3;isFiniteNumber(h)&&(s.lb=[h])}var f=r.getBufferLength(t);if(isFiniteNumber(f)){var v;s.bl=[f];var p=(null==(v=r.media)?void 0:v.playbackRate)||1;s.dl=100*Math.round(f/p/100)}r.playheadLevel&&(s.pb=[r.playheadLevel.bitrate/1e3]);var g=r.hls.maxAutoLevel;if(g>=0){var y=r.hls.levels[g];y&&(s.tpb=[y.bitrate/1e3])}}var m=n?r.getNextPart(n):r.getNextFrag(t);null!=m&&m.url&&m.url!==t.url&&(m.byteRange.length>0?s.nor=[toCmcdValue(m.url,{r:"".concat(m.byteRange[0],"-").concat(m.byteRange[1])})]:s.nor=[m.url]),r.apply(e,s)}catch(E){r.hls.logger.warn("Could not generate segment CMCD data.",E)}},this.recordFragmentResponse=function(e,t,n){var i,a=r.config.cmcd,s=null==a||null==(i=a.eventTargets)?void 0:i.some(function(e){var t;return null==(t=e.events)?void 0:t.includes(CmcdEventType.RESPONSE_RECEIVED)});if(r.reporter&&n.loading.first>0&&s)try{r.reporter.recordResponseReceived({request:{url:e},status:t.code,resourceTiming:{startTime:n.loading.start,responseStart:n.loading.first,duration:n.loading.end-n.loading.start,encodedBodySize:n.total}})}catch(o){r.hls.logger.warn("Could not record fragment response CMCD data.",o)}},this.hls=t;var n=this.config=t.config;null!=n.cmcd&&(n.pLoader=this.createPlaylistLoader(),n.fLoader=this.createFragmentLoader(),this.registerListeners())},[{key:"createReporter",value:function(){var e,t,r=this.config.cmcd;if(null!=r){var n=r.version||CMCD_V1;if(this.reporter=new CmcdReporter({sid:r.sessionId||this.hls.sessionId,cid:r.contentId,version:n,transmissionMode:!0===r.useHeaders?CMCD_HEADERS:CMCD_QUERY,enabledKeys:null!=(e=r.includeKeys)?e:_toConsumableArray(n>=CMCD_V2?CMCD_KEYS:CMCD_V1_KEYS),eventTargets:(null!=(t=r.eventTargets)?t:[]).map(function(e){var t=e.includeKeys;return _objectSpread2(_objectSpread2({},_objectWithoutProperties(e,_excluded)),{},{enabledKeys:null!=t?t:CMCD_KEYS})})},r.loader),this.reporter.update({sf:CmcdStreamingFormat.HLS,sta:this.playerState}),r.reporterCallback){var i=this.reporter,a={updateCustomData:function(e){validateCmcdCustomData(e)&&i.update(e)},recordCustomEvent:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};validateCmcdCustomData(t)&&i.recordEvent(CmcdEventType.CUSTOM_EVENT,_objectSpread2({cen:e},t))}};r.reporterCallback(a)}this.reporter.start()}}},{key:"registerListeners",value:function(){var e=this.hls;e.on(Events$2.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events$2.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Events$2.MEDIA_DETACHED,this.onMediaDetached,this),e.on(Events$2.MEDIA_ENDED,this.onMediaEnded,this),e.on(Events$2.ERROR,this.onError,this),e.on(Events$2.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Events$2.LEVEL_SWITCHED,this.onLevelSwitched,this),e.on(Events$2.BUFFER_APPENDED,this.onBufferInfoChange,this),e.on(Events$2.BUFFER_FLUSHED,this.onBufferInfoChange,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(Events$2.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events$2.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Events$2.MEDIA_DETACHED,this.onMediaDetached,this),e.off(Events$2.MEDIA_ENDED,this.onMediaEnded,this),e.off(Events$2.ERROR,this.onError,this),e.off(Events$2.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Events$2.LEVEL_SWITCHED,this.onLevelSwitched,this),e.off(Events$2.BUFFER_APPENDED,this.onBufferInfoChange,this),e.off(Events$2.BUFFER_FLUSHED,this.onBufferInfoChange,this)}},{key:"destroy",value:function(){this.unregisterListeners(),this.onMediaDetached(),this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.hls=this.config=null,this.onWaiting=this.onPlay=this.onPlaying=this.onPause=null,this.onSeeking=this.onSeeked=this.onRateChange=this.media=null}},{key:"onMediaAttaching",value:function(e,t){var r=this.media=t.media;this.setPlayerState(this.media.autoplay?CmcdPlayerState.STARTING:CmcdPlayerState.PRELOADING),addEventListener(r,"waiting",this.onWaiting),addEventListener(r,"play",this.onPlay),addEventListener(r,"playing",this.onPlaying),addEventListener(r,"pause",this.onPause),addEventListener(r,"seeking",this.onSeeking),addEventListener(r,"seeked",this.onSeeked),addEventListener(r,"ratechange",this.onRateChange)}},{key:"onMediaDetached",value:function(){var e=this.media;e&&(removeEventListener(e,"waiting",this.onWaiting),removeEventListener(e,"play",this.onPlay),removeEventListener(e,"playing",this.onPlaying),removeEventListener(e,"pause",this.onPause),removeEventListener(e,"seeking",this.onSeeking),removeEventListener(e,"seeked",this.onSeeked),removeEventListener(e,"ratechange",this.onRateChange),this.media=null)}},{key:"onMediaEnded",value:function(e,t){this.setPlayerState(CmcdPlayerState.ENDED)}},{key:"onManifestLoading",value:function(e,t){this.initialized=!1,this.starved=!1,this.buffering=!0,this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.createReporter(),this.media||this.setPlayerState(CmcdPlayerState.PRELOADING)}},{key:"onError",value:function(e,t){t.fatal&&(this.setPlayerState(CmcdPlayerState.FATAL_ERROR),this.reporter&&this.reporter.recordEvent(CmcdEventType.ERROR,{ec:[t.details]}))}},{key:"onLevelSwitching",value:function(e,t){var r;if(this.reporter){var n={br:[t.bitrate/1e3]},i=null==(r=t.details)?void 0:r.fragments[0];i&&(n.ot=this.getObjectType(i,t)),this.reporter.recordEvent(CmcdEventType.BITRATE_CHANGE,n)}}},{key:"onLevelSwitched",value:function(e,t){var r=this.hls.levels[t.level];r&&(this.playheadLevel=r)}},{key:"setPlayerState",value:function(e){this.playerState=e,this.reporter&&this.reporter.update({sta:e})}},{key:"getStreamType",value:function(){var e=this.hls.latestLevelDetails;if(e)return e.live?e.partList&&e.canBlockReload?CmcdStreamType.LOW_LATENCY:CmcdStreamType.LIVE:CmcdStreamType.VOD}},{key:"apply",value:function(e){var t,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.reporter){this.reporter.update({mtp:[this.hls.bandwidthEstimate/1e3],pr:null==(t=this.media)?void 0:t.playbackRate,st:this.getStreamType()});var n=r.ot===CmcdObjectType.INIT||r.ot===CmcdObjectType.VIDEO||r.ot===CmcdObjectType.MUXED;this.starved&&n&&(r.bs=!0,r.su=!0,this.starved=!1),null==r.su&&(r.su=this.buffering);var i=this.reporter.createRequestReport({url:e.url,headers:e.headers},r);e.url=i.url,e.headers=i.headers}}},{key:"getNextFrag",value:function(e){var t,r=null==(t=this.hls.levels[e.level])?void 0:t.details;if(r){var n=e.sn-r.startSN;return r.fragments[n+1]}}},{key:"getNextPart",value:function(e){var t,r=e.index,n=e.fragment,i=null==(t=this.hls.levels[n.level])||null==(t=t.details)?void 0:t.partList;if(i)for(var a=n.sn,s=i.length-1;s>=0;s--){var o=i[s];if(o.index===r&&o.fragment.sn===a)return i[s+1]}}},{key:"getObjectType",value:function(e,t){var r=e.type;if("subtitle"===r)return CmcdObjectType.TIMED_TEXT;if("initSegment"===e.sn)return CmcdObjectType.INIT;if("audio"===r)return CmcdObjectType.AUDIO;if("main"===r){if(e.hasStreams){var n=e.elementaryStreams;if(n.audiovideo)return CmcdObjectType.MUXED;if(n.video)return CmcdObjectType.VIDEO;if(n.audio)return CmcdObjectType.AUDIO}if(t){var i=t.audioCodec,a=t.videoCodec;if(!this.hls.audioTracks.length){if(i&&a)return CmcdObjectType.MUXED;if(i)return CmcdObjectType.AUDIO}if(a)return CmcdObjectType.VIDEO}}}},{key:"getTopBandwidth",value:function(){var e=0,t=this.hls,r=t.maxAutoLevel,n=r>-1?r+1:t.levels.length;return t.levels.slice(0,n).forEach(function(t){t.bitrate>e&&(e=t.bitrate)}),e>0?e:NaN}},{key:"getLowestBandwidth",value:function(){var e=1/0,t=this.hls,r=t.maxAutoLevel,n=r>-1?r+1:t.levels.length;return t.levels.slice(0,n).forEach(function(t){t.bitrate<e&&(e=t.bitrate)}),isFiniteNumber(e)?e:NaN}},{key:"getBufferLength",value:function(e){if(!this.media)return NaN;var t="audio"===e.type?this.hls.audioForwardBufferInfo:this.hls.mainForwardBufferInfo;return t?1e3*t.len:NaN}},{key:"getEventBufferLength",value:function(){if(!this.media)return NaN;var e=this.hls.mainForwardBufferInfo,t=this.hls.audioForwardBufferInfo;if(e&&t)return 1e3*Math.min(e.len,t.len);var r=e||t;return r?1e3*r.len:NaN}},{key:"onBufferInfoChange",value:function(e,t){if(this.reporter){var r=this.getEventBufferLength();isFiniteNumber(r)&&this.reporter.update({bl:[r]})}}},{key:"createPlaylistLoader",value:function(){var e=this.config.pLoader,t=this.applyPlaylistData,r=e||this.config.loader;return function(){return _createClass(function e(t){_classCallCheck(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,n){t(e),this.loader.load(e,r,n)}}])}()}},{key:"createFragmentLoader",value:function(){var e=this.config.fLoader,t=this.applyFragmentData,r=this.recordFragmentResponse,n=e||this.config.loader;return function(){return _createClass(function e(t){_classCallCheck(this,e),this.loader=void 0,this.loader=new n(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,n,i){t(e);var a=i.onSuccess;this.loader.load(e,n,_objectSpread2(_objectSpread2({},i),{},{onSuccess:function(t,n,i,s){a(t,n,i,s),r(e.url,t,n)}}))}}])}()}}])}(),PATHWAY_PENALTY_DURATION_MS=3e5,ContentSteeringController=function(){function e(t){var r;return _classCallCheck(this,e),(r=_callSuper(this,e,["content-steering",t.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=t,r.registerListeners(),r}return _inherits(e,Logger$1),_createClass(e,[{key:"registerListeners",value:function(){var e=this.hls;e.on(Events$2.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events$2.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Events$2.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Events$2.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(Events$2.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events$2.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Events$2.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Events$2.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)===NetworkErrorAction.SendAlternateToPenaltyBox&&r.flags&ErrorActionFlags.MoveAllAlternatesMatchingHost){var n=this.levels,i=this._pathwayPriority,a=this.pathwayId;if(t.context){var s=t.context,o=s.groupId,l=s.pathwayId,u=s.type;o&&n?a=this.getPathwayForGroupId(o,u,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!i&&n&&(i=this.pathways()),i&&i.length>1&&(this.updatePathwayPriority(i),r.resolved=this.pathwayId!==a,r.resolved||t.details===ErrorDetails.BUFFER_APPEND_ERROR&&!t.fatal||this.warn("Could not resolve ".concat(t.details,' ("').concat(t.error.message,'") with content-steering for Pathway: ').concat(a," levels: ").concat(n?n.length:n," priorities: ").concat(stringify(i)," penalized: ").concat(stringify(this.penalizedPathways))))}}},{key:"filterParsedLevels",value:function(e){this.levels=e;var t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){var r=e[0].pathwayId;this.log("No levels found in Pathway ".concat(this.pathwayId,'. Setting initial Pathway to "').concat(r,'"')),t=this.getLevelsForPathway(r),this.pathwayId=r}return t.length!==e.length&&this.log("Found ".concat(t.length,"/").concat(e.length,' levels in Pathway "').concat(this.pathwayId,'"')),t}},{key:"getLevelsForPathway",value:function(e){return null===this.levels?[]:this.levels.filter(function(t){return e===t.pathwayId})}},{key:"updatePathwayPriority",value:function(e){var t;this._pathwayPriority=e;var r=this.penalizedPathways,n=performance.now();Object.keys(r).forEach(function(e){n-r[e]>PATHWAY_PENALTY_DURATION_MS&&delete r[e]});for(var i=0;i<e.length;i++){var a=e[i];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,reassignFragmentLevelIndexes(t),this.hls.trigger(Events$2.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 n=this.getLevelsForPathway(r).concat(this.levels||[]),i=0;i<n.length;i++)if(t===LoaderContextType.AUDIO_TRACK&&n[i].hasAudioGroup(e)||t===LoaderContextType.SUBTITLE_TRACK&&n[i].hasSubtitleGroup(e))return n[i].pathwayId;return r}},{key:"clonePathways",value:function(e){var t=this,r=this.levels;if(r){var n={},i={};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 AttrList(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&&(n[t.AUDIO]=r,t.AUDIO=r),s&&(i[t.SUBTITLES]=s,t.SUBTITLES=s);var l=performUriReplacement(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",o),u=new Level({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,_toConsumableArray(l)),cloneRenditionGroups(t.audioTracks,n,o,a),cloneRenditionGroups(t.subtitleTracks,i,o,a)}})}}},{key:"loadSteeringManifest",value:function(e){var t,r=this,n=this.hls.config,i=n.loader;this.loader&&this.loader.destroy(),this.loader=new i(n);try{t=new self.URL(e)}catch(d){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||n.abrEwmaDefaultEstimate);setQueryParam(t,"_HLS_pathway",this.pathwayId),setQueryParam(t,"_HLS_throughput",""+a)}var s={type:LoaderContextType.STEERING_MANIFEST,responseType:"json",url:t.href},o=n.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,n,i,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(d){return r.enabled=!1,void r.log("Failed to parse Steering Manifest RELOAD-URI: ".concat(o))}r.scheduleRefresh(r.uri||i.url),l&&r.clonePathways(l);var c={steeringManifest:s,url:t.toString()};r.hls.trigger(Events$2.STEERING_MANIFEST_LOADED,c),u&&r.updatePathwayPriority(u)}else r.log("Steering VERSION ".concat(s.VERSION," not supported!"))},onError:function(e,t,n,i){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,n){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,n=null==(r=t.hls)?void 0:r.media;!n||n.ended?t.scheduleRefresh(e,1e3*t.timeToLoad):t.loadSteeringManifest(e)},r)}}])}();function cloneRenditionGroups(e,t,r,n){e&&Object.keys(t).forEach(function(i){var a=e.filter(function(e){return e.groupId===i}).map(function(e){var a=_extends({},e);return a.details=void 0,a.attrs=new AttrList(a.attrs),a.url=a.attrs.URI=performUriReplacement(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",r),a.groupId=a.attrs["GROUP-ID"]=t[i],a.attrs["PATHWAY-ID"]=n,a});e.push.apply(e,_toConsumableArray(a))})}function performUriReplacement(e,t,r,n){if(t){var i=n[r];if(i){var a=i[t];if(a)return a}}var s=n.HOST,o=n.PARAMS,l=new self.URL(e);return s&&(l.hostname=s),o&&Object.keys(o).sort().forEach(function(e){e&&setQueryParam(l,e,o[e])}),l.href}var LicenseAndKeysRequestEmitter=function(){return _createClass(function e(){_classCallCheck(this,e),this.status="initialized",this.requestErrors=[],this.licenseXhr=void 0,this.onmessage=void 0,this.onkeystatuseschange=void 0,this.emitter=new EventEmitter,this.error=void 0,this.ok=void 0},[{key:"errored",get:function(){return this.error},set:function(e){this.error=e,this.emitter.eventNames().length&&this.emitter.emit("error",e)}},{key:"hasListeners",get:function(){return this.emitter.eventNames().length>0}},{key:"resolved",get:function(){return this.ok}},{key:"resolve",value:function(){this.ok=!0,this.emitter.emit("resolved")}},{key:"useable",get:function(){var e=this;return this.ok?Promise.resolve():this.error?Promise.reject(this.error):new Promise(function(t,r){e.emitter.on("error",r),e.emitter.on("resolved",t)})}},{key:"reset",value:function(){this.emitter.removeAllListeners();var e=this.licenseXhr;e&&(e.readyState!==XMLHttpRequest.DONE&&e.abort(),this.licenseXhr=void 0),this.onmessage=this.onkeystatuseschange=void 0}}])}(),EMEKeyError=function(){function e(t,r){var n;return _classCallCheck(this,e),(n=_callSuper(this,e,[r])).data=void 0,t.error||(t.error=new Error(r)),n.data=t,t.err=t.error,n}return _inherits(e,_wrapNativeSuper(Error)),_createClass(e)}(),EMEController=function(){function e(t){var r;return _classCallCheck(this,e),(r=_callSuper(this,e,["eme",t.logger])).hls=void 0,r.config=void 0,r.media=null,r.mediaResolved=void 0,r.keyFormatPromise=null,r.keySystemAccessPromises={},r.sessionSetupByUri={},r.mediaKeySessions=[],r.activeKeys={},r.mediaKeys=null,r.setMediaKeysQueue=e.CDMCleanupPromise?[e.CDMCleanupPromise]:[],r.onMediaEncrypted=function(e){var t=e.initDataType,n=e.initData,i='"'.concat(e.type,'" event: init data type: "').concat(t,'"');if(r.log(i),null!==n){if(!r.keyFormatPromise){var a=Object.keys(r.keySystemAccessPromises);a.length||(a=getKeySystemsForConfig(r.config));var s=a.map(keySystemDomainToKeySystemFormat).filter(function(e){return!!e});r.keyFormatPromise=r.getKeyFormatPromise(s)}r.keyFormatPromise.then(function(a){var s,o,l=keySystemFormatToKeySystemDomain(a),u=r.activeLevelKeys();if(l===KeySystems.FAIRPLAY&&"sinf"===t)try{var c=bin2str(new Uint8Array(n)),d=parseSinf(base64Decode(JSON.parse(c).sinf));if(!d)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");s=new Uint8Array(d.subarray(8,24))}catch(S){return void r.warn("".concat(i," Failed to parse sinf: ").concat(S))}else if(l===KeySystems.PLAYREADY)s=parsePlayReadyWRM(new Uint8Array(n));else if(l===KeySystems.WIDEVINE){var h=parseMultiPssh(n).filter(function(e){return e.systemId===KeySystemIds.WIDEVINE});if(h.length){var f,v=h[0];s=null!=(f=v.kids)&&f.length?v.kids[0]:null}}if(s)for(var p=arrayToHex(s),g=0;g<u.length;g++){var y=u[g];if(y.keyId&&(arrayValuesMatch(s,y.keyId)||-1!==y.uri.replace(/-/g,"").indexOf(p))){y.pssh||(y.scheme=t,y.pssh=new Uint8Array(n),y.keyId=s,LevelKey.setKeyIdForUri(y.uri,s)),o=r.getSessionForKey(y,"encrypted-event-key-match");break}}if(!o){var m,E;if(u.length)return(m=u[0]).scheme||(m.scheme=t),(E=u[0]).pssh||(E.pssh=new Uint8Array(n)),r.getSessionForKey(u[0],"encrypted-event-no-match");if(s)throw new Error("Key ID ".concat(arrayToHex(s)," not encountered in playlist"));r.log('Ignoring "'.concat(e.type,'" event - could not determine keyId'))}return o}).catch(function(e){return r.handleError(e)})}},r.onWaitingForKey=function(e){r.log('"'.concat(e.type,'" event'))},r.hls=t,r.config=t.config,r.registerListeners(),r}return _inherits(e,Logger$1),_createClass(e,[{key:"destroy",value:function(){this.onDestroying(),this.onMediaDetached();var e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=null,this.onMediaEncrypted=this.onWaitingForKey=null}},{key:"registerListeners",value:function(){var e=this.hls;e&&(e.on(Events$2.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Events$2.MEDIA_DETACHED,this.onMediaDetached,this),e.on(Events$2.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events$2.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Events$2.DESTROYING,this.onDestroying,this))}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(Events$2.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Events$2.MEDIA_DETACHED,this.onMediaDetached,this),e.off(Events$2.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events$2.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Events$2.DESTROYING,this.onDestroying,this))}},{key:"attemptKeySystemAccess",value:function(e){var t=this;if(!this.hls)return Promise.reject(new Error("destroyed"));var r=this.hls.levels,n=function(e,t,r){return!!e&&r.indexOf(e)===t},i=r.map(function(e){return e.audioCodec}).filter(n),a=r.map(function(e){return e.videoCodec}).filter(n);return i.length+a.length===0&&a.push("avc1.42e01e"),new Promise(function(r,n){var s=function(e){var o=e.shift();t.getMediaKeysPromise(o,i,a).then(function(e){return r({keySystem:o,mediaKeys:e})}).catch(function(t){e.length?s(e):n(t instanceof EMEKeyError?t:new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.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 n="Configured requestMediaKeySystemAccess is not a function ".concat(r);return null===_requestMediaKeySystemAccess&&"http:"===self.location.protocol&&(n="navigator.requestMediaKeySystemAccess is not available over insecure protocol ".concat(location.protocol)),Promise.reject(new Error(n))}return r(e,t)}},{key:"getMediaKeysPromise",value:function(e,t,r){var n,i=this,a=getSupportedMediaKeySystemConfigurations(e,t,r,this.config.drmSystemOptions||{}),s=this.keySystemAccessPromises[e],o=null==(n=s)?void 0:n.keySystemAccess;if(!o){this.log('Requesting encrypted media "'.concat(e,'" key-system access with config: ').concat(stringify(a))),o=this.requestMediaKeySystemAccess(e,a);var l=s=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(function(t){i.log('Failed to obtain access to key-system "'.concat(e,'": ').concat(t))}),o.then(function(t){i.throwIfDestroyed(),i.log('Access for key-system "'.concat(t.keySystem,'" obtained'));var r=i.fetchServerCertificate(e);i.log('Create media-keys for "'.concat(e,'"'));var n=l.mediaKeys=t.createMediaKeys().then(function(t){return i.log('Media-keys created for "'.concat(e,'"')),l.hasMediaKeys=!0,r.then(function(r){return r?i.setMediaKeysServerCertificate(t,e,r):t})});return n.catch(function(t){i.error('Failed to create media-keys for "'.concat(e,'"}: ').concat(t))}),n})}return o.then(function(){return s.mediaKeys})}},{key:"getMediaKeySessionContext",value:function(e,t,r,n){for(var i=this.mediaKeySessions,a=' key-session "'.concat(e,'" keyId: ').concat(arrayToHex(r.keyId||[])," keyUri: ").concat(r.uri,' for "').concat(n,'"'),s=0;s<i.length;s++){var o=i[s];if(!o.initialized&&o.createdFor.levelKey.uri===r.uri)return this.log("Reusing".concat(a)),o}this.log("Creating".concat(a));var l=t.createSession(),u={keySystem:e,mediaKeys:t,mediaKeysSession:l,keyRequests:{},keyStatuses:{},createdFor:{levelKey:r,reason:n},initialized:!1};return i.push(u),u}},{key:"resetMediaKeys",value:function(){var e,t=null==(e=this.mediaKeySessions[0])?void 0:e.keySystem,r=this.keySystemAccessPromises[t];r&&(this.log("reset mediaKeys"),this.mediaKeys=null,r.hasMediaKeys=!1,delete r.mediaKeys,delete this.keySystemAccessPromises[t])}},{key:"updateKeySession",value:function(e,t,r){var n=e.mediaKeysSession;return this.log('Updating key-session "'.concat(n.sessionId,'" for keyId ').concat(arrayToHex(t.keyId||[]),"\n } (data length: ").concat(r.byteLength,")")),n.update(r)}},{key:"getSelectedKeySystemFormats",value:function(){var e=this;return Object.keys(this.keySystemAccessPromises).map(function(t){return{keySystem:t,hasMediaKeys:e.keySystemAccessPromises[t].hasMediaKeys}}).filter(function(e){return!!e.hasMediaKeys}).map(function(e){return keySystemDomainToKeySystemFormat(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,n=e.mediaKeys;return t.attemptSetMediaKeys(r,n)})}},{key:"selectKeySystem",value:function(e){return this.getKeySystemSelectionPromise(e).then(function(e){var t=e.keySystem,r=keySystemDomainToKeySystemFormat(t);if(!r)throw new Error('Unable to find format for key-system "'.concat(t,'"'));return r})}},{key:"selectKeySystemFormat",value:function(e){var t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log("Selecting key-system from fragment (sn: ".concat(e.sn," ").concat(e.type,": ").concat(e.level,") key formats ").concat(t.join(", "))),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}},{key:"getKeyFormatPromise",value:function(e){var t=getKeySystemsForConfig(this.config),r=e.map(keySystemFormatToKeySystemDomain).filter(function(e){return!!e&&-1!==t.indexOf(e)});return this.selectKeySystem(r)}},{key:"loadClear",value:function(e,t,r){var n=this;if(this.config.emeEnabled&&!this.getSelectedKeySystemFormats().length){if(t.length)for(var i,a=function(){var i=t[s];if(e.cc<=i.cc&&(!isMediaFragment(e)||!isMediaFragment(i)||e.sn<i.sn)||!r&&s==o-1)return{v:n.selectKeySystemFormat(i).then(function(e){if(n.hls){i.setKeyFormat(e);var t=keySystemFormatToKeySystemDomain(e);return t?n.getKeySystemAccess([t]):void 0}})}},s=0,o=t.length;s<o;s++)if(i=a())return i.v;if(this.config.requireKeySystemAccessOnStart){var l=getKeySystemsForConfig(this.config);if(l.length)return this.getKeySystemAccess(l)}}return null}},{key:"getKeyStatus",value:function(e){for(var t=this.mediaKeySessions,r=0;r<t.length;r++){var n=_getKeyStatus(e,t[r]);if(n)return n}}},{key:"loadKey",value:function(e){var t=e.decryptdata,r=this.getKeyStatus(t);if("internal-error"===r){var n=getKeyStatusError(r,t);return n.data.frag=e,this.error("".concat(n.message," (").concat(arrayToHex(t.keyId||[]),")")),Promise.reject(n)}var i=e.type,a=this.activeKeys,s=a[i];s&&!t.matches(s.decryptdata)&&(a.previous||(a.previous=[]),a.previous.push(s),delete a[i]),a[i]||(a[i]=e);for(var o=this.mediaKeySessions.length;o--;){var l=this.mediaKeySessions[o];if(t.keyId&&"expired"===l.keyStatuses[arrayToHex(t.keyId)])return this.renewKeySession(t,l)}return this.updateUsablePromise(t,"playlist-key",e)}},{key:"renewKeySession",value:function(e,t){var r=this;return this.resetMediaKeys(),this.removeSession(t).then(function(){return r.throwIfDestroyed(),r.updateUsablePromise(e,"expired")})}},{key:"updateUsablePromise",value:function(e,t,r){var n=this,i=this.getSessionForKey(e,t);return i.catch(function(e){return n.handleError(e,r)}),i.then(function(t){return e})}},{key:"getSessionForKey",value:function(e,t){var r=this,n=this.findContextForKey(e);if(void 0!==n)return Promise.resolve(n);var i,a=e.uri,s=this.sessionSetupByUri[a];i=void 0===s?this.resolveSessionForKey(e,t):s.catch(function(){}).then(function(){return r.throwIfDestroyed(),r.resolveSessionForKey(e,t)}),this.sessionSetupByUri[a]=i;var o=function(){r.sessionSetupByUri[a]===i&&delete r.sessionSetupByUri[a]};return i.then(o,o),i}},{key:"findContextForKey",value:function(e){for(var t=this.mediaKeySessions,r=t.length;r--;){var n=t[r];if(_getKeyStatus(e,n))return n}}},{key:"resolveSessionForKey",value:function(e,t){var r=this;return this.getKeySystemForKeyPromise(e).then(function(n){var i=n.keySystem,a=n.mediaKeys;r.throwIfDestroyed();for(var s=r.mediaKeySessions.length;s--;){var o=r.mediaKeySessions[s];if(_getKeyStatus(e,o))return o;var l=r.getUsableKeyPromise(o,e,t);if(l)return l}return r.attemptSetMediaKeys(i,a).then(function(){return r.throwIfDestroyed(),r.getMediaKeySessionContext(i,a,e,t)}).then(function(n){r.throwIfDestroyed();var i=e.scheme||"cenc",a=e.pssh?e.pssh.buffer:null;return r.generateRequestWithPreferredKeySession(n,e,i,a,t)})})}},{key:"getUsableKeyPromise",value:function(e,t,r){var n=e.keyRequests[t.uri];if(n)return this.log("Waiting for usable key (".concat(r," keyId: ").concat(getKeyIdString(t),' format: "').concat(t.keyFormat,'" URI: ').concat(t.uri,")")),n.useable.then(function(){return e})}},{key:"throwIfDestroyed",value:function(){if(!this.hls)throw new Error("invalid state")}},{key:"handleError",value:function(e,t){if(this.hls)if(e instanceof EMEKeyError){t&&(e.data.frag=t);var r=e.data.decryptdata;this.error("".concat(e.message).concat(r?" (".concat(arrayToHex(r.keyId||[]),")"):"")),this.hls.trigger(Events$2.ERROR,e.data)}else this.error(e.message),this.hls.trigger(Events$2.ERROR,{type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}},{key:"getKeySystemForKeyPromise",value:function(e){var t=keySystemFormatToKeySystemDomain(e.keyFormat),r=t?[t]:getKeySystemsForConfig(this.config);return this.attemptKeySystemAccess(r)}},{key:"getKeySystemSelectionPromise",value:function(e){if(e.length||(e=getKeySystemsForConfig(this.config)),0===e.length)throw new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},"Missing key-system license configuration options ".concat(stringify({drmSystems:this.config.drmSystems})));return this.attemptKeySystemAccess(e)}},{key:"activeLevelKeys",value:function(){var e=this.activeKeys,t=(e.previous||[]).map(function(e){return e.decryptdata});return e.audio&&t.unshift(e.audio.decryptdata),e.main&&t.unshift(e.main.decryptdata),t}},{key:"attemptSetMediaKeys",value:function(e,t){var r=this;if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();var n=this.setMediaKeysQueue.slice();this.log('Setting media-keys for "'.concat(e,'"'));var i=Promise.all(n).then(function(){return r.media?r.media.setMediaKeys(t):new Promise(function(e,n){r.mediaResolved=function(){if(r.mediaResolved=void 0,!r.media)return n(new Error("Attempted to set mediaKeys without media element attached"));r.mediaKeys=t,r.media.setMediaKeys(t).then(e).catch(n)}})});return this.mediaKeys=t,this.setMediaKeysQueue.push(i),i.then(function(){r.log('Media-keys set for "'.concat(e,'"')),n.push(i),r.setMediaKeysQueue=r.setMediaKeysQueue.filter(function(e){return-1===n.indexOf(e)})})}},{key:"filterInitData",value:function(e,t,r,n,i){var a,s=null==(a=this.config.drmSystems)||null==(a=a[e.keySystem])?void 0:a.generateRequest;if(s)try{var o=s.call(this.hls,r,n,_extends({},e,{decryptdata:t,reason:i}),i);if(!o)throw new Error("Invalid response from configured generateRequest filter");t.scheme=o.initDataType?o.initDataType:"cenc";var l=o.initData?o.initData:null;return t.pssh=l?new Uint8Array(l):null,o}catch(c){var u;if(this.warn(c.message),null!=(u=this.hls)&&u.config.debug)throw c}return{initDataType:r,initData:n}}},{key:"generateRequestWithPreferredKeySession",value:function(e,t,r,n,i){var a=this,s=this.getUsableKeyPromise(e,t,i);if(s)return s;var o=this.filterInitData(e,t,r,n,i);if(o&&(n=o.initData?o.initData:null,r=o.initDataType),null===n)return i.startsWith("encrypted-event")?Promise.reject(new Error('missing initialization data for "'.concat(i,'"'))):(this.log('Skipping key-session request for "'.concat(i,'" (no initData)')),Promise.resolve(e));var l=t.uri,u=new LicenseAndKeysRequestEmitter;e.keyRequests[l]=u;var c=function(r){var n=e.mediaKeysSession;if(n){var i=r.messageType,s=r.message;u.status=i,a.log('"'.concat(i,'" message event for session "').concat(n.sessionId,'" message size: ').concat(s.byteLength)),"license-request"===i||"license-renewal"===i?a.renewLicense(e,t,s).catch(function(t){u.errored=t,u.hasListeners||a.handleError(t),a.removeSession(e)}):"license-release"===i?e.keySystem===KeySystems.FAIRPLAY&&a.updateKeySession(e,t,strToUtf8array("acknowledged")).then(function(){return a.removeSession(e)}).catch(function(e){return a.handleError(e)}):a.warn('unhandled media key message type "'.concat(i,'"'))}else{var o=new Error("invalid state");u.errored=o}};u.onmessage=c,addEventListener(e.mediaKeysSession,"message",c);return this.generateRequest(e,t,r,n,i,!1)}},{key:"generateRequest",value:function(e,t,r,n,i,a){var s=this;if(a){var o=this.filterInitData(e,t,r,n,i);o&&(n=o.initData?o.initData:n,r=o.initDataType)}var l=t.uri,u=e.keyRequests[l],c=arrayToHex(t.keyId||[]),d=function(e){var r;e.startsWith("usable")?u.resolve():"internal-error"===e||"output-restricted"===e||"output-downscaled"===e?r=getKeyStatusError(e,t):"expired"===e?r=new Error("key expired (keyId: ".concat(c,")")):"released"===e?r=new Error("key released"):"status-pending"===e||s.warn('unhandled key status change "'.concat(e,'" (keyId: ').concat(c,")")),r&&(u.errored=r,u.hasListeners||s.handleError(r))},h=function(r){if(e.mediaKeysSession){var n=e.keyStatuses=s.getKeyStatuses(e);if(Object.keys(n).some(function(e){return"status-pending"!==n[e]})){for(var i=s.activeLevelKeys(),a=0;a<i.length;a++){var o=arrayToHex(i[a].keyId||[]);if("expired"===n[o]){var l;s.log("Expired key ".concat(stringify(n),' in key-session "').concat(null==(l=e.mediaKeysSession)?void 0:l.sessionId,'"')),s.renewKeySession(t,e).catch(function(e){return s.handleError(e)});break}}var h=n[c];if(h)d(h);else{var f;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(f=e.keyStatusTimeouts)[c]||(f[c]=self.setTimeout(function(){var r;if(e.mediaKeysSession){var n,i=s.getKeyStatus(t);if(i&&"status-pending"!==i)return s.log("No status for keyId ".concat(c,' in key-session "').concat(null==(n=e.mediaKeysSession)?void 0:n.sessionId,'". Using session key-status ').concat(i," from other session.")),d(i);s.log("key status for ".concat(c,' in key-session "').concat(null==(r=e.mediaKeysSession)?void 0:r.sessionId,'" timed out after ').concat(1e3,"ms")),d(h="internal-error")}},1e3)),s.log("No status for keyId ".concat(c," (").concat(stringify(n),")."))}}}else{var v=new Error("invalid state");u.errored=v}};u.onkeystatuseschange=h,addEventListener(e.mediaKeysSession,"keystatuseschange",h);var f=u.useable;return this.log('Generating key-session request for "'.concat(i,'" keyId: ').concat(c," URI: ").concat(l," (init data type: ").concat(r," length: ").concat(n.byteLength,")")),u.status="started",e.initialized=!0,e.mediaKeysSession.generateRequest(r,n).then(function(){var t;u.status="generated",s.log('Request generated for key-session "'.concat(null==(t=e.mediaKeysSession)?void 0:t.sessionId,'" keyId: ').concat(c," URI: ").concat(l))}).catch(function(e){throw s.log("mediaKeysSession.generateRequest failed: ".concat(e)),new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_NO_SESSION,error:e,decryptdata:t,fatal:!1},"Error generating key-session request: ".concat(e))}).then(function(){return f}).catch(function(t){var r;s.log("mediaKeysSession.generateRequest failed: ".concat(t));var n=null==(r=t.data)?void 0:r.details;return n!==ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED&&n!==ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR||!Object.keys(e.keyStatuses).some(function(t){return"usable"===e.keyStatuses[t]})?s.removeSession(e).then(function(){throw t}):(s.handleError(t),e)}).then(function(){return e})}},{key:"getKeyStatuses",value:function(e){var t=this,r={},n=e.mediaKeysSession.sessionId;return e.mediaKeysSession.keyStatuses.forEach(function(i,a){if("string"==typeof a&&"object"===_typeof(i)){var s=a;a=i,i=s}var o="buffer"in a?new Uint8Array(a.buffer,a.byteOffset,a.byteLength):new Uint8Array(a);if(e.keySystem===KeySystems.PLAYREADY&&16===o.length){var l=arrayToHex(o);r[l]=i,changeEndianness(o)}var u=arrayToHex(o);t.log('key status change "'.concat(i,'" for keyStatuses keyId: ').concat(u,' key-session "').concat(n,'"')),r[u]=i}),r}},{key:"fetchServerCertificate",value:function(e){var t=this.config,r=new(0,t.loader)(t),n=getServerCertificateUrl(e,t);return n?(this.log('Fetching server certificate for "'.concat(e,'"')),new Promise(function(i,a){var s={type:LoaderContextType.SERVER_CERTIFICATE,responseType:"arraybuffer",url:n},o=t.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:function(e,t,r,n){i(e.data)},onError:function(t,r,i,o){a(new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:i,response:_objectSpread2({url:s.url,data:void 0},t)},'"'.concat(e,'" certificate request failed (').concat(n,"). Status: ").concat(t.code," (").concat(t.text,")")))},onTimeout:function(t,r,i){a(new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:i,response:{url:s.url,data:void 0}},'"'.concat(e,'" certificate request timed out (').concat(n,")")))},onAbort:function(e,t,r){a(new Error("aborted"))}};r.load(s,l,u)})):(this.log('No Server Certificate in config.drmSystems["'.concat(e,'"]')),Promise.resolve())}},{key:"setMediaKeysServerCertificate",value:function(e,t,r){var n=this;return new Promise(function(i,a){e.setServerCertificate(r).then(function(a){n.log("setServerCertificate ".concat(a?"success":"not supported by CDM"," (").concat(r.byteLength,') on "').concat(t,'"')),i(e)}).catch(function(e){a(new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))})})}},{key:"renewLicense",value:function(e,t,r){var n=this;return this.requestLicense(e,t,new Uint8Array(r)).then(function(r){return n.updateKeySession(e,t,new Uint8Array(r)).catch(function(e){throw new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t,error:e,fatal:!1},e.message)})})}},{key:"unpackPlayReadyKeyMessage",value:function(e,t){var r=bin2str(new Uint16Array(t.buffer));if(!r.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;var n=(new DOMParser).parseFromString(r,"application/xml"),i=n.querySelectorAll("HttpHeader");if(i.length>0)for(var a,s=0,o=i.length;s<o;s++){var l,u,c=null==(l=(a=i[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=n.querySelector("Challenge"),f=null==h?void 0:h.textContent;if(!f)throw new Error("Cannot find <Challenge> in key message");return strToUtf8array(atob(f))}},{key:"setupLicenseXHR",value:function(e,t,r,n,i){var a=this,s=this.config.licenseXhrSetup;return s?Promise.resolve().then(function(){return a.throwIfDestroyed(),s.call(a.hls,e,t,_objectSpread2(_objectSpread2({},r),{},{decryptdata:n}),i)}).catch(function(o){if(!r.mediaKeysSession)throw o;return e.open("POST",t,!0),s.call(a.hls,e,t,_objectSpread2(_objectSpread2({},r),{},{decryptdata:n}),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,r){var n=this;return new Promise(function(i,a){var s=getLicenseServerUrl(e.keySystem,n.config);if(!s)return a(new Error('no license server URL configured for key-system "'.concat(e.keySystem,'"')));var o=e.keyRequests[t.uri];if(!o)return a(new Error("License emitter removed"));n.log("Sending license request to URL: ".concat(s));var l=n.config.keyLoadPolicy.default,u=new XMLHttpRequest;u.responseType="arraybuffer",u.onreadystatechange=function(){if(!n.hls||!e.mediaKeysSession)return a(new Error("invalid state"));if(4===u.readyState)if(200===u.status){o.requestErrors=[];var c=u.response;n.log("License received ".concat(c instanceof ArrayBuffer?c.byteLength:c));var d=n.config.licenseResponseCallback;if(d)try{c=d.call(n.hls,u,s,_objectSpread2(_objectSpread2({},e),{},{decryptdata:t}))}catch(p){n.error(p)}i(c)}else{var h=l.errorRetry,f=h?h.maxNumRetry:0;if(o.requestErrors.push({status:u.status,message:u.statusText}),o.requestErrors.length>f||u.status>=400&&u.status<500)a(new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:t,fatal:!0,networkDetails:u,response:{url:s,data:void 0,code:u.status,text:u.statusText}},"License Request XHR failed (".concat(s,"). Status: ").concat(u.status," (").concat(u.statusText,")")));else{var v=f-o.requestErrors.length;n.warn("Retrying license request, ".concat(v," attempts left")),n.requestLicense(e,t,r).then(i,a)}}},o.licenseXhr&&o.licenseXhr.readyState!==XMLHttpRequest.DONE&&o.licenseXhr.abort(),o.licenseXhr=u,n.setupLicenseXHR(u,s,e,t,r).then(function(t){var r=t.xhr,i=t.licenseChallenge;e.keySystem==KeySystems.PLAYREADY&&(i=n.unpackPlayReadyKeyMessage(r,i)),r.send(i)}).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,addEventListener(r,"encrypted",this.onMediaEncrypted),addEventListener(r,"waitingforkey",this.onWaitingForKey);var n=this.mediaResolved;n?n():this.mediaKeys=r.mediaKeys}}},{key:"onMediaDetached",value:function(){var e=this.media;e&&(removeEventListener(e,"encrypted",this.onMediaEncrypted),removeEventListener(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}},{key:"_clear",value:function(){var t,r=this;this.keyFormatPromise=null,this.keySystemAccessPromises={},this.activeKeys={},this.sessionSetupByUri={};var n=this.mediaResolved;if(n&&n(),this.mediaKeys||this.mediaKeySessions.length){var i=this.media,a=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,LevelKey.clearKeyUriToKeyIdMap();var s=a.length;e.CDMCleanupPromise=Promise.all(a.map(function(e){return r.removeSession(e)}).concat((null==i||null==(t=i.setMediaKeys(null))?void 0:t.catch(function(e){r.log("Could not clear media keys: ".concat(e)),r.hls&&r.hls.trigger(Events$2.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.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(Events$2.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error("Could not close sessions and clear media keys: ".concat(e))})}).then(function(){s&&r.log("finished closing key sessions and clearing media keys")})}}},{key:"onManifestLoading",value:function(){this._clear(),this.keyFormatPromise=null}},{key:"onManifestLoaded",value:function(e,t){var r=t.sessionKeys;if(r&&this.config.emeEnabled&&!this.keyFormatPromise){var n=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(n.join(", "))),this.keyFormatPromise=this.getKeyFormatPromise(n),this.keyFormatPromise.catch(function(){})}}},{key:"removeSession",value:function(e){var t=this,r=e.mediaKeysSession;if(r){this.log('Remove licenses and keys and close session "'.concat(r.sessionId,'"')),Object.keys(e.keyRequests).forEach(function(t){var n=e.keyRequests[t];n.onmessage&&r.removeEventListener("message",n.onmessage),n.onkeystatuseschange&&r.removeEventListener("keystatuseschange",n.onkeystatuseschange),n.reset(),e.keyRequests[t]=void 0}),e.mediaKeysSession=void 0;var n=this.mediaKeySessions.indexOf(e);n>-1&&this.mediaKeySessions.splice(n,1);var i=e.keyStatusTimeouts;return i&&Object.keys(i).forEach(function(e){return self.clearTimeout(i[e])}),(isPersistentSessionType(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()).catch(function(e){t.log("Could not remove session: ".concat(e)),t.hls&&t.hls.trigger(Events$2.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error("Could not remove session: ".concat(e))})}).then(function(){return r.close()}).then(function(){return r.closed}).catch(function(e){t.log("Could not close session: ".concat(e)),t.hls&&t.hls.trigger(Events$2.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error("Could not close session: ".concat(e))})})}return Promise.resolve()}}])}();function getLicenseServerUrl(e,t){var r=t.drmSystems,n=t.widevineLicenseUrl,i=null==r?void 0:r[e];return i?i.licenseUrl:e===KeySystems.WIDEVINE&&n?n:void 0}function getServerCertificateUrl(e,t){var r=t.drmSystems,n=null==r?void 0:r[e];if(n)return n.serverCertificateUrl}function getKeyIdString(e){if(e.keyFormat===KeySystemFormats.FAIRPLAY)return e.uri;if(null===e.keyId)throw new Error("keyId is null");return arrayToHex(e.keyId)}function _getKeyStatus(e,t){var r=e.keyId,n=t.mediaKeysSession;if(r&&n){var i=t.mediaKeysSession.keyStatuses;if(i.size)return i.has(r)?i.get(r):t.keyStatuses[arrayToHex(r)]}}function getKeyStatusError(e,t){var r="output-restricted"===e,n=r?ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:n,fatal:!1,decryptdata:t},r?"HDCP level output restricted":'key status changed to "'.concat(e,'"'))}EMEController.CDMCleanupPromise=void 0;var FPSController=function(){return _createClass(function e(t){_classCallCheck(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(Events$2.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(Events$2.MEDIA_DETACHING,this.onMediaDetaching,this)}},{key:"unregisterListeners",value:function(){this.hls.off(Events$2.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(Events$2.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 n=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=n,n&&"function"==typeof n.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 n=performance.now();if(t){if(this.lastTime){var i=n-this.lastTime,a=r-this.lastDroppedFrames,s=t-this.lastDecodedFrames,o=1e3*a/i,l=this.hls;if(l.trigger(Events$2.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(Events$2.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:l.currentLevel}),l.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=n,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)}}])}(),VTTCue=function(){if(null!=optionalSelf&&optionalSelf.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 n(e){return r(t,e)}function i(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];for(var i=1;i<arguments.length;i++){var a=arguments[i];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,p="",g=!0,y="auto",m="start",E=50,S="middle",T=50,k="middle";Object.defineProperty(o,"id",i({},l,{get:function(){return u},set:function(e){u=""+e}})),Object.defineProperty(o,"pauseOnExit",i({},l,{get:function(){return c},set:function(e){c=!!e}})),Object.defineProperty(o,"startTime",i({},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",i({},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",i({},l,{get:function(){return f},set:function(e){f=""+e,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",i({},l,{get:function(){return v},set:function(e){v=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",i({},l,{get:function(){return p},set:function(t){var n=function(t){return r(e,t)}(t);if(!1===n)throw new SyntaxError("An invalid or illegal string was specified.");p=n,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",i({},l,{get:function(){return g},set:function(e){g=!!e,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",i({},l,{get:function(){return y},set:function(e){if("number"!=typeof e&&"auto"!==e)throw new SyntaxError("An invalid number or illegal string was specified.");y=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",i({},l,{get:function(){return m},set:function(e){var t=n(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");m=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",i({},l,{get:function(){return E},set:function(e){if(e<0||e>100)throw new Error("Position must be between 0 and 100.");E=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",i({},l,{get:function(){return S},set:function(e){var t=n(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");S=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",i({},l,{get:function(){return T},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",i({},l,{get:function(){return k},set:function(e){var t=n(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");k=t,this.hasBeenReset=!0}})),o.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}(),StringDecoder=function(){return _createClass(function e(){_classCallCheck(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 parseTimeStamp(e){function t(e,t,r,n){return 3600*(0|e)+60*(0|t)+(0|r)+parseFloat(n||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 Settings=function(){return _createClass(function e(){_classCallCheck(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 n=0;n<r.length;++n)if(t===r[n]){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 parseOptions(e,t,r,n){var i=n?e.split(n):[e];for(var a in i)if("string"==typeof i[a]){var s=i[a].split(r);if(2===s.length)t(s[0],s[1])}}var defaults$1=new VTTCue(0,0,""),center="middle"===defaults$1.align?"middle":"center";function parseCue(e,t,r){var n=e;function i(){var t=parseTimeStamp(e);if(null===t)throw new Error("Malformed timestamp: "+n);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function a(){e=e.replace(/^\s+/,"")}if(a(),t.startTime=i(),a(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+n);e=e.slice(3),a(),t.endTime=i(),a(),function(e,t){var n=new Settings;parseOptions(e,function(e,t){var i;switch(e){case"region":for(var a=r.length-1;a>=0;a--)if(r[a].id===t){n.set(e,r[a].region);break}break;case"vertical":n.alt(e,t,["rl","lr"]);break;case"line":i=t.split(","),n.integer(e,i[0]),n.percent(e,i[0])&&n.set("snapToLines",!1),n.alt(e,i[0],["auto"]),2===i.length&&n.alt("lineAlign",i[1],["start",center,"end"]);break;case"position":i=t.split(","),n.percent(e,i[0]),2===i.length&&n.alt("positionAlign",i[1],["start",center,"end","line-left","line-right","auto"]);break;case"size":n.percent(e,t);break;case"align":n.alt(e,t,["start",center,"end","left","right"])}},/:/,/\s/),t.region=n.get("region",null),t.vertical=n.get("vertical","");var i=n.get("line","auto");"auto"===i&&-1===defaults$1.line&&(i=-1),t.line=i,t.lineAlign=n.get("lineAlign","start"),t.snapToLines=n.get("snapToLines",!0),t.size=n.get("size",100),t.align=n.get("align",center);var a=n.get("position","auto");"auto"===a&&50===defaults$1.position&&(a="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=a}(e,t)}function fixLineBreaks(e){return e.replace(/<br(?: \/)?>/gi,"\n")}var VTTParser=function(){return _createClass(function e(){_classCallCheck(this,e),this.state="INITIAL",this.buffer="",this.decoder=new StringDecoder,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=fixLineBreaks(e);r<e.length&&"\r"!==e[r]&&"\n"!==e[r];)++r;var n=e.slice(0,r);return"\r"===e[r]&&++r,"\n"===e[r]&&++r,t.buffer=e.slice(r),n}function n(e){parseOptions(e,function(e,t){},/:/)}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{var i="";if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;var a=(i=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:i=r(),t.state){case"HEADER":/:/.test(i)?n(i):i||(t.state="ID");continue;case"NOTE":i||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(i)){t.state="NOTE";break}if(!i)continue;if(t.cue=new VTTCue(0,0,""),t.state="CUE",-1===i.indexOf("--\x3e")){t.cue.id=i;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{parseCue(i,t.cue,t.regionList)}catch(l){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":var o=-1!==i.indexOf("--\x3e");if(!i||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+=i;continue;case"BADCUE":i||(t.state="ID")}}}catch(l){"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this}},{key:"flush",value:function(){var e=this;try{if((e.cue||"HEADER"===e.state)&&(e.buffer+="\n\n",e.parse()),"INITIAL"===e.state||"BADWEBVTT"===e.state)throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}])}();function hash(e){for(var t=5381,r=e.length;r;)t=33*t^e.charCodeAt(--r);return(t>>>0).toString()}var LINEBREAKS=/\r\n|\n\r|\n|\r/g,missingInitPTSErrorStartsWith="Missing initPTS for VTT ",cueString2millis=function(e){var t=parseInt(e.slice(-3)),r=parseInt(e.slice(-6,-4)),n=parseInt(e.slice(-9,-7)),i=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(isFiniteNumber(t)&&isFiniteNumber(r)&&isFiniteNumber(n)&&isFiniteNumber(i)))throw Error("Malformed X-TIMESTAMP-MAP: Local:".concat(e));return t+=1e3*r,t+=6e4*n,t+=36e5*i};function generateCueId(e,t,r){return hash(e.toString())+hash(t.toString())+hash(r)}function parseWebVTT(e,t,r,n,i,a,s){var o,l=new VTTParser,u=utf8ArrayToStr(new Uint8Array(e)).trim().replace(LINEBREAKS,"\n").split("\n"),c=[],d=t?toMpegTsClockFromTimescale(t.baseTime,t.timescale):0,h="00:00.000",f=0,v=0,p=!1,g=!0;l.oncue=function(e){var a=r[n],s=r.ccOffset,l=(f-d)/9e4;if(p){if(null!=a&&a.new&&(s=r.ccOffset=a.start),l){if(!t)return void(o=new Error(missingInitPTSErrorStartsWith+"MPEGTS"));s=l-r.presentationOffset}}else{if(!t)return void(o=new Error(missingInitPTSErrorStartsWith+"without X-TIMESTAMP-MAP"));s=-t.baseTime/t.timescale}var u=e.endTime-e.startTime,h=normalizePts(9e4*(e.startTime+s-v),9e4*i)/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?n&&(e.id="hlsjscc".concat(n,"_").concat(e.id)):e.id=generateCueId(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(e.startsWith("X-TIMESTAMP-MAP=")){g=!1,p=!0,e.slice(16).split(",").forEach(function(e){e.startsWith("LOCAL:")?h=e.slice(6):e.startsWith("MPEGTS:")&&(f=parseInt(e.slice(7)))});try{v=cueString2millis(h)/1e3}catch(t){o=t}return}""===e&&(g=!1)}l.parse(e+"\n")}),l.flush()}var IMSC1_CODEC="stpp.ttml.im1t",HMSF_REGEX=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,TIME_UNIT_REGEX=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,textAlignToLineAlign={left:"start",center:"center",right:"end",start:"start",end:"end"};function parseIMSC1(e,t,r,n){var i=findBox(new Uint8Array(e),["mdat"]);if(0!==i.length){var a=i.map(function(e){return utf8ArrayToStr(e)}),s=toTimescaleFromScale(t.baseTime,1,t.timescale);try{a.forEach(function(e){return r(parseTTML(e,s))})}catch(o){n(o)}}else n(new Error("Could not parse IMSC1 mdat"))}function parseTTML(e,t){var r=(new DOMParser).parseFromString(e,"text/xml").getElementsByTagName("tt")[0];if(!r)throw new Error("Invalid ttml");var n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:1},i=Object.keys(n).reduce(function(e,t){return e[t]=r.getAttribute("ttp:".concat(t))||n[t],e},{});!r.getAttribute("ttp:tickRate")&&r.getAttribute("ttp:frameRate")&&(i.tickRate=Number(i.frameRate)*Number(i.subFrameRate));var a="preserve"!==r.getAttribute("xml:space"),s=collectionToDictionary(getElementCollection(r,"styling","style")),o=collectionToDictionary(getElementCollection(r,"layout","region")),l=getElementCollection(r,"body","[begin]");return[].map.call(l,function(e){var r=getTextContent(e,a);if(!r||!e.hasAttribute("begin"))return null;var n=parseTtmlTime(e.getAttribute("begin"),i),l=parseTtmlTime(e.getAttribute("dur"),i),u=parseTtmlTime(e.getAttribute("end"),i);if(null===n)throw timestampParsingError(e);if(null===u){if(null===l)throw timestampParsingError(e);u=n+l}var c=new VTTCue(n-t,u-t,r);c.id=generateCueId(c.startTime,c.endTime,c.text);var d=getTtmlStyles(o[e.getAttribute("region")],s[e.getAttribute("style")],s),h=d.textAlign;if(h){var f=textAlignToLineAlign[h];f&&(c.lineAlign=f),c.align=h}return _extends(c,d),c}).filter(function(e){return null!==e})}function getElementCollection(e,t,r){var n=e.getElementsByTagName(t)[0];return n?[].slice.call(n.querySelectorAll(r)):[]}function collectionToDictionary(e){return e.reduce(function(e,t){var r=t.getAttribute("xml:id");return r&&(e[r]=t),e},{})}function getTextContent(e,t){return[].slice.call(e.childNodes).reduce(function(e,r,n){var i;return"br"===r.nodeName&&n?e+"\n":null!=(i=r.childNodes)&&i.length?getTextContent(r,t):t?e+r.textContent.trim().replace(/\s+/g," "):e+r.textContent},"")}function getTtmlStyles(e,t,r){var n="http://www.w3.org/ns/ttml#styling",i=null,a=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;return a&&r.hasOwnProperty(a)&&(i=r[a]),["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"].reduce(function(r,a){var s=getAttributeNS(t,n,a)||getAttributeNS(e,n,a)||getAttributeNS(i,n,a);return s&&(r[a]=s),r},{})}function getAttributeNS(e,t,r){return e&&e.hasAttributeNS(t,r)?e.getAttributeNS(t,r):null}function timestampParsingError(e){return new Error("Could not parse ttml timestamp ".concat(e))}function parseTtmlTime(e,t){if(!e)return null;var r=parseTimeStamp(e);return null===r&&(HMSF_REGEX.test(e)?r=parseHoursMinutesSecondsFrames(e,t):TIME_UNIT_REGEX.test(e)&&(r=parseTimeUnits(e,t))),r}function parseHoursMinutesSecondsFrames(e,t){var r=HMSF_REGEX.exec(e),n=(0|r[4])+(0|r[5])/t.subFrameRate;return 3600*(0|r[1])+60*(0|r[2])+(0|r[3])+n/t.frameRate}function parseTimeUnits(e,t){var r=TIME_UNIT_REGEX.exec(e),n=Number(r[1]);switch(r[2]){case"h":return 3600*n;case"m":return 60*n;case"ms":return n/1e3;case"f":return n/t.frameRate;case"t":return n/t.tickRate}return n}function createTrackNode(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:"disabled",a=e.ownerDocument.createElement("track");return a.kind=t,a.label=r,n&&(a.srclang=n),a.src="data:,WEBVTT",a.track.mode=i,e.appendChild(a),a}function getTrackKind(e){return e.forced&&userAgentIsIOSLike()?"forced":e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function addCueToTrack(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(err){logger.debug("[texttrack-utils]: ".concat(err));try{var n=new self.TextTrackCue(t.startTime,t.endTime,t.text);n.id=t.id,e.addCue(n)}catch(i){logger.debug("[texttrack-utils]: Legacy TextTrackCue fallback failed: ".concat(i))}}"disabled"===r&&(e.mode=r)}function removeCuesInRange(e,t,r,n){var i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues&&e.cues.length>0)for(var a=getCuesInRange(e.cues,t,r),s=0;s<a.length;s++)n&&!n(a[s])||e.removeCue(a[s]);"disabled"===i&&(e.mode=i)}function getFirstCueIndexFromTime(e,t){if(t<=e[0].startTime)return 0;var r=e.length-1;if(t>e[r].endTime)return-1;for(var n,i=0,a=r;i<=a;)if(t<e[n=Math.floor((a+i)/2)].startTime)a=n-1;else{if(!(t>e[n].startTime&&i<r))return n;i=n+1}return e[i].startTime-t<t-e[a].startTime?i:a}function getCuesInRange(e,t,r){var n=[],i=getFirstCueIndexFromTime(e,t);if(i>-1)for(var a=i,s=e.length;a<s;a++){var o=e[a];if(o.startTime>=t&&o.endTime<=r)n.push(o);else if(o.startTime>r)return n}return n}var SubtitleTrackController=function(){function e(t){var r;return _classCallCheck(this,e),(r=_callSuper(this,e,[t,"subtitle-track-controller"])).media=null,r.tracks=[],r.groupIds=null,r.tracksInGroup=[],r.trackId=-1,r.currentTrack=null,r.selectDefaultTrack=!0,r.queuedDefaultTrack=-1,r.useTextTrackPolling=!1,r.subtitlePollingInterval=-1,r._subtitleDisplay=!0,r.asyncPollTrackChange=function(){return r.pollTrackChange(0)},r.onTextTracksChanged=function(){if(r.useTextTrackPolling||self.clearInterval(r.subtitlePollingInterval),r.media&&r.hls.config.renderTextTracksNatively){var e,t=-1,n=!1;if(r.currentTrack){var i,a=null==(i=r.currentTrack.trackNode)?void 0:i.track.mode;"showing"===a?(t=r.trackId,n=!0):"hidden"===a&&(t=r.trackId)}if(!n)for(var s=0;s<r.tracksInGroup.length;s++){var o,l=null==(o=r.tracksInGroup[s].trackNode)?void 0:o.track.mode;if("showing"===l){t=s;break}t<0&&"hidden"===l&&(t=s)}if(t>-1)r._subtitleDisplay="showing"===(null==(e=r.tracksInGroup[t].trackNode)?void 0:e.track.mode);r.setSubtitleTrack(t,!0)}},r.registerListeners(),r}return _inherits(e,BasePlaylistController),_createClass(e,[{key:"destroy",value:function(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,_superPropGet(e,"destroy",this)([])}},{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(Events$2.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Events$2.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events$2.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events$2.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Events$2.LEVEL_LOADING,this.onLevelLoading,this),e.on(Events$2.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Events$2.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(Events$2.ERROR,this.onError,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(Events$2.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Events$2.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events$2.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events$2.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Events$2.LEVEL_LOADING,this.onLevelLoading,this),e.off(Events$2.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Events$2.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(Events$2.ERROR,this.onError,this)}},{key:"createTracksInGroup",value:function(){var e,t=this;if(this.media&&this.hls.config.renderTextTracksNatively){this.tracksInGroup.forEach(function(e){e.trackNode||(e.trackNode=createTrackNode(t.media,getTrackKind(e),e.name,e.lang))});var r=null==(e=this.currentTrack)||null==(e=e.trackNode)?void 0:e.track;"disabled"===(null==r?void 0:r.mode)&&(r.mode=this._subtitleDisplay?"showing":"hidden")}}},{key:"onMediaAttached",value:function(e,t){var r=t.media;this.media=r;var n=this.trackId;this.queuedDefaultTrack>-1&&(n=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.setSubtitleTrack(n),this.createTracksInGroup(),this.useTextTrackPolling=!(r.textTracks&&"onchange"in r.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):r.textTracks.addEventListener("change",this.asyncPollTrackChange)}},{key:"pollTrackChange",value:function(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}},{key:"onMediaDetaching",value:function(e,t){var r=this.media;if(r){var n=!!t.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||r.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId,this.setSubtitleTrack(-1)),this.media=null,n||this.hls.config.renderTextTracksNatively&&this.tracksInGroup.forEach(function(e){var t=e.trackNode;t&&(t.track.mode="hidden",t.remove(),e.trackNode=void 0)})}}},{key:"onManifestLoading",value:function(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}},{key:"onManifestParsed",value:function(e,t){this.tracks=t.subtitleTracks}},{key:"onSubtitleTrackLoaded",value:function(e,t){var r=t.id,n=t.groupId,i=t.details,a=this.tracksInGroup[r];if(a&&a.groupId===n){var s=a.details;a.details=t.details,this.log("Subtitle track ".concat(r,' "').concat(a.name,'" lang:').concat(a.lang," group:").concat(n," loaded [").concat(i.startSN,"-").concat(i.endSN,"]")),r===this.trackId&&this.playlistLoaded(r,t,s)}else this.warn("Subtitle track with id:".concat(r," and group:").concat(n," not found in active group ").concat(null==a?void 0:a.groupId))}},{key:"onLevelLoading",value:function(e,t){this.switchLevel(t.level)}},{key:"onLevelSwitching",value:function(e,t){this.switchLevel(t.level)}},{key:"switchLevel",value:function(e){var t=this,r=this.hls.levels[e];if(r){var n=r.subtitleGroups||null,i=this.groupIds,a=this.currentTrack;if(!n||(null==i?void 0:i.length)!==(null==n?void 0:n.length)||null!=n&&n.some(function(e){return-1===(null==i?void 0:i.indexOf(e))})){this.groupIds=n;var s=[];if(this.tracks.forEach(function(e){(e.textCodec===IMSC1_CODEC?t.hls.config.enableIMSC1:t.hls.config.enableWebVTT)&&(!n||n.indexOf(e.groupId)>-1?(e.id=s.length,s.push(e)):e.trackNode&&(e.trackNode.remove(),e.trackNode=void 0))}),s.length===this.tracksInGroup.length){for(var o=!1,l=0;l<s.length;l++)if(s[l]!==this.tracksInGroup[l]){o=!0;break}if(!o)return}s.length&&this.selectDefaultTrack&&!s.some(function(e){return e.default})&&(this.selectDefaultTrack=!1),this.tracksInGroup=s,this.trackId=-1,this.currentTrack=null;var u=this.hls.config.subtitlePreference;if(!a&&u){this.selectDefaultTrack=!1;var c=findMatchingOption(u,s);if(c>-1)a=s[c];else{var d=findMatchingOption(u,this.tracks);a=this.tracks[d]}}var h=this.findTrackId(a);-1===h&&a&&(h=this.findTrackId(null));var f={subtitleTracks:s};this.log("Updating subtitle tracks, ".concat(s.length,' track(s) found in "').concat(null==n?void 0:n.join(","),'" group-id')),this.hls.trigger(Events$2.SUBTITLE_TRACKS_UPDATED,f),this.setSubtitleTrack(h),this.createTracksInGroup()}}}},{key:"findTrackId",value:function(e){for(var t=this.tracksInGroup,r=this.selectDefaultTrack,n=0;n<t.length;n++){var i=t[n];if((!r||i.default)&&(r||e)&&(!e||matchesOption(i,e)))return n}if(e){for(var a=0;a<t.length;a++){var s=t[a];if(mediaAttributesIdentical(e.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return a}for(var o=0;o<t.length;o++){var l=t[o];if(mediaAttributesIdentical(e.attrs,l.attrs,["LANGUAGE"]))return o}}return-1}},{key:"onError",value:function(e,t){!t.fatal&&t.context&&t.context.type===LoaderContextType.SUBTITLE_TRACK&&t.context.id===this.trackId&&inGroupOrNone(t.context.groupId,this.groupIds)&&this.checkRetry(t)}},{key:"allSubtitleTracks",get:function(){return this.tracks}},{key:"subtitleTracks",get:function(){return this.tracksInGroup}},{key:"subtitleTrack",get:function(){return this.trackId},set:function(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e,!0)}},{key:"setSubtitleOption",value:function(e){if(this.hls.config.subtitlePreference=e,e){if(-1===e.id)return this.setSubtitleTrack(-1,!0),null;var t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){var r=this.currentTrack;if(r&&matchesOption(e,r))return r;var n=findMatchingOption(e,this.tracksInGroup);if(n>-1){var i=this.tracksInGroup[n];return this.setSubtitleTrack(n,!0),i}if(r)return null;var a=findMatchingOption(e,t);if(a>-1)return t[a]}}return null}},{key:"loadPlaylist",value:function(t){_superPropGet(e,"loadPlaylist",this)([]),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,t)}},{key:"loadingPlaylist",value:function(t,r){_superPropGet(e,"loadingPlaylist",this)([t,r]);var n=t.id,i=t.groupId,a=this.getUrlWithDirectives(t.url,r),s=t.details,o=null==s?void 0:s.age;this.log("Loading subtitle ".concat(n,' "').concat(t.name,'" lang:').concat(t.lang," group:").concat(i).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(Events$2.SUBTITLE_TRACK_LOADING,{url:a,id:n,groupId:i,deliveryDirectives:r||null,track:t})}},{key:"toggleTrackModes",value:function(){var e=this;if(this.media&&this.hls.config.renderTextTracksNatively){var t=this.currentTrack;this.tracksInGroup.forEach(function(r){if(r.trackNode){var n=r===t?e._subtitleDisplay?"showing":"hidden":"disabled",i=r.trackNode.track;i.mode!==n&&(i.mode=n)}})}}},{key:"setSubtitleTrack",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=this.tracksInGroup;if(this.media||(this.queuedDefaultTrack=e),e<-1||e>=r.length||!isFiniteNumber(e))this.warn("Invalid subtitle track id: ".concat(e));else{var n=this.currentTrack,i=r[e]||null;if(this.trackId=e,this.currentTrack=i,t&&this.toggleTrackModes(),i){var a=!!i.details&&!i.details.live;if(i!==n||!a){this.log("Switching to subtitle-track ".concat(e)+(i?' "'.concat(i.name,'" lang:').concat(i.lang," group:").concat(i.groupId):""));var s=i.id,o=i.groupId,l=void 0===o?"":o,u=i.name,c=i.type,d=i.url;this.hls.trigger(Events$2.SUBTITLE_TRACK_SWITCH,{id:s,groupId:l,name:u,type:c,url:d});var h=this.switchParams(i.url,null==n?void 0:n.details,i.details);this.loadPlaylist(h)}}else n&&this.hls.trigger(Events$2.SUBTITLE_TRACK_SWITCH,{id:e})}}}])}(),MAX_START_GAP_JUMP=2,TICK_INTERVAL$2=100,GapController=function(){function e(t,r){var n;return _classCallCheck(this,e),(n=_callSuper(this,e,["gap-controller",t.logger])).hls=void 0,n.fragmentTracker=void 0,n.media=null,n.mediaSource=void 0,n.nudgeRetry=0,n.skipRetry=0,n.stallReported=!1,n.stalled=null,n.moved=!1,n.seeking=!1,n.buffered={},n.lastCurrentTime=void 0,n.ended=0,n.waiting=0,n.onMediaPlaying=function(){n.ended=0,n.waiting=0},n.onMediaWaiting=function(){var e;null!=(e=n.media)&&e.seeking||(n.waiting=self.performance.now(),n.tick())},n.onMediaEnded=function(){var e;n.hls&&(n.ended=(null==(e=n.media)?void 0:e.currentTime)||1,n.hls.trigger(Events$2.MEDIA_ENDED,{stalled:!1}))},n.hls=t,n.fragmentTracker=r,n.lastCurrentTime=n.getCurrentTime(),n.registerListeners(),n}return _inherits(e,TaskLoop),_createClass(e,[{key:"registerListeners",value:function(){var e=this.hls;e&&(e.on(Events$2.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Events$2.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events$2.BUFFER_APPENDED,this.onBufferAppended,this))}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(Events$2.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Events$2.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events$2.BUFFER_APPENDED,this.onBufferAppended,this))}},{key:"destroy",value:function(){_superPropGet(e,"destroy",this)([]),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}},{key:"onMediaAttached",value:function(e,t){this.setInterval(TICK_INTERVAL$2),this.mediaSource=t.mediaSource;var r=this.media=t.media;addEventListener(r,"playing",this.onMediaPlaying),addEventListener(r,"waiting",this.onMediaWaiting),addEventListener(r,"ended",this.onMediaEnded)}},{key:"onMediaDetaching",value:function(e,t){this.clearInterval();var r=this.media;r&&(removeEventListener(r,"playing",this.onMediaPlaying),removeEventListener(r,"waiting",this.onMediaWaiting),removeEventListener(r,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}},{key:"onBufferAppended",value:function(e,t){this.buffered=t.timeRanges}},{key:"hasBuffered",get:function(){return Object.keys(this.buffered).length>0}},{key:"getCurrentTime",value:function(){var e,t=(null==(e=this.hls)?void 0:e.config.timelineOffset)||0;return this.media?Math.max(this.media.currentTime,t):t}},{key:"tick",value:function(){var e;if(null!=(e=this.media)&&e.readyState&&this.hasBuffered){var t=this.getCurrentTime();this.media.currentTime<t||(this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t)}}},{key:"poll",value:function(e,t){var r,n,i=null==(r=this.hls)?void 0:r.config;if(i){var a=this.media;if(a){var s=a.seeking,o=this.seeking&&!s,l=!this.seeking&&s,u=a.paused&&!s||a.ended||0===a.playbackRate;if(this.seeking=s,e!==t)return t&&(this.ended=0),this.moved=!0,s||(this.skipRetry=this.nudgeRetry=0,i.nudgeOnVideoHole&&!u&&e>t&&this.nudgeOnVideoHole(e,t)),void(0===this.waiting&&this.stallResolved(e));if(l||o)o&&this.stallResolved(e);else{if(u)return this.skipRetry=this.nudgeRetry=0,this.stallResolved(e),void(!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(Events$2.MEDIA_ENDED,{stalled:!1})));if(BufferHelper.getBuffered(a).length){var c=BufferHelper.bufferInfo(a,e,0),d=this.fragmentTracker;d&&this.hls&&withInterstitialBoundary(c,e,d,this.hls);var h=c.nextStart||0;if(s&&d&&this.hls){var f=getInFlightDependency(this.hls.inFlightFragments,e),v=c.len>MAX_START_GAP_JUMP,p=!h||f||h-e>MAX_START_GAP_JUMP&&!d.getPartialFragment(e);if(v||p)return;this.moved=!1}var g=null==(n=this.hls)?void 0:n.latestLevelDetails;if(!this.moved&&null!==this.stalled&&d){if(!(c.len>0)&&!h)return;var y=Math.max(h,c.start||0)-e,m=!(null==g||!g.live)?2*g.targetduration:MAX_START_GAP_JUMP,E=appendedFragAtPosition(e,d);if(y>0&&(y<=m||E))return void(a.paused||this._trySkipBufferHole(E))}var S=i.detectStallWithCurrentTimeMs,T=self.performance.now(),k=this.waiting,_=this.stalled;if(null===_){if(!(k>0&&T-k<S))return void(this.stalled=T);_=this.stalled=k}var A=T-_;if(!s&&(A>=S||k&&this.moved)&&this.hls){var b;if("ended"===(null==(b=this.mediaSource)?void 0:b.readyState)&&(null==g||!g.live)&&Math.abs(e-((null==g?void 0:g.edge)||0))<1){if(this.ended)return;return this.ended=e||1,void this.hls.trigger(Events$2.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(c),!this.media||!this.hls)return;if(a.currentTime!==e){var L=e;return e=a.currentTime,this.moved=!0,void this.log("currentTime changed ".concat(L," > ").concat(e))}}var R=BufferHelper.bufferInfo(a,e,i.maxBufferHole);this._tryFixBufferStall(R,A,e)}else this.skipRetry=this.nudgeRetry=0}}}}},{key:"stallResolved",value:function(e){var t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){var r=self.performance.now()-t;this.log("playback not stuck anymore @".concat(e,", after ").concat(Math.round(r),"ms")),this.stallReported=!1,this.waiting=0,this.hls.trigger(Events$2.STALL_RESOLVED,{})}}},{key:"nudgeOnVideoHole",value:function(e,t){var r,n=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(r=this.buffered.audio)&&r.length&&n&&n.length>1&&e>n.end(0)){var i=BufferHelper.bufferedInfo(BufferHelper.timeRangesToArray(this.buffered.audio),e,0);if(i.len>1&&t>=i.start){var a=BufferHelper.timeRangesToArray(n),s=BufferHelper.bufferedInfo(a,t,0).bufferedIndex;if(s>-1&&s<a.length-1){var o=BufferHelper.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=appendedFragAtPosition(e,this.fragmentTracker);d&&"fragment"in d?d=d.fragment:d||(d=void 0);var h=BufferHelper.bufferInfo(this.media,e,0);this.hls.trigger(Events$2.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.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 n,i,a=this.fragmentTracker,s=this.media,o=null==(n=this.hls)?void 0:n.config;if(s&&a&&o){var l=null==(i=this.hls)?void 0:i.latestLevelDetails,u=appendedFragAtPosition(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,n=e.nextStart;if(r&&n){var i=r.getFragAtPos(t,PlaylistLevelType.MAIN),a=r.getFragAtPos(n,PlaylistLevelType.MAIN);if(i&&a)return a.sn-i.sn<2}return!1}},{key:"_reportStall",value:function(e){var t=this.hls,r=this.media,n=this.stallReported,i=this.stalled;if(!n&&null!==i&&r&&t){this.stallReported=!0;var a=new Error("Playback stalling at @".concat(r.currentTime," due to low buffer (").concat(stringify(e),")"));this.warn(a.message),t.trigger(Events$2.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:i}})}}},{key:"_trySkipBufferHole",value:function(e){var t=this.fragmentTracker,r=this.media,n=this.hls,i=null==n?void 0:n.config;if(!r||!t||!i)return 0;var a=r.currentTime,s=BufferHelper.bufferInfo(r,a,0);withInterstitialBoundary(s,a,t,n);var o=a<s.start?s.start:s.nextStart;if(o){var l=s.len<=i.maxBufferHole,u=s.len>0&&s.len<1&&r.readyState<3,c=o-a;if(c>0&&(l||u)){if(c>i.maxBufferHole){var d=!1;if(0===a){var h=t.getAppendedFrag(0,PlaylistLevelType.MAIN);h&&o<h.end&&(d=!0)}if(!d&&e){var f;if(null==(f=n.loadLevelObj)||!f.details)return 0;if(getInFlightDependency(n.inFlightFragments,o))return 0;for(var v=!1,p=e.end;p<o;){var g=appendedFragAtPosition(p,t),y=g?g.duration:0;if(!(y>0)){v=!0;break}p+=y}if(v)return 0}}var m=i.nudgeMaxRetry,E=i.skipBufferHolePadding,S=++this.skipRetry>m,T=Math.max(o,a)+E;if(S||(this.warn("skipping hole, adjusting currentTime from ".concat(a," to ").concat(T)),this.moved=!0,r.currentTime=T),null==e||!e.gap||S){var k=new Error(S?"Playhead still not moving after seeking over buffer hole from ".concat(a," to ").concat(T," after ").concat(i.nudgeMaxRetry," attempts."):"fragment loaded with buffer holes, seeking from ".concat(a," to ").concat(T)),_={type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_SEEK_OVER_HOLE,fatal:S,error:k,reason:k.message,buffer:s.len,bufferInfo:s};e&&("fragment"in e?_.part=e:_.frag=e),n.trigger(Events$2.ERROR,_)}return T}}return 0}},{key:"_tryNudgeBuffer",value:function(e){var t=this.hls,r=this.media,n=this.nudgeRetry,i=null==t?void 0:t.config;if(!r||!i)return 0;var a=r.currentTime;if(this.nudgeRetry++,n<i.nudgeMaxRetry){var s=a+(n+1)*i.nudgeOffset,o=new Error("Nudging 'currentTime' from ".concat(a," to ").concat(s));this.warn(o.message),r.currentTime=s,t.trigger(Events$2.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.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(i.nudgeMaxRetry," nudges"));this.error(l.message),t.trigger(Events$2.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_STALLED_ERROR,error:l,fatal:!0,buffer:e.len,bufferInfo:e})}}}])}();function getInFlightDependency(e,t){var r=inFlight(e.main);if(r&&r.start<=t)return r;var n=inFlight(e.audio);return n&&n.start<=t?n:null}function inFlight(e){if(!e)return null;switch(e.state){case State.IDLE:case State.STOPPED:case State.ENDED:case State.ERROR:return null}return e.frag}function appendedFragAtPosition(e,t){return t.getAppendedFrag(e,PlaylistLevelType.MAIN)||t.getPartialFragment(e)}function withInterstitialBoundary(e,t,r,n){var i=n.latestLevelDetails,a=appendedFragAtPosition(t,r);if(interstitialsEnabled(n.config)&&!e.nextStart&&i&&a&&n.interstitialsManager){var s="type"in a?a:a.fragment,o=getNextFrag(i,s.sn);(null==o?void 0:o.level)===s.level&&fragOverlapsQueuedInterstitial(o,n.interstitialsManager.playerQueue,t)&&(e.nextStart=o.start)}}var MIN_CUE_DURATION=.25;function getCueClass(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function createCueWithDataFields(e,t,r,n,i){var a=new e(t,r,"");try{a.value=n,i&&(a.type=i)}catch(s){a=new e(t,r,stringify(i?_objectSpread2({type:i},n):n))}return a}var MAX_CUE_ENDTIME=function(){var e=getCueClass();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY}(),ID3TrackController=function(){return _createClass(function e(t){var r=this;_classCallCheck(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(Events$2.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(Events$2.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Events$2.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Events$2.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events$2.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events$2.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(Events$2.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Events$2.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Events$2.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}},{key:"_unregisterListeners",value:function(){var e=this.hls;e&&(e.off(Events$2.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Events$2.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Events$2.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events$2.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events$2.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(Events$2.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Events$2.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Events$2.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}},{key:"onMediaAttaching",value:function(e,t){this.media=t.media}},{key:"onMediaAttached",value:function(){var e,t=null==(e=this.hls)?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}},{key:"onMediaDetaching",value:function(e,t){this.media=null,!!t.transferMedia||(this.id3Track&&(this.id3Track.remove(),this.id3Track=null),this.dateRangeCuesAppended={})}},{key:"onManifestLoading",value:function(){this.dateRangeCuesAppended={}}},{key:"createTrack",value:function(e){return createTrackNode(e,"metadata","id3","","hidden")}},{key:"onFragParsingMetadata",value:function(e,t){if(this.media&&this.hls){var r=this.hls.config,n=r.enableEmsgMetadataCues,i=r.enableID3MetadataCues;if(n||i){var a=t.samples;this.id3Track||(this.id3Track=this.createTrack(this.media));var s=getCueClass();if(s)for(var o=0;o<a.length;o++){var l=a[o].type;if((l!==MetadataSchema.emsg||n)&&i){var u=getId3Frames(a[o].data),c=a[o].pts,d=c+a[o].duration;d>MAX_CUE_ENDTIME&&(d=MAX_CUE_ENDTIME),d-c<=0&&(d=c+MIN_CUE_DURATION);for(var h=0;h<u.length;h++){var f=u[h];if(!isId3TimestampFrame(f)){this.updateId3CueEnds(c,l);var v=createCueWithDataFields(s,c,d,f,l);v&&this.id3Track.track.addCue(v)}}}}}}}},{key:"updateId3CueEnds",value:function(e,t){var r,n=null==(r=this.id3Track)?void 0:r.track.cues;if(n)for(var i=n.length;i--;){var a=n[i];a.type===t&&a.startTime<e&&a.endTime===MAX_CUE_ENDTIME&&(a.endTime=e)}}},{key:"onBufferFlushing",value:function(e,t){var r=t.startOffset,n=t.endOffset,i=t.type,a=this.id3Track,s=this.hls;if(s){var o,l=s.config,u=l.enableEmsgMetadataCues,c=l.enableID3MetadataCues;if(a&&(u||c))o="audio"===i?function(e){return e.type===MetadataSchema.audioId3&&c}:"video"===i?function(e){return e.type===MetadataSchema.emsg&&u}:function(e){return e.type===MetadataSchema.audioId3&&c||e.type===MetadataSchema.emsg&&u},removeCuesInRange(a.track,r,n,o)}}},{key:"onLevelUpdated",value:function(e,t){var r=t.details;this.updateDateRangeCues(r,!0)}},{key:"onLevelPtsUpdated",value:function(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}},{key:"updateDateRangeCues",value:function(e,t){var r=this;if(this.hls&&this.media){var n=this.hls.config,i=n.assetPlayerId,a=n.timelineOffset,s=n.enableDateRangeMetadataCues,o=n.interstitialsController;if(s){var l=getCueClass();if(i&&a&&!o){var u=e.fragmentStart,c=e.fragmentEnd,d=this.assetCue;d?(d.startTime=u,d.endTime=c):l&&(d=this.assetCue=createCueWithDataFields(l,u,c,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"))&&(d.id=i,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.track.addCue(d),d.addEventListener("enter",this.onEventCueEnter))}if(e.hasProgramDateTime){var h,f=this.id3Track,v=e.dateRanges,p=Object.keys(v),g=this.dateRangeCuesAppended;if(f&&t)if(null!=(h=f.track.cues)&&h.length)for(var y,m=Object.keys(g).filter(function(e){return-1===p.indexOf(e)}),E=function(){var e=m[S],t=null==(y=g[e])?void 0:y.cues;delete g[e],t&&Object.keys(t).forEach(function(e){var n=t[e];if(n){n.removeEventListener("enter",r.onEventCueEnter);try{f.track.removeCue(n)}catch(i){}}})},S=m.length;S--;)E();else g=this.dateRangeCuesAppended={};var T=e.fragments[e.fragments.length-1];if(0!==p.length&&isFiniteNumber(null==T?void 0:T.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(var k=function(){var e=p[_],t=v[e],n=t.startTime,i=g[e],a=(null==i?void 0:i.cues)||{},s=(null==i?void 0:i.durationKnown)||!1,u=MAX_CUE_ENDTIME,c=t.duration;if(t.endDate&&null!==c)u=n+c,s=!0;else if(t.endOnNext&&!s){var d=p.reduce(function(e,r){if(r!==t.id){var n=v[r];if(n.class===t.class&&n.startDate>t.startDate&&(!e||t.startDate<e.startDate))return n}return e},null);d&&(u=d.startTime,s=!0)}for(var h=Object.keys(t.attr),f=0;f<h.length;f++){var y=h[f];if(isDateRangeCueAttribute(y)){var m=a[y];if(m)!s||null!=i&&i.durationKnown?Math.abs(m.startTime-n)>.01&&(m.startTime=n,m.endTime=u):m.endTime=u;else if(l){var E=t.attr[y];isSCTE35Attribute(y)&&(E=hexToArrayBuffer(E));var S=createCueWithDataFields(l,n,u,{key:y,data:E},MetadataSchema.dateRange);S&&(S.id=e,r.id3Track.track.addCue(S),a[y]=S,o&&("X-ASSET-LIST"!==y&&"X-ASSET-URL"!==y||S.addEventListener("enter",r.onEventCueEnter)))}}}g[e]={cues:a,dateRange:t,durationKnown:s}},_=0;_<p.length;_++)k()}}}}}}])}();function getSourceBuffer(){return self.SourceBuffer||self.WebKitSourceBuffer}function _isMSESupported(){if(!_getMediaSource2())return!1;var e=getSourceBuffer();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}function _isSupported(){if(!_isMSESupported())return!1;var e=_getMediaSource2();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(mimeTypeForCodec(t,"video"))})||["mp4a.40.2","fLaC"].some(function(t){return e.isTypeSupported(mimeTypeForCodec(t,"audio"))}))}function changeTypeSupported(){var e,t=getSourceBuffer();return"function"==typeof(null==t||null==(e=t.prototype)?void 0:e.changeType)}var HlsIFramesOnlyClass,HlsImageIFramesOnlyClass,AlternateAudio={DISABLED:0,SWITCHING:1,SWITCHED:2},TICK_INTERVAL$1=100,StreamController=function(){function e(t,r,n){var i;return _classCallCheck(this,e),(i=_callSuper(this,e,[t,r,n,"stream-controller",PlaylistLevelType.MAIN])).audioCodecSwap=!1,i.level=-1,i._forceStartLoad=!1,i._hasEnoughToStart=!1,i.altAudio=AlternateAudio.DISABLED,i.audioOnly=!1,i._couldBacktrack=!1,i._backtrackFragment=void 0,i.audioCodecSwitch=!1,i.videoBuffer=null,i.onMediaPlaying=function(){i.tick()},i.onMediaSeeked=function(){var e=i.media,t=e?e.currentTime:null;if(null!==t&&isFiniteNumber(t)&&(i.log("Media seeked to ".concat(t)),i.getBufferedFrag(t))){var r=i.getFwdBufferInfoAtPos(e,t,PlaylistLevelType.MAIN,0);r&&0!==r.len?i.tick():i.log("Main buffer empty at ".concat(t,' on "seeked" event: ').concat(r?r.len:r))}},i.registerListeners(),i}return _inherits(e,BaseStreamController),_createClass(e,[{key:"registerListeners",value:function(){_superPropGet(e,"registerListeners",this)([]);var t=this.hls;t.on(Events$2.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Events$2.LEVEL_LOADING,this.onLevelLoading,this),t.on(Events$2.LEVEL_LOADED,this.onLevelLoaded,this),t.on(Events$2.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(Events$2.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(Events$2.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(Events$2.BUFFER_CREATED,this.onBufferCreated,this),t.on(Events$2.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(Events$2.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(Events$2.FRAG_BUFFERED,this.onFragBuffered,this)}},{key:"unregisterListeners",value:function(){_superPropGet(e,"unregisterListeners",this)([]);var t=this.hls;t.off(Events$2.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Events$2.LEVEL_LOADED,this.onLevelLoaded,this),t.off(Events$2.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(Events$2.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(Events$2.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(Events$2.BUFFER_CREATED,this.onBufferCreated,this),t.off(Events$2.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(Events$2.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(Events$2.FRAG_BUFFERED,this.onFragBuffered,this)}},{key:"onHandlerDestroying",value:function(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),_superPropGet(e,"onHandlerDestroying",this)([])}},{key:"startLoad",value:function(e,t){if(this.levels){var r=this.lastCurrentTime,n=this.hls;if(this.stopLoad(),this.setInterval(TICK_INTERVAL$1),this.level=-1,!this.startFragRequested){var i=n.startLevel;-1===i&&(n.config.testBandwidth&&this.levels.length>1?(i=0,this.bitrateTest=!0):i=n.firstAutoLevel),n.nextLoadLevel=i,this.level=n.loadLevel,this._hasEnoughToStart=!!t}r>0&&-1===e&&!t&&this.initPTS.length&&(this.log("Override startPosition with lastCurrentTime @".concat(r)),e=r),this.state=State.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,t||this.fragmentTracker.hasFragments(this.playlistType)||(this._hasEnoughToStart=this.startFragRequested=!1),this.tick()}else this._forceStartLoad=!0,this.state=State.STOPPED}},{key:"stopLoad",value:function(){this._forceStartLoad=!1,_superPropGet(e,"stopLoad",this)([])}},{key:"doTick",value:function(){switch(this.state){case State.WAITING_LEVEL:var e=this.levels,t=this.level,r=null==e?void 0:e[t],n=null==r?void 0:r.details;if(n&&(!n.live||this.levelLastLoaded===r&&!this.waitForLive(r))){if(this.waitForCdnTuneIn(n))break;this.state=State.IDLE;break}if(this.hls.nextLoadLevel!==this.level){this.state=State.IDLE;break}break;case State.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate()}this.state===State.IDLE&&this.doTickIdle(),this.onTickEnd()}},{key:"onTickEnd",value:function(){var t;_superPropGet(e,"onTickEnd",this)([]),null!=(t=this.media)&&t.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,n=this.media;if(null!==t&&(n||this.primaryPrefetch||!this.startFragRequested&&e.config.startFragPrefetch)&&(!this.altAudio||!this.audioOnly)){var i=this.buffering?e.nextLoadLevel:e.loadLevel;if(null!=r&&r[i]){var a=r[i],s=this.getMainFwdBufferInfo();if(null!==s){var o=this.getLevelDetails();if(o&&this._streamEnded(s,o)){var l={type:this.targetBufferType()};return this.hls.trigger(Events$2.BUFFER_EOS,l),void(this.state=State.ENDED)}if(this.buffering){e.loadLevel!==i&&-1===e.manualLevel&&this.log("Adapting to level ".concat(i," from level ").concat(this.level)),this.level=e.nextLoadLevel=i;var u=a.details;if(!u||this.state===State.WAITING_LEVEL||this.waitForLive(a))return this.level=i,this.state=State.WAITING_LEVEL,void(this.startFragRequested=!1);var c=s.len,d=this.getMaxBufferLength(a.maxBitrate);if(!(c>=d)){this.backtrackFragment&&this.backtrackFragment.start>s.end&&(this.backtrackFragment=void 0);var h=this.backtrackFragment?this.backtrackFragment.start:s.end,f=this.getNextFragment(h,u);if(this.couldBacktrack&&!this.fragPrevious&&f&&isMediaFragment(f)&&this.fragmentTracker.getState(f)!==FragmentState.OK){var v,p=(null!=(v=this.backtrackFragment)?v:f).sn-u.startSN,g=u.fragments[p-1];g&&f.cc===g.cc&&(f=g,this.fragmentTracker.removeFragment(g))}else this.backtrackFragment&&s.len&&(this.backtrackFragment=void 0);if(f&&this.isLoopLoading(f,h)){if(!f.gap){var y=this.audioOnly&&!this.altAudio?ElementaryStreamTypes.AUDIO:ElementaryStreamTypes.VIDEO,m=(y===ElementaryStreamTypes.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;m&&this.afterBufferFlushed(m,y)}f=this.getNextFragmentLoopLoading(f,u,s,PlaylistLevelType.MAIN,d)}f&&(this.exceedsMaxBuffer(s,d,f)||this.loadFragment(f,a,h))}}}}}}},{key:"loadFragment",value:function(t,r,n){var i=this.fragmentTracker.getState(t);i===FragmentState.NOT_LOADED||i===FragmentState.PARTIAL?this.bitrateTest?(this.log("Fragment ".concat(t.sn," of level ").concat(t.level," is being downloaded to test bitrate and will not be buffered")),this._loadBitrateTestFrag(t,r)):_superPropGet(e,"loadFragment",this)([t,r,n]):this.clearTrackerIfNeeded(t)}},{key:"immediateLevelSwitch",value:function(){var t;(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==AlternateAudio.DISABLED)&&(((null==(t=this.getLevelDetails())?void 0:t.fragmentStart)||0)>this.lastCurrentTime&&_superPropGet(e,"flushMainBuffer",this)([0,Number.POSITIVE_INFINITY,"audio"]))}},{key:"getBufferOutput",value:function(){return this.mediaBuffer&&this.altAudio===AlternateAudio.SWITCHED?this.mediaBuffer:this.media}},{key:"checkFragmentChanged",value:function(){var e=this.fragPlaying;if(!this.checkFragPlaying())return!1;var t=this.fragPlaying;if(t){var r=t.level;this.hls.trigger(Events$2.FRAG_CHANGED,{frag:t,previousFrag:e}),(null==e?void 0:e.level)!==r&&this.hls.trigger(Events$2.LEVEL_SWITCHED,{level:r})}return!0}},{key:"backtrackFragment",get:function(){return this._backtrackFragment},set:function(e){this._backtrackFragment=e}},{key:"couldBacktrack",get:function(){return this._couldBacktrack},set:function(e){this._couldBacktrack=e}},{key:"abortCurrentFrag",value:function(){this.backtrackFragment=void 0,_superPropGet(e,"abortCurrentFrag",this)([])}},{key:"flushMainBuffer",value:function(t,r){_superPropGet(e,"flushMainBuffer",this)([t,r,this.targetBufferType()])}},{key:"targetBufferType",value:function(){return this.altAudio!==AlternateAudio.SWITCHED||this.audioOnly?null:"video"}},{key:"onMediaAttached",value:function(t,r){_superPropGet(e,"onMediaAttached",this)([t,r]);var n=r.media;addEventListener(n,"playing",this.onMediaPlaying),addEventListener(n,"seeked",this.onMediaSeeked)}},{key:"onMediaDetaching",value:function(t,r){var n=this.media;n&&(removeEventListener(n,"playing",this.onMediaPlaying),removeEventListener(n,"seeked",this.onMediaSeeked)),this.videoBuffer=null,_superPropGet(e,"onMediaDetaching",this)([t,r]),!!r.transferMedia||(this._hasEnoughToStart=!1)}},{key:"onManifestLoading",value:function(){_superPropGet(e,"onManifestLoading",this)([]),this.log("Trigger BUFFER_RESET"),this.hls.trigger(Events$2.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.backtrackFragment=void 0,this.altAudio=AlternateAudio.DISABLED,this.audioOnly=!1}},{key:"onManifestParsed",value:function(e,t){for(var r=!1,n=!1,i=0;i<t.levels.length;i++){var a=t.levels[i].audioCodec;a&&(r=r||-1!==a.indexOf("mp4a.40.2"),n=n||-1!==a.indexOf("mp4a.40.5"))}this.audioCodecSwitch=r&&n&&!changeTypeSupported(),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===State.IDLE){var r=t.levelInfo;(!r.details||r.details.live&&(this.levelLastLoaded!==r||r.details.expired)||this.waitForCdnTuneIn(r.details))&&(this.state=State.WAITING_LEVEL)}}},{key:"onLevelLoaded",value:function(e,t){var r,n=this,i=this.levels,a=this.startFragRequested,s=t.level,o=t.details,l=o.totalduration;if(i){this.log("Level ".concat(s," loaded [").concat(o.startSN,",").concat(o.endSN,"]").concat(o.lastPartSn?"[part-".concat(o.lastPartSn,"-").concat(o.lastPartIndex,"]"):"",", cc [").concat(o.startCC,", ").concat(o.endCC,"] duration:").concat(l));var u=t.levelInfo,c=this.fragCurrent;!c||this.state!==State.FRAG_LOADING&&this.state!==State.FRAG_LOADING_WAITING_RETRY||c.level!==t.level&&c.loader&&this.abortCurrentFrag();var d=0;if(o.live||null!=(r=u.details)&&r.live){var h;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;d=this.alignPlaylists(o,u.details,null==(h=this.levelLastLoaded)?void 0:h.details)}if(u.details=o,this.levelLastLoaded=u,a||this.setStartPosition(o,d),this.hls.trigger(Events$2.LEVEL_UPDATED,{details:o,level:s}),this.state===State.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=State.IDLE}a&&o.live&&this.synchronizeToLiveEdge(o),this.initPTS.some(function(e,t){if(t>=o.startCC)return!0;delete n.initPTS[t]}),this.tick()}else this.warn("Levels were reset while loading level ".concat(s))}},{key:"synchronizeToLiveEdge",value:function(e){var t=this.config,r=this.media;if(r){var n=this.hls.liveSyncPosition,i=this.playhead,a=e.fragmentStart,s=e.edge,o=i>=a-t.maxFragLookUpTolerance&&i<=s;if(null!==n&&r.duration>n&&(i<n||!o)){var l=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!o&&r.readyState<4||i<s-l)&&(this._hasEnoughToStart||(this.nextLoadPosition=n),r.readyState))if(this.warn("Playback: ".concat(i," is located too far from the end of live sliding playlist: ").concat(s,", reset currentTime to : ").concat(n)),"buffered"===this.config.liveSyncMode){var u,c=BufferHelper.bufferInfo(r,n,0);if(null==(u=c.buffered)||!u.length)return void(r.currentTime=n);if(c.start<=i)return void(r.currentTime=n);var d=BufferHelper.bufferedInfo(c.buffered,i,0).nextStart;d&&(r.currentTime=d)}else r.currentTime=n}}}},{key:"_handleFragmentLoadProgress",value:function(e){var t,r=e.frag,n=e.part,i=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 TransmuxerInterface(this.hls,PlaylistLevelType.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=n?n.index:-1,v=-1!==f,p=getAESAdjustments(r,n,this.iframesOnly),g=p.decryptRange,y=p.byteRange,m=new ChunkMetadata(r.level,r.sn,r.stats.chunkCount,y?y.end-y.start:i.byteLength,f,v,r.duration,this.iframesOnly,g),E=this.initPTS[r.cc];h.push(i,c,d,l,r,n,o.totalduration,u,m,E)}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,n=this.hls,i=this.altAudio!==AlternateAudio.DISABLED;if(useAlternateAudio(t.url,n))this.altAudio=AlternateAudio.SWITCHING;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(i)return this.altAudio=AlternateAudio.DISABLED,this.fragmentTracker.removeAllFragments(),n.once(Events$2.BUFFER_FLUSHED,function(){r.hls&&r.hls.trigger(Events$2.AUDIO_TRACK_SWITCHED,t)}),void n.trigger(Events$2.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});n.trigger(Events$2.AUDIO_TRACK_SWITCHED,t)}}},{key:"onAudioTrackSwitched",value:function(e,t){var r=useAlternateAudio(t.url,this.hls);if(r){var n=this.videoBuffer;n&&this.mediaBuffer!==n&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=n)}this.altAudio=r?AlternateAudio.SWITCHED:AlternateAudio.DISABLED,this.tick()}},{key:"onBufferCreated",value:function(e,t){var r,n,i=t.tracks,a=!1;for(var s in i){var o=i[s];if("main"===o.id){if(n=s,r=o,"video"===s){var l=i[s];l&&(this.videoBuffer=l.buffer)}}else a=!0}a&&r?(this.log("Alternate track found, use ".concat(n,".buffered to schedule main fragment loading")),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}},{key:"onFragBuffered",value:function(e,t){var r=t.frag,n=t.part,i=r.type===PlaylistLevelType.MAIN;if(i){if(this.fragContextChanged(r))return this.warn("Fragment ".concat(r.sn).concat(n?" p: "+n.index:""," of level ").concat(r.level," finished buffering, but was aborted. state: ").concat(this.state)),void(this.state===State.PARSED&&(this.state=State.IDLE));var a=!1;if(isMediaFragment(r)&&(a=!!r.gap&&!r.tagList.some(function(e){return"GAP"===e[0]})),this.fragBufferedComplete(r,n),a){var s;r.stats.retry++;var o=null==(s=this.levels)?void 0:s[r.level];o&&o.fragmentError++}}var l=this.media;l&&(!this._hasEnoughToStart&&BufferHelper.getBuffered(l).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),i&&this.tick())}},{key:"hasEnoughToStart",get:function(){return this._hasEnoughToStart}},{key:"onError",value:function(e,t){var r;if(t.fatal)this.state=State.ERROR;else switch(t.details){case ErrorDetails.FRAG_GAP:case ErrorDetails.FRAG_PARSING_ERROR:case ErrorDetails.FRAG_DECRYPT_ERROR:case ErrorDetails.FRAG_LOAD_ERROR:case ErrorDetails.FRAG_LOAD_TIMEOUT:case ErrorDetails.KEY_LOAD_ERROR:case ErrorDetails.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(PlaylistLevelType.MAIN,t);break;case ErrorDetails.LEVEL_LOAD_ERROR:case ErrorDetails.LEVEL_LOAD_TIMEOUT:case ErrorDetails.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==State.WAITING_LEVEL||(null==(r=t.context)?void 0:r.type)!==LoaderContextType.LEVEL||(this.state=State.IDLE);break;case ErrorDetails.BUFFER_APPEND_NO_PROGRESS:if("main"!==t.parent)return;t.frag&&(t.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn("Marking fragment ".concat(t.frag.sn," of level ").concat(t.frag.level," as a gap after ").concat(t.appendsWithoutProgress," appends without buffered range growth, to prevent loop loading")),this.fragmentTracker.addAsGap(t.frag));break;case ErrorDetails.BUFFER_ADD_CODEC_ERROR:case ErrorDetails.BUFFER_APPEND_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case ErrorDetails.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 ErrorDetails.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}},{key:"onFragLoadEmergencyAborted",value:function(){this.state=State.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}},{key:"onBufferFlushed",value:function(e,t){var r=t.type;if(r!==ElementaryStreamTypes.AUDIO||!this.altAudio){var n=(r===ElementaryStreamTypes.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;n&&(this.afterBufferFlushed(n,r),this.tick())}}},{key:"onLevelsUpdated",value:function(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}},{key:"swapAudioCodec",value:function(){this.audioCodecSwap=!this.audioCodecSwap}},{key:"seekToStartPos",value:function(){var e=this.media;if(e){var t=e.currentTime,r=this.startPosition;if(r>=0&&t<r){if(e.seeking)return void this.log("could not seek to ".concat(r,", already seeking at ").concat(t));var n=this.timelineOffset;n&&r&&(r+=n);var i=this.getLevelDetails(),a=BufferHelper.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==i?void 0:i.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 n=r.hls,i=null==e?void 0:e.frag;if(i&&!r.fragContextChanged(i)){t.fragmentError=0,r.state=State.IDLE,r.startFragRequested=!1,r.bitrateTest=!1;var a=i.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),n.trigger(Events$2.FRAG_LOADED,e),i.bitrateTest=!1}}).catch(function(t){r.state!==State.STOPPED&&r.state!==State.ERROR&&(r.warn(t),r.resetFragmentLoading(e))})}},{key:"_handleTransmuxComplete",value:function(e){var t=this.playlistType,r=this.hls,n=e.remuxResult,i=e.chunkMeta,a=this.getCurrentContext(i);if(a){var s=a.frag,o=a.part,l=a.level,u=n.video,c=n.text,d=n.id3,h=n.initSegment,f=l.details,v=this.altAudio?void 0:n.audio;if(this.fragContextChanged(s))this.fragmentTracker.removeFragment(s);else{if(this.state=State.PARSING,h){var p=h.tracks;if(p){var g=s.initSegment||s;if(this.unhandledEncryptionError(h,s))return;this._bufferInitSegment(l,p,g,i),r.trigger(Events$2.FRAG_PARSING_INIT_SEGMENT,{frag:g,id:t,tracks:p})}var y=h.initPTS,m=h.timescale,E=this.initPTS[s.cc];if(isFiniteNumber(y)&&(!E||E.baseTime!==y||E.timescale!==m)){var S=h.trackId;this.initPTS[s.cc]={baseTime:y,timescale:m,trackId:S};var T=this.initPTS.slice(0);r.trigger(Events$2.INIT_PTS_FOUND,{timestampOffsets:T,frag:s,id:t,initPTS:y,timescale:m,trackId:S})}}if(u&&f){v&&"audiovideo"===u.type&&this.logMuxedErr(s);var k=f.fragments[s.sn-1-f.startSN],_=s.sn===f.startSN,A=!k||s.cc>k.cc;if(!1!==n.independent){var b=u.startPTS,L=u.endPTS,R=u.startDTS,C=u.endDTS;if(o)o.elementaryStreams[u.type]={startPTS:b,endPTS:L,startDTS:R,endDTS:C};else if(u.firstKeyFrame&&u.independent&&1===i.id&&!A&&(this.couldBacktrack=!0),u.dropped&&u.independent){var I=this.getMainFwdBufferInfo(),P=(I?I.end:this.getLoadPosition())+this.config.maxBufferHole,D=u.firstKeyFramePTS?u.firstKeyFramePTS:b;if(!_&&P<D-this.config.maxBufferHole&&!A)return void this.backtrack(s);A&&(s.gap=!0),s.setElementaryStreamInfo(u.type,s.start,L,s.start,C,!0)}else _&&b-(f.appliedTimelineOffset||0)>MAX_START_GAP_JUMP&&(s.gap=!0);s.setElementaryStreamInfo(u.type,b,L,R,C),this.backtrackFragment&&(this.backtrackFragment=s),this.bufferFragmentData(u,s,o,i,_||A)}else{if(!_&&!A)return void this.backtrack(s);s.gap=!0}}if(v){var w=v.startPTS,O=v.endPTS,x=v.startDTS,M=v.endDTS;o&&(o.elementaryStreams[ElementaryStreamTypes.AUDIO]={startPTS:w,endPTS:O,startDTS:x,endDTS:M}),s.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO,w,O,x,M),this.bufferFragmentData(v,s,o,i)}if(f&&null!=d&&d.samples.length){var F={id:t,frag:s,details:f,samples:d.samples};r.trigger(Events$2.FRAG_PARSING_METADATA,F)}if(f&&c){var N={id:t,frag:s,details:f,samples:c.samples};r.trigger(Events$2.FRAG_PARSING_USERDATA,N)}}}else this.resetWhenMissingContext(i)}},{key:"logMuxedErr",value:function(e){this.warn("".concat(isMediaFragment(e)?"Media":"Init"," segment with muxed audiovideo where only video expected: ").concat(e.url))}},{key:"_bufferInitSegment",value:function(e,t,r,n){var i=this;if(this.state===State.PARSING){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=pickMostCompleteCodecName(a.codec,l);if("mp4a"===u&&(u="mp4a.40.5"),this.audioCodecSwitch){u&&(u=-1!==u.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");var c=a.metadata;c&&"channelCount"in c&&1!==(c.channelCount||1)&&!userAgentFirefoxVersion()&&(u="mp4a.40.5")}u&&-1!==u.indexOf("mp4a.40.5")&&userAgentIsAndroidLike()&&"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=PlaylistLevelType.MAIN,this.log("Init audio buffer, container:".concat(a.container,", codecs[selected/level/parsed]=[").concat(u||"","/").concat(l||"","/").concat(a.codec,"]")),delete t.audiovideo}if(s){s.levelCodec=e.videoCodec,s.id=PlaylistLevelType.MAIN;var d=s.codec;if(4===(null==d?void 0:d.length))switch(d){case"hvc1":case"hev1":s.codec="hvc1.1.6.L120.90";break;case"av01":s.codec="av01.0.04M.08";break;case"avc1":s.codec="avc1.42e01e"}this.log("Init video buffer, container:".concat(s.container,", codecs[level/parsed]=[").concat(e.videoCodec||"","/").concat(d,"]").concat(s.codec!==d?" parsed-corrected="+s.codec:"").concat(s.supplemental?" supplemental="+s.supplemental:"")),delete t.audiovideo}o&&(this.iframesOnly&&this.logMuxedErr(r),this.log("Init audiovideo buffer, container:".concat(o.container,", codecs[level/parsed]=[").concat(e.codecs,"/").concat(o.codec,"]")),delete t.video,delete t.audio);var h=Object.keys(t);if(h.length){if(this.hls.trigger(Events$2.BUFFER_CODECS,t),!this.hls)return;h.forEach(function(e){var a=t[e].initSegment;null!=a&&a.byteLength&&i.hls.trigger(Events$2.BUFFER_APPENDING,{type:e,data:a,frag:r,part:null,chunkMeta:n,parent:r.type})})}this.tickImmediate()}}},{key:"getMainFwdBufferInfo",value:function(){var e=this.getBufferOutput();return this.getFwdBufferInfo(e,PlaylistLevelType.MAIN)}},{key:"maxBufferLength",get:function(){var e=this.levels,t=this.level,r=null==e?void 0:e[t];return r?this.getMaxBufferLength(r.maxBitrate):this.config.maxBufferLength}},{key:"backtrack",value:function(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=State.IDLE}},{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 isFiniteNumber(t)?this.getAppendedFrag(t):null}},{key:"currentProgramDateTime",get:function(){var e,t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if(isFiniteNumber(t)){var r=this.getLevelDetails(),n=this.currentFrag||(r?findFragmentByPTS(null,r.fragments,t):null);if(n){var i=n.programDateTime;if(null!==i){var a=i+1e3*(t-n.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}}])}(),IFrameStreamController=function(){function e(){var t;_classCallCheck(this,e);for(var r=arguments.length,n=new Array(r),i=0;i<r;i++)n[i]=arguments[i];return(t=_callSuper(this,e,[].concat(n))).currentOp=void 0,t.nextOp=void 0,t.cached=[],t.cachedSize=0,t.cacheFragmentData=!0,t.initDetails=void 0,t.onBufferedToEnd=function(){var e=t.media;null!=e&&e.seeking&&(e.currentTime=e.currentTime)},t.onMediaSeeking=function(){},t}return _inherits(e,StreamController),_createClass(e,[{key:"setInitPts",value:function(e){this.initPTS=e.slice()}},{key:"loadMediaAt",value:function(e,t){if(this.hls){var r=t.seekOnAppend,n=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=n,this.startPosition=e,this.state){case State.STOPPED:case State.ENDED:case State.ERROR:this.state=State.IDLE}this.state===State.IDLE?(this.hls.resumeBuffering(),this.tick(),this.currentOp=[n,t]):this.nextOp=[n,t],this.hls.off(Events$2.BUFFERED_TO_END,this.onBufferedToEnd);var i=this.media;if(r&&i)this.seekTo(n)&&(this.currentOp=[n,t],this.nextOp=void 0,this.flushPipeline(n,!0))}}},{key:"seekTo",value:function(e){var t=this.media;if(t){var r,n=null==(r=this.getLevelDetails())?void 0:r.edge,i=void 0!==n?n:t.duration;if(e>=i&&(e=i-.01),BufferHelper.bufferInfo(t,e,0).len>0&&this.getBufferedAt(e))return t.currentTime=e,!0}return!1}},{key:"getBufferedAt",value:function(e){return this.fragmentTracker.getBufferedFrag(e,PlaylistLevelType.MAIN)}},{key:"cacheSet",value:function(e,t){if(this.hls){e.data=t;var r=this.cached;r.push(e),this.cachedSize+=t.buffer.byteLength;for(var n=this.hls.config.iframeCacheLimit;this.cachedSize>n&&r.length>1;){var i=r.shift();if(!i.data){this.cached=r.filter(function(e){return!!e.data}),this.cachedSize=r.reduce(function(e,t){var r=t.data;return r?r.buffer.byteLength:0},0);break}this.cachedSize-=i.data.byteLength,i.data=void 0}}}},{key:"onHandlerDestroying",value:function(){this.cached.length=0,this.cachedSize=0,_superPropGet(e,"onHandlerDestroying",this)([])}},{key:"_handleFragmentLoadProgress",value:function(t){var r=t.frag,n=t.part,i=t.payload;this.cacheFragmentData&&!n&&null!=i&&i.byteLength&&!r.data&&isMediaFragment(r)&&this.cacheSet(r,new Uint8Array(i.slice(0))),_superPropGet(e,"_handleFragmentLoadProgress",this)([t])}},{key:"loadFragment",value:function(t,r,n){var i=this.fragmentTracker.getState(t);i!==FragmentState.NOT_LOADED&&i!==FragmentState.PARTIAL||!this.canReplayCached(t)?_superPropGet(e,"loadFragment",this)([t,r,n]):this.replayCachedFragment(t)}},{key:"canReplayCached",value:function(e){var t;if(!this.cacheFragmentData||null==(t=e.data)||!t.byteLength)return!1;var r=e.decryptdata;return"identity"!==(null==r?void 0:r.keyFormat)||!!r.key}},{key:"replayCachedFragment",value:function(e){var t=e.data.slice().buffer;this.log("Buffering cached ".concat(e.type," sn: ").concat(e.sn," of level ").concat(e.level," (").concat(t.byteLength," bytes)")),this.fragCurrent=e,this.startFragRequested=!0;var r=e.stats=new LoadStats;r.loading.start=r.loading.first=r.loading.end=self.performance.now(),r.loaded=r.total=t.byteLength,r.chunkCount=1,this.state=State.FRAG_LOADING;var n={frag:e,part:null,payload:t,networkDetails:null};this._handleFragmentLoadProgress(n),this.hls.trigger(Events$2.FRAG_LOADED,n),this._handleFragmentLoadComplete(n)}},{key:"fragBufferedComplete",value:function(t,r){_superPropGet(e,"fragBufferedComplete",this)([t,r]);var n=this.currentOp,i=this.nextOp;this.currentOp=this.nextOp=void 0,this.state=State.STOPPED,null!=n&&n[1].seekOnAppend&&(this.flushPipeline(n[0],!i),this.seekTo(n[0])||this.log("Could not seek to ".concat(n[0]," after fragment buffered (superseded or flushed) buffer: ").concat(this.media?timeRangesToString(BufferHelper.getBuffered(this.media)):"none"))),i&&this.loadMediaAt.apply(this,i)}},{key:"flushPipeline",value:function(e,t){if(t){var r=this.media;if(r){var n=BufferHelper.bufferInfo(r,e,0),i=n.len?n.nextStart:0;i&&(this.fragmentTracker.removeFragmentsInRange(i,1/0,PlaylistLevelType.MAIN),this.flushMainBuffer(i,1/0))}this.hls.once(Events$2.BUFFERED_TO_END,this.onBufferedToEnd)}this.hls.trigger(Events$2.BUFFER_EOS,{type:"video"})}},{key:"playhead",get:function(){return this.nextLoadPosition}},{key:"startLoad",value:function(){if(!this.startFragRequested){var e=this.hls;e.nextLoadLevel=-1===e.startLevel?0:e.firstAutoLevel}}},{key:"seekToStartPos",value:function(){}},{key:"setStartPosition",value:function(){}},{key:"alignPlaylists",value:function(t,r,n){var i=this.initDetails;return this.initDetails=null,_superPropGet(e,"alignPlaylists",this)([t,r,n||i||void 0])}},{key:"getMainFwdBufferInfo",value:function(){var e=this.playhead,t=this.getBufferedAt(e);if(t){var r=t.duration;return{len:r,start:e,end:e+r,bufferedIndex:-1}}return{len:0,start:e,end:e,bufferedIndex:-1}}},{key:"_streamEnded",value:function(){var e=this.playhead,t=this.fragmentTracker.getBufferedFrag(e,PlaylistLevelType.MAIN);return!(null==t||!t.endList)}}])}(),ImageIFrameStreamController=function(){function e(){var t;_classCallCheck(this,e);for(var r=arguments.length,n=new Array(r),i=0;i<r;i++)n[i]=arguments[i];return(t=_callSuper(this,e,[].concat(n)))._img=void 0,t.queued=void 0,t.cacheFragmentData=!1,t}return _inherits(e,IFrameStreamController),_createClass(e,[{key:"image",get:function(){return this._img},set:function(e){var t,r=null==(t=this._img)?void 0:t.src;r&&self.URL.revokeObjectURL(r),this._img=e}},{key:"loadMediaAt",value:function(e){if(this.hls){var t=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=t,this.startPosition=e,this.state){case State.STOPPED:case State.ENDED:case State.ERROR:this.state=State.IDLE}if(this.state===State.IDLE){if(this.hls.resumeBuffering(),this.media||(this.media={}),this.tick(),this.state===State.IDLE){var r=this.getBufferedAt(e);r&&(this.fragCurrent=r,this.updateImage(r,null))}}else{var n=this.fragCurrent;(!n||e>=n.start&&e<n.end)&&(this.queued=[t])}}}},{key:"updateImage",value:function(e,t,r){var n=this,i=e.data;i||this.fragmentTracker.removeFragment(e);var a=this._img;if(a&&i){var s=self.performance.now();(t?t.stats:e.stats).buffering.start=e.stats.buffering.start=s,a.onload=function(){if(n.hls){var i=n.hls.levels[e.level];null!=i&&i.fragmentError&&(i.fragmentError=0,e.stats.retry=0);var a=self.performance.now(),s=t?t.stats:e.stats;s.buffering.end=e.stats.buffering.end=a,n.hls.trigger(Events$2.FRAG_BUFFERED,{frag:e,part:t,stats:s,id:e.type,chunkMeta:r})}},a.onerror=function(){n.handleError("Image decode error",e,t,r)};var o=a.src;o&&self.URL.revokeObjectURL(o);var l=new Blob([i],{type:"image/jpeg"});a.src=self.URL.createObjectURL(l)}else this.state=State.STOPPED,this.processQueued()}},{key:"processQueued",value:function(){var e=this.queued;this.queued=void 0,e&&this.loadMediaAt.apply(this,e)}},{key:"handleError",value:function(e,t,r,n){if(this.hls){var i=new Error(e);this.hls.trigger(Events$2.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_PARSING_ERROR,chunkMeta:n,frag:t,part:r,fatal:!1,error:i,err:i})}}},{key:"_bufferInitSegment",value:function(){}},{key:"bufferFragmentData",value:function(t,r,n,i){_superPropGet(e,"bufferFragmentData",this)([t,r,n,i,!0]);var a=findBox(new Uint8Array(t.data1),["mdat"]);if(0!==a.length){var s=r;this.cacheSet(s,a[0]),this.updateImage(s,n,i)}else this.handleError("Could not find I-Frame mdat",r,n,i)}},{key:"fragBufferedComplete",value:function(t,r){this.fragmentTracker.fragBuffered(t,!0),_superPropGet(e,"fragBufferedComplete",this)([t,r]),this.processQueued()}},{key:"checkFragPlaying",value:function(){var e,t=null==(e=this.fragPrevious)?void 0:e.start;if(void 0!==t){var r=this.getAppendedFrag(t);if(r&&!mediaFragmentsAreEqual(r,this.fragPlaying))return this.fragPlaying=r,!0}return!1}},{key:"getMainFwdBufferInfo",value:function(){return{len:0,start:this.playhead,end:this.playhead,bufferedIndex:-1}}}])}(),PRELOAD_IFRAME_PLAYLISTS_AFTER_BUFFER_SECONDS=10,IMAGE_IFRAME_ATTACH_ERROR="Image I-Frame player does not accept HTMLMediaElements",loadMediaAtOptionsDefault={seekOnAppend:!0},IFrameController=function(){function e(t,r){var n;return _classCallCheck(this,e),(n=_callSuper(this,e,["iframes",t.logger])).hls=void 0,n.stats=void 0,n.variableList=null,n.initPTS=[],n.iframeInstances=void 0,n.instanceCounter=0,HlsIFramesOnlyClass||(HlsIFramesOnlyClass=createHlsIFramesOnly(r)),HlsImageIFramesOnlyClass||(HlsImageIFramesOnlyClass=createHlsImageIFramesOnly(HlsIFramesOnlyClass)),n.hls=t,n.iframeInstances=[],n.registerListeners(),n}return _inherits(e,Logger$1),_createClass(e,[{key:"registerListeners",value:function(){var e=this.hls;e&&(e.on(Events$2.MANIFEST_LOADING,this.clearAsset,this),e.on(Events$2.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Events$2.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Events$2.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(Events$2.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Events$2.DESTROYING,this.onDestroying,this))}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(Events$2.MANIFEST_LOADING,this.clearAsset,this),e.off(Events$2.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Events$2.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Events$2.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(Events$2.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Events$2.DESTROYING,this.onDestroying,this))}},{key:"clearAsset",value:function(){this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances.forEach(function(e){return e.destroy()}),this.iframeInstances.length=0}},{key:"onDestroying",value:function(){this.unregisterListeners(),this.clearAsset(),this.hls=void 0}},{key:"onManifestLoaded",value:function(e,t){this.stats=t.stats,this.variableList=t.variableList}},{key:"onLevelsUpdated",value:function(e,t){var r,n=t.levels,i=null==(r=this.hls)?void 0:r.pathwayPriority;n.length&&i&&this.iframeInstances.forEach(function(e){e.pathwayPriority=i})}},{key:"onInitPtsFound",value:function(e,t){var r=t.id,n=t.timestampOffsets;r===PlaylistLevelType.MAIN&&(this.initPTS=n)}},{key:"onFragBuffered",value:function(e,t){var r,n=this,i=this.hls;i&&i.hasEnoughToStart&&((null==(r=i.mainForwardBufferInfo)?void 0:r.len)||0)>PRELOAD_IFRAME_PLAYLISTS_AFTER_BUFFER_SECONDS&&this.iframeInstances.forEach(function(e){var t;e.loadingEnabled||e.startLoad((null==(t=n.hls)||null==(t=t.media)?void 0:t.currentTime)||0)})}},{key:"createIFramePlayer",value:function(e){var t;return this.createInstance(HlsIFramesOnlyClass,null==(t=this.hls)?void 0:t.iframeVariants,e)}},{key:"createImageIFramePlayer",value:function(e){var t,r=null==(t=this.hls)?void 0:t.iframeVariants.filter(function(e){return e.imageCodec});return this.createInstance(HlsImageIFramesOnlyClass,r,e,"image-")}},{key:"createInstance",value:function(e,t,r,n){var i=this.hls;if(!i)return null;var a=i.url,s=i.userConfig,o=i.latestLevelDetails,l=i.loadLevelObj,u=i.loadLevel,c=i.bandwidthEstimate,d=i.sessionId,h=this.stats,f=this.variableList;if(null==t||!t.length||!h||!a)return null;var v="".concat(n||"","iframe-player-").concat(this.instanceCounter++),p=i.levels,g=l||p[u],y=getVideoPreference(g,s.videoPreference),m=(null==g?void 0:g.pathwayId)||".",E=new e(_objectSpread2(_objectSpread2({},s),{},{loggerId:v,primarySessionId:d,videoPreference:y,abrEwmaDefaultEstimate:c,streamController:void 0,audioStreamController:void 0,audioTrackController:void 0,subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,id3TrackController:void 0,fpsController:void 0,gapController:void 0,iframeController:void 0,cmcd:void 0,interstitialsController:void 0,backBufferLength:1/0,maxMaxBufferLength:1,capLevelToPlayerSize:!0,enableWorker:!1,autoStartLoad:!1,startFragPrefetch:!1,testBandwidth:!1,progressive:!1},r),a,this.initPTS,o);return this.iframeInstances=this.iframeInstances.filter(function(e){return!e.url}),this.iframeInstances.push(E),E.trigger(Events$2.MANIFEST_LOADED,{levels:t,contentSteering:{uri:"",pathwayId:m},sessionKeys:null,audioTracks:[],iframeVariants:[],sessionData:null,startTimeOffset:null,stats:h,networkDetails:null,url:a,variableList:f}),E}}])}();function createHlsIFramesOnly(e){return function(e){function t(e,r,n,i){var a;return _classCallCheck(this,t),e.streamController||(e.streamController=IFrameStreamController),(a=_callSuper(this,t,[e]))._url=r,a.streamController.setInitPts(n),a.streamController.initDetails=i,a}return _inherits(t,e),_createClass(t,[{key:"loadSource",value:function(){}},{key:"loadMediaAt",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:loadMediaAtOptionsDefault;if(!(e<0)){var r=_objectSpread2(_objectSpread2({},loadMediaAtOptionsDefault),t);this.loadingEnabled||this.startLoad(e),this.streamController.loadMediaAt(e,r)}}}])}(e)}function createHlsImageIFramesOnly(e){return function(e){function t(e,r,n,i){return _classCallCheck(this,t),e.cmcdController=void 0,e.emeController=void 0,e.streamController||(e.streamController=ImageIFrameStreamController),e.capLevelController=void 0,e.bufferController=void 0,_callSuper(this,t,[e,r,n,i])}return _inherits(t,e),_createClass(t,[{key:"attachImage",value:function(e){this.streamController.image=e}},{key:"detachImage",value:function(){this.streamController.image=void 0}},{key:"loadSource",value:function(){}},{key:"attachMedia",value:function(){throw new Error(IMAGE_IFRAME_ATTACH_ERROR)}},{key:"detachMedia",value:function(){}},{key:"recoverMediaError",value:function(){}},{key:"transferMedia",value:function(){return null}},{key:"loadMediaAt",value:function(e){if(e<0)return null;this.loadingEnabled||this.startLoad(e),this.streamController.loadMediaAt(e)}}])}(e)}var ALIGNED_END_THRESHOLD_SECONDS=.025,TimelineOccupancy=function(e){return e[e.Point=0]="Point",e[e.Range=1]="Range",e}({});function generateAssetIdentifier(e,t,r){return"".concat(e.identifier,"-").concat(r+1,"-").concat(hash(t))}var InterstitialEvent=function(){return _createClass(function e(t,r){_classCallCheck(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 fragmentRefCoversTime(t,e)?getSnapToFragmentTime(e,t):e}return e}},{key:"startOffset",get:function(){return this.cue.pre?0:this.startTime}},{key:"startIsAligned",get:function(){if(0===this.startTime||this.snapOptions.out)return!0;var e=this.dateRange.tagAnchor;if(e){var t=this.dateRange.startTime;return t-getSnapToFragmentTime(t,e)<.1}return!1}},{key:"resumptionOffset",get:function(){var e=this.resumeOffset,t=isFiniteNumber(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 fragmentRefCoversTime(t,e)?getSnapToFragmentTime(e,t):e}return e}},{key:"appendInPlace",get:function(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||!this.startIsAligned||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<ALIGNED_END_THRESHOLD_SECONDS))},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"]?TimelineOccupancy.Range:TimelineOccupancy.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 eventToString(this)}}])}();function getSnapToFragmentTime(e,t){return e-t.start<t.duration/2&&!(Math.abs(e-(t.start+t.duration))<ALIGNED_END_THRESHOLD_SECONDS)?t.start:t.start+t.duration}function fragmentRefCoversTime(e,t){return t>e.start-ALIGNED_END_THRESHOLD_SECONDS&&t<e.start+e.duration+ALIGNED_END_THRESHOLD_SECONDS}function getInterstitialUrl(e,t,r){var n=new self.URL(e,r);return"data:"!==n.protocol&&setQueryParam(n,"_HLS_primary_id",t),n}function getNextAssetIndex(e,t){for(;null!=(r=e.assetList[++t])&&r.error;)var r;return t}function eventToString(e){return'["'.concat(e.identifier,'" ').concat(e.cue.pre?"<pre>":e.cue.post?"<post>":"").concat(e.timelineStart.toFixed(2),"-").concat(e.resumeTime.toFixed(2),"]")}function eventAssetToString(e){var t=e.timelineStart,r=e.duration||0;return'["'.concat(e.identifier,'" ').concat(t.toFixed(2),"-").concat((t+r).toFixed(2),"]")}var HlsAssetPlayer=function(){return _createClass(function e(t,r,n,i){var a=this;_classCallCheck(this,e),this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=function(){a.reachedPlayout(a.currentTime)&&a.hls&&a.hls.trigger(Events$2.PLAYOUT_LIMIT_REACHED,{})};var s=this.hls=new t(r);this.interstitial=n,this.assetItem=i;var o=function(){a.hasDetails=!0};s.once(Events$2.LEVEL_LOADED,o),s.once(Events$2.AUDIO_TRACK_LOADED,o),s.once(Events$2.SUBTITLE_TRACK_LOADED,o),s.on(Events$2.MEDIA_ATTACHING,function(e,t){var r=t.media;a.removeMediaListeners(),a.mediaAttached=r,a.interstitial.playoutLimit&&(r.addEventListener("timeupdate",a.checkPlayout),a.appendInPlace&&s.on(Events$2.BUFFER_APPENDED,function(){var e=a.bufferedEnd;a.reachedPlayout(e)&&(a._bufferedEosTime=e,s.trigger(Events$2.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=getInterstitialUrl(t,e.config.primarySessionId||"").href}catch(r){}e.loadSource(t)}}},{key:"bufferedInPlaceToEnd",value:function(e,t){var r;if(!this.appendInPlace)return!1;if(null!=(r=this.hls)&&r.bufferedToEnd)return!0;if(!e)return!1;var n=Math.min(this._bufferedEosTime||1/0,this.duration),i=this.timelineOffset+(t||0),a=BufferHelper.bufferInfo(e,i,.02);return this.getAssetTime(a.end)>=n-.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=BufferHelper.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 n;null==(n=this.hls)||n.on(e,t)}},{key:"once",value:function(e,t,r){var n;null==(n=this.hls)||n.once(e,t)}},{key:"off",value:function(e,t,r){var n;null==(n=this.hls)||n.off(e,t)}},{key:"toString",value:function(){var e;return"HlsAssetPlayer: ".concat(eventAssetToString(this.assetItem)," ").concat(null==(e=this.hls)?void 0:e.sessionId," ").concat(this.appendInPlace?"append-in-place":"")}}])}(),ABUTTING_THRESHOLD_SECONDS=.033,InterstitialsSchedule=function(){function e(t,r){var n;return _classCallCheck(this,e),(n=_callSuper(this,e,["interstitials-sched",r])).onScheduleUpdate=void 0,n.eventMap={},n.events=null,n.items=null,n.durations={primary:0,playout:0,integrated:0},n.onScheduleUpdate=t,n}return _inherits(e,Logger$1),_createClass(e,[{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,n){return e<=n.startOffset&&t>n.startOffset?(delete n.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 n=this.items;if(n)for(n[r]||(void 0===t&&(t=e.start),r=this.findItemIndexAtTime(t));r>=0&&null!=(i=n[r])&&i.event;){var i;r--}return r}},{key:"findItemIndexAtTime",value:function(e,t){var r=this.items;if(r)for(var n=0;n<r.length;n++){var i=r[n];t&&"primary"!==t&&(i=i[t]);var a=i.start,s=r[n].event,o=null!=s&&s.cue.pre?s.duration:i.end;if(e===a||e>a&&e<o)return n}return-1}},{key:"findJumpRestrictedIndex",value:function(e,t){var r=this.items;if(r)for(var n=e;n<=t&&r[n];n++){var i=r[n].event;if(null!=i&&i.restrictions.jump&&!i.appendInPlace)return n}return-1}},{key:"findEventIndex",value:function(e){var t=this.items;if(t)for(var r=t.length;r--;){var n;if((null==(n=t[r].event)?void 0:n.identifier)===e)return r}return-1}},{key:"findAssetIndex",value:function(e,t){var r=e.assetList,n=r.length;if(n>1)for(var i=0;i<n;i++){var a=r[i];if(!a.error){var s=a.timelineStart;if(t===s||t>s&&(t<s+(a.duration||0)||i===n-1))return i}}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,n=r[r.length-1];if(n)return n.identifier}return null}},{key:"parseInterstitialDateRanges",value:function(e,t){var r=this,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,i=e.main.details,a=i.dateRanges,s=this.events,o=this.parseDateRanges(a,{url:i.url},t),l=Object.keys(a),u=s?s.filter(function(e){return-1===l.indexOf(e.identifier)}):[];o.length&&o.sort(function(e,t){var r=e.cue.pre,n=e.cue.post,i=t.cue.pre,a=t.cue.post;if(r&&!i)return-1;if(i&&!r)return 1;if(n&&!a)return 1;if(a&&!n)return-1;if(!(r||i||n||a)){var s=e.startTime,o=t.startTime;if(s!==o)return s-o}return e.dateRange.tagOrder-t.dateRange.tagOrder}),this.events=o,u.forEach(function(e){r.removeEvent(e)}),this.updateSchedule(e,u,n)}},{key:"updateSchedule",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],i=this.events||[];if(i.length||t.length||this.length<2){var a=this.items,s=this.parseSchedule(i,e,r);(n||t.length||(null==a?void 0:a.length)!==s.length||s.some(function(e,t){return Math.abs(e.playout.start-a[t].playout.start)>.005||Math.abs(e.playout.end-a[t].playout.end)>.005}))&&(this.items=s,this.onScheduleUpdate(t,a))}}},{key:"parseDateRanges",value:function(e,t,r){for(var n=[],i=Object.keys(e),a=0;a<i.length;a++){var s=i[a],o=e[s];if(o.isInterstitial){var l=this.eventMap[s];l?l.setDateRange(o):(l=new InterstitialEvent(o,t),this.eventMap[s]=l,!1===r&&(l.appendInPlace=r)),n.push(l)}}return n}},{key:"parseSchedule",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,n=[],i=t.main.details,a=i.live?1/0:i.edge,s=0;if((e=e.filter(function(e){return!(e.error||e.cue.once&&e.hasPlayed)})).length){this.resolveOffsets(e,t);var o=0,l=0;if(e.forEach(function(t,u){var c=t.cue.pre,d=t.cue.post,h=e[u-1]||null,f=t.appendInPlace,v=d?a:t.startOffset,p=t.duration,g=t.timelineOccupancy===TimelineOccupancy.Range?p:0,y=c&&i.live?r+(t.resumeOffset||0):0,m=y||t.resumptionOffset,E=(null==h?void 0:h.startTime)===v,S=v+t.cumulativeDuration,T=f?S+p:v+m;if(c||!d&&v<=0){var k=l;l+=g,t.timelineStart=S;var _=s;s+=p,n.push({event:t,start:S,end:T,playout:{start:_,end:s},integrated:{start:k,end:l}})}else{if(!(v<=a))return;if(!E){var A=v-o;if(A>ABUTTING_THRESHOLD_SECONDS){var b=o,L=l;l+=A;var R=s;s+=A;var C={previousEvent:e[u-1]||null,nextEvent:t,start:b,end:b+A,playout:{start:R,end:s},integrated:{start:L,end:l}};n.push(C)}else A>0&&h&&(h.cumulativeDuration+=A,n[n.length-1].end=v)}d&&(T=S),t.timelineStart=S;var I=l;l+=g;var P=s;s+=p,n.push({event:t,start:S,end:T,playout:{start:P,end:s},integrated:{start:I,end:l}})}var D=y||t.resumeTime;o=d||D>a?a:!c&&T&&t.appendInPlaceStarted&&D-T>ABUTTING_THRESHOLD_SECONDS?T:D}),o<a){var u,c=o,d=l,h=a-o;l+=h;var f=s;s+=h,n.push({previousEvent:(null==(u=n[n.length-1])?void 0:u.event)||null,nextEvent:null,start:o,end:c+h,playout:{start:f,end:s},integrated:{start:d,end:l}})}this.setDurations(a,s,l)}else{n.push({previousEvent:null,nextEvent:null,start:0,end:a,playout:{start:0,end:a},integrated:{start:0,end:a}}),this.setDurations(a,a,a)}return n}},{key:"setDurations",value:function(e,t,r){this.durations={primary:e,playout:t,integrated:r}}},{key:"resolveOffsets",value:function(e,t){var r=this,n=t.main.details,i=n.live?1/0:n.edge,a=0,s=-1;e.forEach(function(o,l){var u=o.cue.pre,c=o.cue.post,d=u?0:c?i:o.startTime;(r.updateAssetDurations(o),s===d?o.cumulativeDuration=a:(a=0,s=d),!c&&o.snapOptions.in&&(o.resumeAnchor=findFragmentByPTS(null,n.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<ABUTTING_THRESHOLD_SECONDS&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&r.warn("Could not change append strategy for abutting event ".concat(o))));var h=isFiniteNumber(o.resumeOffset)?o.resumeOffset:o.duration;a+=h})}},{key:"primaryCanResumeInPlaceAt",value:function(e,t){var r=this,n=e.resumeTime,i=e.startTime+e.resumptionOffset;return Math.abs(n-i)>ALIGNED_END_THRESHOLD_SECONDS?(this.log('"'.concat(e.identifier,'" resumption ').concat(n," not aligned with estimated timeline end ").concat(i)),!1):!Object.keys(t).some(function(i){var a=t[i].details,s=a.edge;if(n>=s)return r.log('"'.concat(e.identifier,'" resumption ').concat(n," past ").concat(i," playlist end ").concat(s)),!1;var o=findFragmentByPTS(null,a.fragments,n);if(!o)return r.log('"'.concat(e.identifier,'" resumption ').concat(n," does not align with any fragments in ").concat(i," playlist (").concat(a.fragStart,"-").concat(a.fragmentEnd,")")),!0;var l="audio"===i?.175:0;return!(Math.abs(o.start-n)<ALIGNED_END_THRESHOLD_SECONDS+l||Math.abs(o.end-n)<ALIGNED_END_THRESHOLD_SECONDS+l)&&(r.log('"'.concat(e.identifier,'" resumption ').concat(n," not aligned with ").concat(i," 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,n=!1,i=!1,a=0;a<e.assetList.length;a++){var s=e.assetList[a],o=t+r;s.startOffset=r,s.timelineStart=o,n||(n=null===s.duration),i||(i=!!s.error),r+=s.error?0:s.duration||0}e.duration=n&&!i?Math.max(r,e.duration):r}}},{key:"removeEvent",value:function(e){e.reset(),delete this.eventMap[e.identifier]}}])}();function segmentToString(e){return"[".concat(e.event?'"'+e.event.identifier+'"':"primary",": ").concat(e.start.toFixed(2),"-").concat(e.end.toFixed(2),"]")}var AssetListLoader=function(){return _createClass(function e(t){_classCallCheck(this,e),this.hls=void 0,this.hls=t},[{key:"destroy",value:function(){this.hls=null}},{key:"loadAssetList",value:function(e,t){var r,n=this,i=e.assetListUrl;try{r=getInterstitialUrl(i,this.hls.sessionId,e.baseUrl)}catch(h){var a=this.assignAssetListError(e,ErrorDetails.ASSET_LIST_LOAD_ERROR,h,i);return void this.hls.trigger(Events$2.ERROR,a)}t&&"data:"!==r.protocol&&setQueryParam(r,"_HLS_start_offset",""+t);var s=this.hls.config,o=new(0,s.loader)(s),l={type:LoaderContextType.INTERSTITIAL_ASSET_LIST,responseType:"json",url:r.href},u=s.interstitialAssetListLoadPolicy.default,c={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:function(t,r,i,a){var s=t.data,o=null==s?void 0:s.ASSETS;if(Array.isArray(o))e.assetListResponse=s,n.hls.trigger(Events$2.ASSET_LIST_LOADED,{event:e,assetListResponse:s,networkDetails:a});else{var l=n.assignAssetListError(e,ErrorDetails.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),i.url,r,a);n.hls.trigger(Events$2.ERROR,l)}},onError:function(t,r,i,a){var s=n.assignAssetListError(e,ErrorDetails.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,i);n.hls.trigger(Events$2.ERROR,s)},onTimeout:function(t,r,i){var a=n.assignAssetListError(e,ErrorDetails.ASSET_LIST_LOAD_TIMEOUT,new Error("Timeout loading X-ASSET-LIST (".concat(r.url,")")),r.url,t,i);n.hls.trigger(Events$2.ERROR,a)}};return o.load(l,c,d),this.hls.trigger(Events$2.ASSET_LIST_LOADING,{event:e}),o}},{key:"assignAssetListError",value:function(e,t,r,n,i,a){return e.error=r,{type:ErrorTypes.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:n,error:r,networkDetails:a,stats:i}}}])}();function playWithCatch(e){var t;null==e||null==(t=e.play())||t.catch(function(){})}function timelineMessage(e,t){return"[".concat(e,"] Advancing timeline position to ").concat(t)}var InterstitialsController=function(){function e(t,r){var n;return _classCallCheck(this,e),(n=_callSuper(this,e,["interstitials",t.logger])).HlsPlayerClass=void 0,n.hls=void 0,n.assetListLoader=void 0,n.mediaSelection=null,n.altSelection=null,n.media=null,n.detachedData=null,n.requiredTracks=null,n.manager=null,n.playerQueue=[],n.bufferedPos=-1,n.timelinePos=-1,n.schedule=void 0,n.playingItem=null,n.bufferingItem=null,n.waitingItem=null,n.endedItem=null,n.playingAsset=null,n.endedAsset=null,n.bufferingAsset=null,n.bufferPastEdge=!1,n.shouldPlay=!1,n.onPlay=function(){n.shouldPlay=!0},n.onPause=function(){n.shouldPlay=!1},n.onSeeking=function(){var e=n.currentTime;if(void 0!==e&&!n.playbackDisabled&&n.schedule){var t=e-n.timelinePos;if(!(Math.abs(t)<1/7056e5)){var r=t<=-.01;-1!==n.timelinePos||n.effectivePlayingItem||n.checkStart(),n.timelinePos=e,n.bufferedPos=e;var i=n.playingItem;if(i){if(r)n.schedule.resetErrorsInRange(e,e-t)&&n.updateSchedule(!0);if(n.checkBuffer(),r&&e<i.start||e>=i.end){var a,s=n.findItemIndex(i),o=n.schedule.findItemIndexAtTime(e);if(-1===o&&(o=s+(r?-1:1),n.log("seeked ".concat(r?"back ":"","to position not covered by schedule ").concat(e," (resolving from ").concat(s," to ").concat(o,")"))),!n.isInterstitial(i)&&null!=(a=n.media)&&a.paused&&(n.shouldPlay=!1),!r&&o>s){var l=n.schedule.findJumpRestrictedIndex(s+1,o);if(l>s)return void n.setSchedulePosition(l)}n.setSchedulePosition(o)}else{var u=n.playingAsset;if(u){var c,d=u.timelineStart,h=u.duration||0;if(r&&e<d||e>=d+h)null!=(c=i.event)&&c.appendInPlace&&(n.clearAssetPlayers(i.event,i),n.flushFrontBuffer(e)),n.setScheduleToAssetAtTime(e,u)}else if(n.playingLastItem&&n.isInterstitial(i)){var f=i.event.assetList[0];f&&(n.endedItem=n.playingItem,n.playingItem=null,n.setScheduleToAssetAtTime(e,f))}}}else n.checkBuffer()}}},n.onTimeupdate=function(){var e=n.currentTime;if(void 0!==e&&!n.playbackDisabled&&(-1!==n.timelinePos||n.effectivePlayingItem||n.checkStart(),e>n.timelinePos)){n.timelinePos=e,e>n.bufferedPos&&n.checkBuffer();var t=n.playingItem;if(t&&!n.playingLastItem){if(e>=t.end){n.timelinePos=t.end;var r=n.findItemIndex(t);n.setSchedulePosition(r+1)}var i=n.playingAsset;if(i)e>=i.timelineStart+(i.duration||0)&&n.setScheduleToAssetAtTime(e,i)}}},n.onScheduleUpdate=function(e,t){var r=n.schedule;if(r){var i=n.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)&&n.log("INTERSTITIALS_UPDATED (".concat(a.length,"): ").concat(a,"\nSchedule: ").concat(s.map(function(e){return segmentToString(e)})," pos: ").concat(n.timelinePos)),l.length&&n.log("Removed events ".concat(l));var c=null,d=null;i&&(c=n.updateItem(i,n.timelinePos),n.itemsMatch(i,c)?n.playingItem=c:n.waitingItem=null),n.waitingItem=n.updateItem(n.waitingItem);var h=n.bufferingItem;if(h&&(d=n.updateItem(h,n.bufferedPos),n.itemsMatch(h,d)?n.bufferingItem=d:h.event&&(n.bufferingItem=n.playingItem,n.clearInterstitial(h.event,null))),e.forEach(function(e){e.assetList.forEach(function(e){n.clearAssetPlayer(e.identifier,null)})}),n.playerQueue.forEach(function(e){if(e.interstitial.appendInPlace){var t=e.assetItem.timelineStart,r=e.timelineOffset-t;if(r)try{e.timelineOffset=t}catch(i){Math.abs(r)>ALIGNED_END_THRESHOLD_SECONDS&&n.warn("".concat(i,' ("').concat(e.assetId,'" ').concat(e.timelineOffset,"->").concat(t,")"))}}}),u||t){if(n.hls.trigger(Events$2.INTERSTITIALS_UPDATED,{events:a.slice(0),schedule:s.slice(0),durations:o,removedIds:l}),n.isInterstitial(i)&&l.indexOf(i.event.identifier)>-1)return n.warn('Interstitial "'.concat(i.event.identifier,'" removed while playing')),void n.primaryFallback(i.event);i&&n.trimInPlace(c,i),h&&d!==c&&n.trimInPlace(d,h),n.checkBuffer()}}},n.hls=t,n.HlsPlayerClass=r,n.assetListLoader=new AssetListLoader(t),n.schedule=new InterstitialsSchedule(n.onScheduleUpdate,t.logger),n.registerListeners(),n}return _inherits(e,Logger$1),_createClass(e,[{key:"registerListeners",value:function(){var e=this.hls;e&&(e.on(Events$2.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Events$2.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Events$2.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events$2.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events$2.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Events$2.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Events$2.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(Events$2.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(Events$2.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(Events$2.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(Events$2.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(Events$2.BUFFER_APPENDED,this.onBufferAppended,this),e.on(Events$2.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Events$2.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(Events$2.MEDIA_ENDED,this.onMediaEnded,this),e.on(Events$2.ERROR,this.onError,this),e.on(Events$2.DESTROYING,this.onDestroying,this))}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(Events$2.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Events$2.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Events$2.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events$2.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events$2.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Events$2.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Events$2.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(Events$2.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(Events$2.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(Events$2.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(Events$2.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(Events$2.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Events$2.BUFFER_APPENDED,this.onBufferAppended,this),e.off(Events$2.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Events$2.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(Events$2.MEDIA_ENDED,this.onMediaEnded,this),e.off(Events$2.ERROR,this.onError,this),e.off(Events$2.DESTROYING,this.onDestroying,this))}},{key:"startLoad",value:function(){this.resumeBuffering()}},{key:"stopLoad",value:function(){this.pauseBuffering()}},{key:"resumeBuffering",value:function(){var e;null==(e=this.getBufferingPlayer())||e.resumeBuffering()}},{key:"pauseBuffering",value:function(){var e;null==(e=this.getBufferingPlayer())||e.pauseBuffering()}},{key:"destroy",value:function(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}},{key:"onDestroying",value:function(){var e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}},{key:"removeMediaListeners",value:function(e){removeEventListener(e,"play",this.onPlay),removeEventListener(e,"pause",this.onPause),removeEventListener(e,"seeking",this.onSeeking),removeEventListener(e,"timeupdate",this.onTimeupdate)}},{key:"onMediaAttaching",value:function(e,t){var r=this.media=t.media;addEventListener(r,"seeking",this.onSeeking),addEventListener(r,"timeupdate",this.onTimeupdate),addEventListener(r,"play",this.onPlay),addEventListener(r,"pause",this.onPause)}},{key:"onMediaAttached",value:function(e,t){var r=this.effectivePlayingItem,n=this.detachedData;if(this.detachedData=null,null===r)this.checkStart();else if(!n){this.clearScheduleState();var i=this.findItemIndex(r);this.setSchedulePosition(i)}}},{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,n=this.media;if(this.media=null,!r&&(n&&this.removeMediaListeners(n),this.detachedData)){var i=this.getBufferingPlayer();i&&(this.log("Removing schedule state for detachedData and ".concat(i)),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,i.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},n=function(t,n,a,s,o){if(t){var l=t[n].start,u=t.event;if(u){if("playout"===n||u.timelineOccupancy!==TimelineOccupancy.Point){var c=r(a);(null==c?void 0:c.interstitial)===u&&(l+=c.assetItem.startOffset+c[o])}}else l+=("bufferedPos"===s?i():e[s])-t.start;return l}return 0},i=function(){var t=e.bufferedPos;return t===Number.MAX_VALUE?a("primary"):Math.max(t,0)},a=function(t){var r,n;return null!=(r=e.primaryDetails)&&r.live?e.primaryDetails.edge:(null==(n=e.schedule)?void 0:n.durations[t])||0},s=function(t,i){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(i,'"'));var l=e.effectivePlayingItem,u=e.schedule.findItemIndexAtTime(t,i),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 p=r(e.playingAsset),g=(null==p?void 0:p.media)||e.primaryMedia;if(g){var y="primary"===i?g.currentTime:n(l,i,e.playingAsset,"timelinePos","currentTime"),m=t-y,E=(f?y:g.currentTime)+m;if(E>=0&&(!p||f||E<=p.duration))return void(g.currentTime=E)}}if(c){var S=t;if("primary"!==i){var T=t-c[i].start;S=c.start+T}var k=!e.isInterstitial(c);if(e.isInterstitial(l)&&!l.event.appendInPlace||!k&&!c.event.appendInPlace){if(l){var _=e.findItemIndex(l);if(u>_){var A=e.schedule.findJumpRestrictedIndex(_+1,u);if(A>_)return void e.setSchedulePosition(A)}var b=0;if(k)e.timelinePos=S,e.checkBuffer();else for(var L=c.event.assetList,R=t-(c[i]||c).start,C=L.length;C--;){var I=L[C];if(I.duration&&R>=I.startOffset&&R<I.startOffset+I.duration){b=C;break}}e.setSchedulePosition(u,b)}}else{var P=e.media||(f?null==d?void 0:d.media:null);P&&(P.currentTime=S)}}}},o=function(){var r=e.effectivePlayingItem;if(e.isInterstitial(r))return r;var n=t();return e.isInterstitial(n)?n:null},l={get bufferedEnd(){var r,i=t(),a=e.bufferingItem;return a&&a===i&&(n(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?n(r,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-r.playout.start:0},set currentTime(t){var r=o(),n=e.effectivePlayingItem;n&&n===r&&s(t+n.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 i()},get currentTime(){var t=e.timelinePos;return t>0?t:0},set currentTime(e){s(e,"primary")},get duration(){return a("primary")},get seekableStart(){return e.seekableStart}},integrated:{get bufferedEnd(){return n(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return n(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(e){s(e,"integrated")},get duration(){return a("integrated")},get seekableStart(){return function(t,r){var n;if(0!==t&&"primary"!==r&&null!=(n=e.schedule)&&n.length){var i,a=e.schedule.findItemIndexAtTime(t),s=null==(i=e.schedule.items)?void 0:i[a];if(s)return t+(s[r].start-s.start)}return t}(e.seekableStart,"integrated")}},skip:function(){var t=e.effectivePlayingItem,r=null==t?void 0:t.event;if(r&&!r.restrictions.skip){var n=e.findItemIndex(t);if(r.appendInPlace){var i=t.playout.start+t.event.duration;s(i+.001,"playout")}else e.advanceAfterAssetEnded(r,n,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 n=this.media;!n&&null!=(e=this.bufferingItem)&&null!=(e=e.event)&&e.appendInPlace&&(n=this.primaryMedia);var i=null==(t=n)?void 0:t.currentTime;if(void 0!==i&&isFiniteNumber(i))return i}}}},{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,n=e.media;if(r&&n===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&n)return void(this.detachedData={media:n});var i=e.transferMedia();this.log("transfer MediaSource from ".concat(e," ").concat(stringify(i))),this.detachedData=i}else t&&n&&(this.shouldPlay||(this.shouldPlay=!n.paused))}},{key:"transferMediaTo",value:function(e,t){var r,n,i=this;if(e.media!==t){var a,s=null,o=this.hls,l=e!==o,u=l&&e.interstitial.appendInPlace,c=null==(r=this.detachedData)?void 0:r.mediaSource;if(o.media)u&&(s=o.transferMedia(),this.detachedData=s),a="Primary";else{var d=this.getBufferingPlayer();d?(s=d.transferMedia(),this.detachedData=s,a="".concat(d)):a=c?"detached MediaSource":"detached media"}if(!s)if(c)s=this.detachedData,this.log("using detachedData: MediaSource ".concat(stringify(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;i.clearInterstitial(e.interstitial,null),t.appendInPlace=!1,t.appendInPlace&&i.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==(n=s.mediaSource)?void 0:n.readyState);if(this.log("".concat(f?"transfering MediaSource":"attaching media"," to ").concat(l?e:"Primary"," from ").concat(a," (media.currentTime: ").concat(t.currentTime,")")),f||l){var v=f&&s?_objectSpread2({},s):{media:t},p=this.schedule;if(p&&l){var g=e.assetId===p.assetIdAtEnd;v.overrides={duration:p.duration,endOfStream:g||!1===e.appendInPlace}}if(!f&&u){var y=e,m=y.assetItem.timelineStart;if(m){var E=y.hls,S=Math.max(this.timelinePos-m,Number.EPSILON);E.startPosition!==S&&(this.log("Set ".concat(y," startPosition: ").concat(S)),E.config.startPosition=S,E.loadingEnabled&&E.startLoad(S))}}e.attachMedia(v)}else e.attachMedia(t)}}},{key:"onInterstitialCueEnter",value:function(){this.onTimeupdate()}},{key:"checkStart",value:function(){var e=this.schedule,t=null==e?void 0:e.events,r=this.hls;if(t&&!this.playbackDisabled&&this.media&&r){-1===this.bufferedPos&&(this.bufferedPos=0);var n=this.timelinePos,i=this.effectivePlayingItem;if(-1===n){if(!r.loadingEnabled)return void this.log("waiting for startLoad( <startPosition> )");var a=r.startPosition;if(this.timelinePos=a,0===t.length)this.setSchedulePosition(0);else if(t[0].cue.pre){this.log(timelineMessage("checkStart (preroll)",a));var s=e.findEventIndex(t[0].identifier);this.setSchedulePosition(s)}else if(a>=0||!this.primaryLive){this.log(timelineMessage("checkStart",a));var o=this.timelinePos=a>0?a:0,l=e.findItemIndexAtTime(o);this.setSchedulePosition(l)}else 0===r.liveSyncPosition?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(i&&!this.playingItem){this.log(timelineMessage("checkStart (playing item)",i.start));var u=e.findItemIndex(i);this.setSchedulePosition(u)}}}},{key:"advanceAssetBuffering",value:function(e,t){var r=e.event,n=r.findAssetIndex(t),i=getNextAssetIndex(r,n);if(r.isAssetPastPlayoutLimit(i)){if(this.schedule){var a,s=this.getNextItemIndex(e,!0),o=null==(a=this.schedule.items)?void 0:a[s];o&&this.bufferedToItem(o)}}else this.bufferedToEvent(e,i)}},{key:"livePrerollResumption",value:function(e,t){if(e.cue.pre&&this.primaryLive&&!isFiniteNumber(e.resumeOffset)&&this.hls){var r=this.getLiveStartPos();if(t){var n=this.getBufferingPlayer();return r+(null!=n&&n.interstitial.cue.pre?n.remaining:0)}return r}}},{key:"getNextItemIndex",value:function(e,t){if(this.schedule){var r=this.livePrerollResumption(e.event,t);if(void 0!==r)return this.log("find next item index @".concat(r)),this.schedule.findItemIndexAtTime(r)}return this.findItemIndex(e)+1}},{key:"advanceAfterAssetEnded",value:function(e,t,r){var n=getNextAssetIndex(e,r);if(e.isAssetPastPlayoutLimit(n)){if(this.schedule){var i=this.schedule.items;if(i){var a=i[t],s=a.event?this.getNextItemIndex(a):t+1;if(s>=i.length)return void this.setSchedulePosition(-1);var o=e.resumeTime;this.timelinePos<o&&(this.log(timelineMessage("advanceAfterAssetEnded",o)),this.timelinePos=o,e.appendInPlace&&!i[s].event&&this.hls.startLoad(o+.01),this.checkBuffer(this.bufferedPos<o)),this.setSchedulePosition(s)}}}else{if(e.appendInPlace){var l=e.assetList[n];l&&this.advanceInPlace(l.timelineStart)}this.setSchedulePosition(t,n)}}},{key:"setScheduleToAssetAtTime",value:function(e,t){var r=this.schedule;if(r){var n=t.parentIdentifier,i=r.getEvent(n);if(i){var a=r.findEventIndex(n),s=r.findAssetIndex(i,e);this.advanceAfterAssetEnded(i,a,s-1)}}}},{key:"setSchedulePosition",value:function(e,t){var r,n=null==(r=this.schedule)?void 0:r.items;if(n&&!this.playbackDisabled){var i=e>=0?n[e]:null;this.log("setSchedulePosition ".concat(e,", ").concat(t," (").concat(i?segmentToString(i):i,") 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,i)||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(eventAssetToString(l))),this.endedAsset=l,this.playingAsset=null,this.hls.trigger(Events$2.INTERSTITIAL_ASSET_ENDED,{asset:l,assetListIndex:h,event:o,schedule:n.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,i),!c.media||null!=(d=this.detachedData)&&d.mediaSource||c.detachMedia()}if(!this.eventItemsMatch(a,i)&&(this.endedItem=a,this.playingItem=this.waitingItem=null,this.log("INTERSTITIAL_ENDED ".concat(o," ").concat(segmentToString(a))),o.hasPlayed=!0,this.hls.trigger(Events$2.INTERSTITIAL_ENDED,{event:o,schedule:n.slice(0),scheduleIndex:e}),o.cue.once&&this.hls)){var f;this.updateSchedule();var v=null==(f=this.schedule)?void 0:f.items;if(i&&v){var p=this.findItemIndex(i),g=this.livePrerollResumption(o);if(void 0!==g){var y=g,m=this.getNextItemIndex(a);if(!this.isInterstitial(n[m])){var E,S=null==(E=this.primaryDetails)?void 0:E.fragments;if(o.snapOptions.in&&S){var T=findFragmentByPTS(null,S,g);T&&(y=Math.min(Math.max(n[m].start,getSnapToFragmentTime(y,T)),n[m].end))}}if(this.log(timelineMessage("live join (preroll)",y)),this.timelinePos=y,m!==p&&(m||0===m))return void this.advanceSchedule(m,v,void 0,a,s)}this.advanceSchedule(p,v,t,a,s)}return}}this.advanceSchedule(e,n,t,a,s)}}},{key:"advanceSchedule",value:function(e,t,r,n,i){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,n=s.findEventIndex(r.identifier);(n<e||n>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=getNextAssetIndex(c,(r=c.cue.pre?0:s.findAssetIndex(c,this.timelinePos))-1);if(c.isAssetPastPlayoutLimit(d)||c.appendInPlace&&this.timelinePos===o.end)return void this.advanceAfterAssetEnded(c,e,r);r=d}var h=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);var f=this.preloadAssets(c,r);if(this.eventItemsMatch(o,h||n)||(this.waitingItem=o,this.log("INTERSTITIAL_STARTED ".concat(segmentToString(o)," ").concat(c.appendInPlace?"append in place":"")),c.hasPlayed=!1,this.hls.trigger(Events$2.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 p=c.assetList.length;this.warn("asset ".concat(r+1,"/").concat(p," 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&&playWithCatch(f.media)}else o?(this.resumePrimary(o,e,n),this.shouldPlay&&playWithCatch(this.hls.media)):i&&this.isInterstitial(n)&&(this.endedItem=null,this.playingItem=n,n.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 n,i;this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=null,this.bufferedToItem(e),this.endedItem=null,this.log("resuming ".concat(segmentToString(e)));var a=this.timelinePos;if(null!=(n=this.detachedData)&&n.mediaSource?this.primaryLive&&this.startLoadingPrimaryAt(a):((a<e.start||a>=e.end||a<this.seekableStart)&&(a=this.getPrimaryResumption(e,t),this.log(timelineMessage("resumePrimary",a)),this.timelinePos=a),this.attachPrimary(a,e)),r){var s=null==(i=this.schedule)?void 0:i.items;s&&(this.log("INTERSTITIALS_PRIMARY_RESUMED ".concat(segmentToString(e))),this.hls.trigger(Events$2.INTERSTITIALS_PRIMARY_RESUMED,{schedule:s.slice(0),scheduleIndex:t}),this.checkBuffer())}}},{key:"seekableStart",get:function(){var e;return this.primaryLive&&(null==(e=this.primaryDetails)?void 0:e.fragmentStart)||0}},{key:"getPrimaryResumption",value:function(e,t,r){var n=e.start;if(this.primaryLive){if(0===t)return this.hls.startPosition;var i=this.endedItem||this.playingItem,a=null!=i&&i.event?this.livePrerollResumption(i.event,r):void 0;if(void 0!==a)return a;var s=this.primaryDetails;if(s){var o=s.fragmentStart,l=s.edge;if(n<o||n>l&&!r){var u=this.hls.liveSyncPosition;return this.log("primary resumption out of bounds (".concat(n," [").concat(o,"-").concat(l,"]) snapping to liveSync ").concat(u)),u||o}}}return this.log("primary resumption itemStart: ".concat(n)),n}},{key:"getLiveStartPos",value:function(){var e,t=this.hls.startPosition,r=this.hls.liveSyncPosition||0,n=3*((null==(e=this.primaryDetails)?void 0:e.targetduration)||10);return-1===t||r&&r-t<n?r||0:t}},{key:"isAssetBuffered",value:function(e){var t=this.getAssetPlayer(e.identifier);return null!=t&&t.hls?t.hls.bufferedToEnd:BufferHelper.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 n=this.primaryMedia;if(n){var i=this.hls;i.media?this.checkBuffer():(this.transferMediaTo(i,n),r&&this.startLoadingPrimaryAt(e,r)),r||(this.log(timelineMessage("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,r))}}},{key:"startLoadingPrimaryAt",value:function(e,t){var r=this.hls,n=r.loadingEnabled,i=r.bufferingEnabled,a=r.startPosition,s=r.hasEnoughToStart;if(this.log("Start loading primary @".concat(e," bufferedPos: ").concat(this.bufferedPos," startPosition: ").concat(a," skip seek: ").concat(t," has enough ").concat(s," loadingEnabled: ").concat(n," bufferingEnabled: ").concat(i)),!t&&s||!n||Math.abs(a-e)>.1){var o=this.primaryDetails;if(null!=o&&o.live&&e+.5>=o.edge){var l=this.bufferingItem;return this.log("Resume primary loading when live passes ".concat(e," buffering item: ").concat(l?segmentToString(l):null)),r.pauseBuffering(),void(this.bufferPastEdge=!0)}r.startLoad(e,t)}else i||r.resumeBuffering()}},{key:"onManifestLoading",value:function(){var e;this.stopLoad(),null==(e=this.schedule)||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(Events$2.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(Events$2.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 n=_objectSpread2(_objectSpread2({},this.mediaSelection||this.altSelection),{},{main:r});this.mediaSelection=n;var i=this.hls.startPosition;if(this.schedule.parseInterstitialDateRanges(n,this.hls.config.interstitialAppendInPlace,-1===i?0:i),this.schedule.items)if(this.effectivePlayingItem){if(this.bufferPastEdge){var a=this.primaryDetails,s=this.bufferedPos;if(null!=a&&a.live&&s+.5<a.edge){this.bufferPastEdge=!1;var o=this.bufferingItem;if(this.log("Live edge ".concat(a.edge," passed buffer: ").concat(s," buffering item: ").concat(o?segmentToString(o):null)),(null==o?void 0:o.end)===1/0){var l=this.playingItem,u=this.isInterstitial(l)&&l.event.appendInPlace;this.hls.startLoad(Math.max(s,o.start),u)}else{var c=this.getBufferingPlayer();if(c)c.bufferedInPlaceToEnd(this.primaryMedia,c.currentTime)&&c.hls&&c.hls.trigger(Events$2.BUFFERED_TO_END,void 0)}}}}else this.checkStart()}}}},{key:"onAudioTrackUpdated",value:function(e,t){var r=this.hls.audioTracks[t.id],n=this.mediaSelection;if(n){var i=_objectSpread2(_objectSpread2({},n),{},{audio:r});this.mediaSelection=i}else this.altSelection=_objectSpread2(_objectSpread2({},this.altSelection),{},{audio:r})}},{key:"onSubtitleTrackUpdated",value:function(e,t){var r=this.hls.subtitleTracks[t.id],n=this.mediaSelection;if(n){var i=_objectSpread2(_objectSpread2({},n),{},{subtitles:r});this.mediaSelection=i}else this.altSelection=_objectSpread2(_objectSpread2({},this.altSelection),{},{subtitles:r})}},{key:"onAudioTrackSwitching",value:function(e,t){var r=getBasicSelectionOption(t);this.playerQueue.forEach(function(e){var n=e.hls;return n&&(n.setAudioOption(t)||n.setAudioOption(r))})}},{key:"onSubtitleTrackSwitch",value:function(e,t){var r=getBasicSelectionOption(t);this.playerQueue.forEach(function(e){var n=e.hls;return n&&(n.setSubtitleOption(t)||-1!==t.id&&n.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 n=this.timelinePos;this.bufferedPos=n,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 n=t[r];if(n.cue.post){var i=this.getEventItem(n.identifier);i&&this.eventItemsMatch(i,this.bufferingItem)&&this.bufferedToItem(i,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,n=null==(r=this.schedule)?void 0:r.items;return e&&n&&n[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,n){e.event.isAssetPastPlayoutLimit(n)&&r.clearAssetPlayer(t.identifier,null)});var n=e.end+.25,i=BufferHelper.bufferInfo(this.primaryMedia,n,0);if(i.end>n||(i.nextStart||0)>n){this.log("trim buffered interstitial ".concat(segmentToString(e)," (was ").concat(segmentToString(t),")"));this.attachPrimary(n,null,!0),this.flushFrontBuffer(n)}}}},{key:"itemsMatch",value:function(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}},{key:"eventItemsMatch",value:function(e,t){var r;return!!t&&(e===t||e.event.identifier===(null==(r=t.event)?void 0:r.identifier))}},{key:"findEventIndex",value:function(e){return this.schedule?this.schedule.findEventIndex(e):-1}},{key:"getEventItem",value:function(e){if(this.schedule){var t,r=null==(t=this.schedule.items)?void 0:t[this.findEventIndex(e)];if(this.isInterstitial(r)&&r.event.identifier===e)return r}}},{key:"findItemIndex",value:function(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}},{key:"updateSchedule",value:function(){var e,t,r=arguments.length>0&&void 0!==arguments[0]&&arguments[0],n=this.mediaSelection;if(n){var i=(null==(e=this.hls)?void 0:e.liveSyncPosition)||0;null==(t=this.schedule)||t.updateSchedule(n,[],i,r)}}},{key:"checkBuffer",value:function(e){var t,r=null==(t=this.schedule)?void 0:t.items;if(r){var n=BufferHelper.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=n.len<1),this.updateBufferedPos(n.end,r,e)}}},{key:"updateBufferedPos",value:function(e,t,r){var n=this.schedule,i=this.bufferingItem;if(!(this.bufferedPos>e)&&n)if(1===t.length&&this.itemsMatch(t[0],i))this.bufferedPos=e;else{var a=this.playingItem,s=this.findItemIndex(a),o=n.findItemIndexAtTime(e);if(this.bufferedPos<e){var l,u=this.findItemIndex(i),c=Math.min(u+1,t.length-1),d=t[c];if((-1===o&&i&&e>=i.end||null!=(l=d.event)&&l.appendInPlace&&e+.01>=d.start)&&(o=c),this.isInterstitial(i)){var h=i.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,i)&&(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 n=r.getAssetPlayer(e.identifier);return!(null!=n&&n.bufferedInPlaceToEnd(t))})}},{key:"setBufferingItem",value:function(e){var t=this,r=this.bufferingItem,n=this.schedule;if(!this.itemsMatch(e,r)&&n){var i=n.items,a=n.events;if(!i||!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(segmentToString(e))+(r?" (".concat(l.toFixed(2)," remaining)"):"")),!this.playbackDisabled)if(s){var u=n.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach(function(e,r){var n=t.getAssetPlayer(e.identifier);n&&(r===u&&n.loadSource(),n.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(function(e){return e.pauseBuffering()});this.hls.trigger(Events$2.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:a.slice(0),schedule:i.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 n=this.getPrimaryResumption(e,this.findItemIndex(e),!0),i=this.bufferedPos=Math.max(n,Math.min(this.bufferedPos,e.end),this.timelinePos,e.start),a=this.detachedData;if(a)if(a.mediaSource){this.attachPrimary(i,e,!0)}else this.startLoadingPrimaryAt(i);else{var s=this.playingItem,o=this.isInterstitial(s)&&s.event.appendInPlace;this.startLoadingPrimaryAt(i,o)}}}},{key:"bufferedToEvent",value:function(e,t){var r=e.event,n=0===r.assetList.length&&!r.assetListLoader,i=r.cue.once;if(n||!i){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,n=e.assetList.length,i=0===n&&!e.assetListLoader,a=e.cue.once;if(i){var s,o,l=e.timelineStart,u=this.playingItem,c=this.getBufferingPlayer();if(e.appendInPlace)this.isInterstitial(u)||(null==u||null==(s=u.nextEvent)?void 0:s.identifier)!==e.identifier||this.flushFrontBuffer(l+.25);var d=0;if(c&&!c.interstitial.cue.pre||!this.primaryLive||(d=this.getLiveStartPos(),c&&(d+=c.remaining)),d&&!e.cue.pre&&!e.cue.post){var h=d-l;h>0&&(o=Math.round(1e3*h)/1e3)}if(this.log("Load interstitial asset ".concat(t+1,"/").concat(r?1:n," ").concat(e).concat(d?" live-start: ".concat(d," start-offset: ").concat(o," (timeline-start: ").concat(l,")"):"")),r)return this.createAsset(e,0,0,l,e.duration,r);var f=this.assetListLoader.loadAssetList(e,o);f&&(e.assetListLoader=f)}else if(!a&&n){for(var v=t;v<n;v++){var p=e.assetList[v],g=this.getAssetPlayerQueueIndex(p.identifier);-1!==g&&!this.playerQueue[g].destroyed||p.error||this.createAssetPlayer(e,p,v)}var y=e.assetList[t];if(y){var m=this.getAssetPlayer(y.identifier);return m&&m.loadSource(),m}}return null}},{key:"flushFrontBuffer",value:function(e){var t=this,r=this.requiredTracks;if(r){var n=this.primaryDetails;if(!(n&&e>=n.edge))this.log("Removing front buffer starting at ".concat(e)),Object.keys(r).forEach(function(r){t.hls.trigger(Events$2.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,n,i,a){var s={parentIdentifier:e.identifier,identifier:generateAssetIdentifier(e,a,t),duration:i,startOffset:r,timelineStart:n,uri:a};return this.createAssetPlayer(e,s,t)}},{key:"createAssetPlayer",value:function(e,t,r){var n=this,i=this.hls,a=i.userConfig,s=getVideoPreference(i.loadLevelObj||i.levels[i.currentLevel],a.videoPreference),o=i.audioTracks[i.audioTrack],l=i.subtitleTracks[i.subtitleTrack],u=0;if(this.primaryLive||e.appendInPlace){var c=this.timelinePos-t.timelineStart;if(c>=0){var d=t.duration;d&&c<d&&(u=c)}}var h=t.identifier,f=_objectSpread2(_objectSpread2({},a),{},{maxMaxBufferLength:Math.min(15,i.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:i.sessionId,assetPlayerId:h,abrEwmaDefaultEstimate:i.bandwidthEstimate,interstitialsController:void 0,startPosition:u,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:s,audioPreference:o||a.audioPreference,subtitlePreference:l||a.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(f.timelineOffset=t.timelineStart));var v=f.cmcd;null!=v&&v.sessionId&&v.contentId&&(f.cmcd=_extends({},v,{contentId:hash(t.uri)})),this.getAssetPlayer(h)&&this.warn("Duplicate date range identifier ".concat(e," and asset ").concat(h));var p=new HlsAssetPlayer(this.HlsPlayerClass,f,e,t);this.playerQueue.push(p),e.assetList[r]=t;var g=!0,y=function(i){if(i.live){var a=new Error("Interstitials MUST be VOD assets ".concat(e)),s={fatal:!0,type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,error:a},o=n.findEventIndex(e.identifier);n.handleAssetItemError(s,e,o,r,a.message)}else{var l=i.edge-i.fragmentStart,u=t.duration;(g||null===u||l>u)&&(g=!1,n.log('Interstitial asset "'.concat(h,'" duration change ').concat(u," > ").concat(l)),t.duration=l,n.updateSchedule())}};p.on(Events$2.LEVEL_UPDATED,function(e,t){var r=t.details;return y(r)}),p.on(Events$2.LEVEL_PTS_UPDATED,function(e,t){var r=t.details;return y(r)}),p.on(Events$2.EVENT_CUE_ENTER,function(){return n.onInterstitialCueEnter()});var m=function(e,t){var r=n.getAssetPlayer(h);if(r&&t.tracks){r.off(Events$2.BUFFER_CODECS,m),r.tracks=t.tracks;var i=n.primaryMedia;n.bufferingAsset===r.assetItem&&i&&!r.media&&n.bufferAssetPlayer(r,i)}};p.on(Events$2.BUFFER_CODECS,m);p.on(Events$2.BUFFERED_TO_END,function(){var t=n.getAssetPlayer(h);if(n.log("buffered to end of asset ".concat(t)),t&&n.schedule){var r=n.getEventItem(e.identifier);r&&n.advanceAssetBuffering(r,t.assetItem)}});var E=function(t){return function(){if(n.getAssetPlayer(h)&&n.schedule){n.shouldPlay=!0;var r=n.findEventIndex(e.identifier);n.advanceAfterAssetEnded(e,r,t)}}};return p.once(Events$2.MEDIA_ENDED,E(r)),p.once(Events$2.PLAYOUT_LIMIT_REACHED,E(1/0)),p.on(Events$2.ERROR,function(t,i){if(n.schedule){var a=n.getAssetPlayer(h);if(i.details===ErrorDetails.BUFFER_STALLED_ERROR)return null!=a&&a.appendInPlace?void n.handleInPlaceStall(e):(n.onTimeupdate(),void n.checkBuffer(!0));i.details!==ErrorDetails.BUFFER_SEEK_OVER_HOLE&&n.handleAssetItemError(i,e,n.findEventIndex(e.identifier),r,"Asset player error ".concat(i.error," ").concat(e))}}),p.on(Events$2.DESTROYING,function(){if(n.getAssetPlayer(h)&&n.schedule){var t=new Error("Asset player destroyed unexpectedly ".concat(h)),i={fatal:!0,type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};n.handleAssetItemError(i,e,n.findEventIndex(e.identifier),r,t.message)}}),this.log("INTERSTITIAL_ASSET_PLAYER_CREATED ".concat(eventAssetToString(t))),this.hls.trigger(Events$2.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:r,event:e,player:p}),p}},{key:"clearInterstitial",value:function(e,t){this.clearAssetPlayers(e,t),e.reset()}},{key:"clearAssetPlayers",value:function(e,t){var r=this;e.assetList.forEach(function(e){r.clearAssetPlayer(e.identifier,t)})}},{key:"resetAssetPlayer",value:function(e){var t=this.getAssetPlayerQueueIndex(e);if(-1!==t){this.log('reset asset player "'.concat(e,'" after error'));var r=this.playerQueue[t];this.transferMediaFromPlayer(r,null),r.resetDetails()}}},{key:"clearAssetPlayer",value:function(e,t){var r=this.getAssetPlayerQueueIndex(e);if(-1!==r){var n=this.playerQueue[r];this.log("clear ".concat(n," toSegment: ").concat(t?segmentToString(t):t)),this.transferMediaFromPlayer(n,t),this.playerQueue.splice(r,1),n.destroy()}}},{key:"emptyPlayerQueue",value:function(){for(var e;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}},{key:"startAssetPlayer",value:function(e,t,r,n,i){var a=e.interstitial,s=e.assetItem,o=e.assetId,l=a.assetList.length,u=this.playingAsset;this.endedAsset=null,this.playingAsset=s,(null==u?void 0:u.identifier)!==o&&(u&&(this.clearAssetPlayer(u.identifier,r[n]),delete u.error),this.log("INTERSTITIAL_ASSET_STARTED ".concat(t+1,"/").concat(l," ").concat(eventAssetToString(s))),this.hls.trigger(Events$2.INTERSTITIAL_ASSET_STARTED,{asset:s,assetListIndex:t,event:a,schedule:r.slice(0),scheduleIndex:n,player:e})),this.bufferAssetPlayer(e,i)}},{key:"bufferAssetPlayer",value:function(e,t){var r;if(this.schedule){var n=e.interstitial,i=e.assetItem,a=this.getEventItem(n.identifier);if(a)if(e.loadSource(),this.setBufferingItem(a),this.bufferingAsset=i,e.bufferedInPlaceToEnd(this.primaryMedia,e.currentTime))this.advanceAssetBuffering(a,i);else{var s=this.getBufferingPlayer();if(s!==e){var o=n.appendInPlace;if(!o||!1!==(null==s?void 0:s.interstitial.appendInPlace)){var l=(null==s?void 0:s.tracks)||(null==(r=this.detachedData)?void 0:r.tracks)||this.requiredTracks;if(o&&i!==this.playingAsset){if(!e.tracks)return void this.log("Waiting for track info before buffering ".concat(e));if(l&&!isCompatibleTrackChange(l,e.tracks)){var u=new Error("Asset ".concat(eventAssetToString(i)," SourceBuffer tracks ('").concat(Object.keys(e.tracks),"') are not compatible with primary content tracks ('").concat(Object.keys(l),"')")),c={fatal:!0,type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,error:u},d=n.findAssetIndex(i);return void this.handleAssetItemError(c,n,this.findEventIndex(n.identifier),d,u.message)}}this.transferMediaTo(e,t)}}}}}},{key:"handleInPlaceStall",value:function(e){var t=this.schedule,r=this.primaryMedia;if(t&&r){var n=r.currentTime,i=t.findAssetIndex(e,n),a=e.assetList[i];if(a){var s=this.getAssetPlayer(a.identifier);if(s){var o=s.currentTime||n-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(n,")")),o&&(l/r.playbackRate<.5||s.bufferedInPlaceToEnd(r,s.currentTime))&&s.hls){var u=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,u,i)}}}}}},{key:"advanceInPlace",value:function(e){var t=this.primaryMedia;if(t&&t.currentTime<e){var r="advance currentTime to ".concat(e,", duration: ").concat(t.duration);t.duration>e?(this.log(r),t.currentTime=e):this.log("Cannot ".concat(r))}}},{key:"handleAssetItemError",value:function(e,t,r,n,i){if(e.details!==ErrorDetails.BUFFER_STALLED_ERROR){var a=t.assetList[n]||null;if(this.warn("INTERSTITIAL_ASSET_ERROR ".concat(a?eventAssetToString(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=_extends({},e,{fatal:!1,errorAction:createDoNothingErrorAction(!0),asset:a,assetListIndex:n,event:t,schedule:u,scheduleIndex:r,player:l});if(this.hls.trigger(Events$2.INTERSTITIAL_ASSET_ERROR,c),e.fatal){var d=this.playingAsset,h=this.bufferingAsset,f=new Error(i);if(a&&(this.clearAssetPlayer(s,null),a.error=f),t.assetList.some(function(e){return!e.error}))for(var v=n;v<t.assetList.length;v++)this.resetAssetPlayer(t.assetList[v].identifier);else t.error=f;this.updateSchedule(!0),t.error?this.primaryFallback(t):(null==d?void 0:d.identifier)===s?this.advanceAfterAssetEnded(t,r,n):(null==h?void 0:h.identifier)===s&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,h)}}}}},{key:"primaryFallback",value:function(e){var t=e.timelineStart,r=this.effectivePlayingItem,n=this.playingItem,i=this.seekableStart,a=this.hls.startPosition,s=this.timelinePos;if(this.isInterstitial(r)){this.log('Fallback to primary from event "'.concat(e.identifier,'" start: ').concat(t," pos: ").concat(s," playing: ").concat(segmentToString(r)," startPosition: ").concat(a," seekableStart: ").concat(i," error: ").concat(e.error)),-1===s&&(s=a),s=Math.max(s,i);var o=this.updateItem(r,s);this.itemsMatch(r,o)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(-1===s)return void this.checkStart();if(this.schedule&&this.isInterstitial(n)){var l=this.schedule.findItemIndexAtTime(s);this.setSchedulePosition(l)}}},{key:"onAssetListLoaded",value:function(e,t){var r,n,i=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);i.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==(n=this.bufferingItem)?void 0:n.event;if(h){var v=this.findEventIndex(s),p=this.getEventItem(s);if(p){if(!this.playingItem&&this.timelinePos>p.end)if(this.schedule.findItemIndexAtTime(this.timelinePos)!==v)return a.error=new Error("Interstitial ".concat(o.length?"no longer within playback range":"asset-list is empty"," ").concat(this.timelinePos," ").concat(a)),this.log(a.error.message),this.updateSchedule(!0),void this.primaryFallback(a);this.setBufferingItem(p)}this.setSchedulePosition(v)}else if((null==f?void 0:f.identifier)===s){var g=a.assetList[0];if(g){var y=this.getAssetPlayer(g.identifier);if(f.appendInPlace){var m=this.primaryMedia;y&&m&&this.bufferAssetPlayer(y,m)}else y&&y.loadSource()}}}}},{key:"onError",value:function(e,t){if(this.schedule)switch(t.details){case ErrorDetails.ASSET_LIST_PARSING_ERROR:case ErrorDetails.ASSET_LIST_LOAD_ERROR:case ErrorDetails.ASSET_LIST_LOAD_TIMEOUT:var r=t.interstitial;r&&(this.updateSchedule(!0),this.primaryFallback(r));break;case ErrorDetails.BUFFER_STALLED_ERROR:var n=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(n)&&n.event.appendInPlace)return void this.handleInPlaceStall(n.event);var i=this.primaryMedia;this.log("Primary player stall @".concat(this.timelinePos," currentTime: ").concat(null==i?void 0:i.currentTime," bufferedPos: ").concat(this.bufferedPos)),this.onTimeupdate(),this.checkBuffer(!0)}}}])}(),LatencyController=function(){return _createClass(function e(t){var r=this;_classCallCheck(this,e),this.hls=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=function(){var e,t=r.media,n=r.levelDetails;if(t&&n&&r.hls){r.currentTime=t.currentTime;var i=r.hls.config,a=r.computeLatency();if(null!==a){r._latency=a;var s=i.lowLatencyMode,o=i.maxLiveSyncPlaybackRate;if(s&&1!==o&&n.live){var l=r.targetLatency;if(null!==l){var u=a-l,c=u<Math.min(r.maxLatency,l+n.targetduration),d=interstitialsEnabled(i)&&!(null==(e=r.hls.interstitialsManager)||null==(e=e.playingItem)||!e.event);if(c&&u>.05&&r.forwardBufferLength>1&&!d){var h=Math.min(2,Math.max(1,o)),f=Math.round(2/(1+Math.exp(-.75*u-r.edgeStalled))*20)/20,v=Math.min(h,Math.max(1,f));r.changeMediaPlaybackRate(t,v)}else 1!==t.playbackRate&&0!==t.playbackRate&&r.changeMediaPlaybackRate(t,1)}}}}},this.hls=t,this.registerListeners()},[{key:"levelDetails",get:function(){var e;return(null==(e=this.hls)?void 0:e.latestLevelDetails)||null}},{key:"latency",get:function(){return this._latency||0}},{key:"maxLatency",get:function(){var e,t=null==(e=this.hls)?void 0:e.config;if(!t)return 0;if(void 0!==t.liveMaxLatencyDuration)return t.liveMaxLatencyDuration;var r=this.levelDetails;return r?t.liveMaxLatencyDurationCount*r.targetduration:0}},{key:"targetLatency",get:function(){var e=this.levelDetails;if(null===e||!this.hls)return null;var t=this.hls.config,r=e.holdBack,n=e.partHoldBack,i=e.targetduration,a=t.liveSyncDuration,s=t.liveSyncDurationCount,o=t.lowLatencyMode,l=this.hls.userConfig,u=o&&n||r;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||0===u)&&(u=void 0!==a?a:s*i);var c=i;return u+Math.min(this.stallCount*t.liveSyncOnStallIncrease,c)},set:function(e){this.hls&&(this.stallCount=0,this.hls.config.liveSyncDuration=e,this._targetLatencyUpdated=!0)}},{key:"liveSyncPosition",get:function(){var e=this.estimateLiveEdge(),t=this.targetLatency;if(null===e||null===t||!this.hls)return null;var r=this.levelDetails;if(null===r)return null;var n=r.edge,i=e-t-this.edgeStalled,a=n-r.totalduration,s=n-(this.hls.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(a,i),s)}},{key:"drift",get:function(){var e=this.levelDetails;return null===e?1:e.drift}},{key:"edgeStalled",get:function(){var e=this.levelDetails;if(null===e||!this.hls)return 0;var t=3*(this.hls.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}},{key:"forwardBufferLength",get:function(){var e=this.media,t=this.levelDetails;if(!e||!t)return 0;var r=e.buffered.length;return(r?e.buffered.end(r-1):t.edge)-this.currentTime}},{key:"destroy",value:function(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}},{key:"registerListeners",value:function(){var e=this.hls;e&&(e.on(Events$2.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Events$2.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events$2.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events$2.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Events$2.ERROR,this.onError,this),e.on(Events$2.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}},{key:"unregisterListeners",value:function(){var e=this.hls;e&&(e.off(Events$2.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Events$2.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events$2.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events$2.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Events$2.ERROR,this.onError,this),e.off(Events$2.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}},{key:"onMediaAttached",value:function(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}},{key:"onMediaDetaching",value:function(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}},{key:"onManifestLoading",value:function(){this._latency=null,this.stallCount=0}},{key:"onLevelUpdated",value:function(e,t){var r=t.details;r.advanced&&this.onTimeupdate(),!r.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}},{key:"onAssetStarted",value:function(e,t){var r,n=this.hls,i=this.media||t.event.appendInPlace&&(null==n||null==(r=n.interstitialsManager)?void 0:r.playerQueue.reduce(function(e,t){return e||t.media},null));n&&i&&i.playbackRate>1&&i.playbackRate<=n.config.maxLiveSyncPlaybackRate&&this.changeMediaPlaybackRate(i,1)}},{key:"onError",value:function(e,t){var r;t.details===ErrorDetails.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,n;e.playbackRate!==t&&(null==(r=this.hls)||r.logger.debug("[latency-controller]: latency=".concat(this.latency.toFixed(3),", targetLatency=").concat(null==(n=this.targetLatency)?void 0:n.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}}])}(),TICK_INTERVAL=500,SubtitleStreamController=function(){function e(t,r,n){var i;return _classCallCheck(this,e),(i=_callSuper(this,e,[t,r,n,"subtitle-stream-controller",PlaylistLevelType.SUBTITLE])).currentTrackId=-1,i.tracksBuffered=[],i.mainDetails=null,i.registerListeners(),i}return _inherits(e,BaseStreamController),_createClass(e,[{key:"onHandlerDestroying",value:function(){this.unregisterListeners(),_superPropGet(e,"onHandlerDestroying",this)([]),this.mainDetails=null}},{key:"registerListeners",value:function(){_superPropGet(e,"registerListeners",this)([]);var t=this.hls;t.on(Events$2.LEVEL_LOADED,this.onLevelLoaded,this),t.on(Events$2.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(Events$2.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(Events$2.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(Events$2.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(Events$2.BUFFER_FLUSHING,this.onBufferFlushing,this)}},{key:"unregisterListeners",value:function(){_superPropGet(e,"unregisterListeners",this)([]);var t=this.hls;t.off(Events$2.LEVEL_LOADED,this.onLevelLoaded,this),t.off(Events$2.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(Events$2.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(Events$2.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(Events$2.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(Events$2.BUFFER_FLUSHING,this.onBufferFlushing,this)}},{key:"startLoad",value:function(e,t){this.stopLoad(),this.state=State.IDLE,this.setInterval(TICK_INTERVAL),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}},{key:"onManifestLoading",value:function(){_superPropGet(e,"onManifestLoading",this)([]),this.mainDetails=null}},{key:"onMediaDetaching",value:function(t,r){this.tracksBuffered=[],_superPropGet(e,"onMediaDetaching",this)([t,r])}},{key:"onLevelLoaded",value:function(e,t){this.mainDetails=t.details}},{key:"onSubtitleFragProcessed",value:function(e,t){var r=t.frag,n=t.part;if(t.success){var i=this.tracksBuffered[this.currentTrackId];if(i){for(var a,s=(n||r).start,o=0;o<i.length;o++)if(s>=i[o].start&&s<=i[o].end){a=i[o];break}var l=s+(n||r).duration;if(a?a.end=l:(a={start:s,end:l},i.push(a)),!n||l>=r.end){var u=this.fragmentTracker.fragBuffered(r);n&&u&&(u.range.subs={time:[{startPTS:r.start,endPTS:l}],partial:!0}),isMediaFragment(r)&&!this.fragContextChanged(r)&&(this.fragPrevious=r),this.fragBufferedComplete(r,n),this.media&&this.tickImmediate()}}}}},{key:"onBufferFlushing",value:function(e,t){var r=t.startOffset,n=t.endOffset;if(0===r&&n!==Number.POSITIVE_INFINITY){var i=n-1;if(i<=0)return;t.endOffsetSubtitles=Math.max(0,i),this.tracksBuffered.forEach(function(e){if(e)for(var t=0;t<e.length;)if(e[t].end<=i)e.shift();else{if(!(e[t].start<i))break;e[t].start=i,t++}}),this.fragmentTracker.removeFragmentsInRange(r,i,PlaylistLevelType.SUBTITLE)}}},{key:"onError",value:function(e,t){var r=t.frag;(null==r?void 0:r.type)===PlaylistLevelType.SUBTITLE&&(t.details===ErrorDetails.FRAG_GAP&&this.fragmentTracker.addAsGap(r),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==State.STOPPED&&(this.state=State.IDLE))}},{key:"onSubtitleTracksUpdated",value:function(e,t){var r=this,n=t.subtitleTracks;this.levels&&subtitleOptionsIdentical(this.levels,n)?this.levels=n.map(function(e){return new Level(e)}):(this.tracksBuffered=[],this.levels=n.map(function(e){var t=new Level(e);return r.tracksBuffered[t.id]=[],t}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,PlaylistLevelType.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null)}},{key:"onSubtitleTrackSwitch",value:function(e,t){var r;if(this.currentTrackId=t.id,this.abortCurrentFrag(),null!=(r=this.levels)&&r.length&&-1!==this.currentTrackId){var n=this.levels[this.currentTrackId];null!=n&&n.details?(this.mediaBuffer=this.mediaBufferTimeRanges,this.state!==State.STOPPED&&this.setInterval(TICK_INTERVAL)):this.mediaBuffer=null}else this.clearInterval()}},{key:"onSubtitleTrackLoaded",value:function(e,t){var r,n=this.currentTrackId,i=this.levels,a=t.details,s=t.id;if(i){var o=i[s];if(!(s>=i.length)&&o){this.log("Subtitle track ".concat(s," loaded [").concat(a.startSN,",").concat(a.endSN,"]").concat(a.lastPartSn?"[part-".concat(a.lastPartSn,"-").concat(a.lastPartIndex,"]"):"",",duration:").concat(a.totalduration)),this.mediaBuffer=this.mediaBufferTimeRanges;var l=this.mainDetails,u=0;if(a.live||null!=(r=o.details)&&r.live){if(a.deltaUpdateFailed)return;if(!l)return void(this.startFragRequested=!1);var c;if(o.details)u=this.alignPlaylists(a,o.details,null==(c=this.levelLastLoaded)?void 0:c.details);a.alignedSliding||(alignStream(l,a,this),u=a.fragmentStart)}o.details=a,this.levelLastLoaded=o,l&&!this.startFragRequested&&this.setStartPosition(l,u),s===n&&(this.hls.trigger(Events$2.SUBTITLE_TRACK_UPDATED,{details:a,id:s,groupId:t.groupId}),this.tickImmediate())}}else this.warn("Subtitle tracks were reset while loading level ".concat(s))}},{key:"_handleFragmentLoadProgress",value:function(e){var t=e.frag,r=e.part,n=e.payload;r&&null!=n&&n.byteLength&&this.shouldDecrypt(t)&&this.decryptPayload(n,t,r)}},{key:"_handleFragmentLoadComplete",value:function(e){var t=e.frag,r=e.payload;!this.fragContextChanged(t)&&null!=r&&r.byteLength&&this.shouldDecrypt(t)&&this.decryptPayload(r,t,null)}},{key:"shouldDecrypt",value:function(e){var t=e.decryptdata;return!!(null!=t&&t.key&&t.iv&&isFullSegmentEncryption(t.method))}},{key:"decryptPayload",value:function(e,t,r){var n=this,i=t.decryptdata,a=performance.now();this.decrypter.decrypt(new Uint8Array(e),i.key.buffer,i.iv.buffer,getAesModeFromFullSegmentMethod(i.method)).then(function(e){n.fragContextChanged(t)||n.hls.trigger(Events$2.FRAG_DECRYPTED,{frag:t,part:r,payload:e,stats:{tstart:a,tdecrypt:performance.now()}})}).catch(function(e){n.hls.trigger(Events$2.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t,part:r}),r||(n.warn("".concat(e.name,": ").concat(e.message)),n.state=State.IDLE)})}},{key:"doTick",value:function(){if(this.state===State.IDLE&&this.levels){var e;if(!this.media&&!this.primaryPrefetch&&(this.startFragRequested||!this.config.startFragPrefetch))return;var t=this.currentTrackId,r=this.levels[t],n=null==r?void 0:r.details;if(!n||this.waitForLive(r)||this.waitForCdnTuneIn(n))return void(this.startFragRequested=!1);var i=this.config,a=this.playhead,s=BufferHelper.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],a,i.maxBufferHole),o=s.end,l=s.len;if(l>Math.max(this.hls.maxBufferLength+n.levelTargetDuration,(null==(e=this.hls.mainForwardBufferInfo)?void 0:e.len)||0)||l&&!this.buffering)return;var u=this.getNextFragment(o,n);if(!u)return;if(isMediaFragment(u)){var c,d=u.sn-n.startSN,h=n.fragments[d-1];u.cc!==(null==h?void 0:h.cc)||null!=(c=n.partList)&&c.length||this.fragmentTracker.getState(h)!==FragmentState.NOT_LOADED||(u=h)}this.loadFragment(u,r,o)}}},{key:"loadFragment",value:function(t,r,n){var i=this.fragmentTracker.getState(t);i!==FragmentState.NOT_LOADED&&i!==FragmentState.PARTIAL||_superPropGet(e,"loadFragment",this)([t,r,n])}},{key:"mediaBufferTimeRanges",get:function(){return new BufferableInstance(this.tracksBuffered[this.currentTrackId]||[])}}])}(),BufferableInstance=_createClass(function e(t){_classCallCheck(this,e),this.buffered=void 0;var r=function(e,r,n){if((r>>>=0)>n-1)throw new DOMException("Failed to execute '".concat(e,"' on 'TimeRanges': The index provided (").concat(r,") is greater than the maximum bound (").concat(n,")"));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)}}}),specialCea608CharsCodes={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},getCharForByte=function(e){return String.fromCharCode(specialCea608CharsCodes[e]||e)},NR_ROWS=15,NR_COLS=42,rowsLowCh1={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},rowsHighCh1={17:2,18:4,21:6,22:8,23:10,19:13,20:15},rowsLowCh2={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},rowsHighCh2={25:2,26:4,29:6,30:8,31:10,27:13,28:15},backgroundColors=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],CaptionsLogger=function(){return _createClass(function e(){_classCallCheck(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;logger.log("".concat(this.time," [").concat(e,"] ").concat(r))}}}])}(),numArrayToHexArray=function(e){for(var t=[],r=0;r<e.length;r++)t.push(e[r].toString(16));return t},DEFAULT_PEN_STYLES=Object.freeze({foreground:"white",underline:!1,italics:!1,background:"black",flash:!1}),PenState=function(){return _createClass(function e(){_classCallCheck(this,e),this.styles=DEFAULT_PEN_STYLES},[{key:"foreground",get:function(){return this.styles.foreground},set:function(e){var t=this.styles;this.styles={foreground:e,underline:t.underline,italics:t.italics,background:t.background,flash:t.flash}}},{key:"underline",get:function(){return this.styles.underline},set:function(e){var t=this.styles;this.styles={foreground:t.foreground,underline:e,italics:t.italics,background:t.background,flash:t.flash}}},{key:"italics",get:function(){return this.styles.italics},set:function(e){var t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:e,background:t.background,flash:t.flash}}},{key:"background",get:function(){return this.styles.background},set:function(e){var t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:t.italics,background:e,flash:t.flash}}},{key:"flash",get:function(){return this.styles.flash},set:function(e){var t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:t.italics,background:t.background,flash:e}}},{key:"reset",value:function(){this.styles=DEFAULT_PEN_STYLES}},{key:"setStyles",value:function(e){var t=this.styles,r=Object.prototype.hasOwnProperty;this.styles={foreground:r.call(e,"foreground")?e.foreground:t.foreground,underline:r.call(e,"underline")?e.underline:t.underline,italics:r.call(e,"italics")?e.italics:t.italics,background:r.call(e,"background")?e.background:t.background,flash:r.call(e,"flash")?e.flash:t.flash}}},{key:"toString",value:function(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}])}(),StyledUnicodeChar=function(){return _createClass(function e(){_classCallCheck(this,e),this.uchar=" ",this.penState=new PenState},[{key:"reset",value:function(){this.uchar=" ",this.penState.reset()}},{key:"setChar",value:function(e,t){this.uchar=e,this.penState.styles=t.styles}},{key:"setPenState",value:function(e){this.penState.styles=e.styles}},{key:"copy",value:function(e){this.uchar=e.uchar,this.penState.styles=e.penState.styles}}])}(),Row=function(){return _createClass(function e(t){_classCallCheck(this,e),this.chars=[],this.pos=0,this.currPenState=new PenState,this.cueStartTime=null,this.logger=void 0;for(var r=0;r<NR_COLS;r++)this.chars.push(new StyledUnicodeChar);this.logger=t},[{key:"equals",value:function(e){for(var t=this.chars,r=e.chars,n=0;n<NR_COLS;n++){var i=t[n],a=r[n];if(i.uchar!==a.uchar)return!1;var s=i.penState.styles,o=a.penState.styles;if(s!==o&&(s.foreground!==o.foreground||s.underline!==o.underline||s.italics!==o.italics||s.background!==o.background||s.flash!==o.flash))return!1}return!0}},{key:"copy",value:function(e){for(var t=0;t<NR_COLS;t++)this.chars[t].copy(e.chars[t])}},{key:"isEmpty",value:function(){for(var e=this.chars,t=0;t<NR_COLS;t++){var r=e[t];if(" "!==r.uchar)return!1;var n=r.penState.styles;if(n!==DEFAULT_PEN_STYLES&&("white"!==n.foreground||n.underline||n.italics||"black"!==n.background||n.flash))return!1}return!0}},{key:"setCursor",value:function(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>=NR_COLS&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=NR_COLS-1)}},{key:"moveCursor",value:function(e){var t=Math.min(this.pos+e,NR_COLS);if(e>1)for(var r=this.pos+1;r<t;r++)this.chars[r].setPenState(this.currPenState);this.setCursor(t)}},{key:"backSpace",value:function(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}},{key:"insertChar",value:function(e){var t=this;e>=144&&this.backSpace();var r=getCharForByte(e);this.pos>=NR_COLS?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<NR_COLS;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<NR_COLS;r++){var n=this.chars[r].uchar;" "!==n&&(t=!1),e.push(n)}return t?"":e.join("")}},{key:"setPenStyles",value:function(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}])}(),CaptionScreen=function(){return _createClass(function e(t){_classCallCheck(this,e),this.rows=[],this.currRow=NR_ROWS-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(var r=0;r<NR_ROWS;r++)this.rows.push(new Row(t));this.logger=t},[{key:"reset",value:function(){for(var e=0;e<NR_ROWS;e++)this.rows[e].clear();this.currRow=NR_ROWS-1}},{key:"equals",value:function(e){for(var t=!0,r=0;r<NR_ROWS;r++)if(!this.rows[r].equals(e.rows[r])){t=!1;break}return t}},{key:"copy",value:function(e){for(var t=0;t<NR_ROWS;t++)for(var r=this.rows[t].chars,n=e.rows[t].chars,i=0;i<NR_COLS;i++){var a=r[i],s=n[i];a.uchar=s.uchar,a.penState.styles=s.penState.styles}}},{key:"isEmpty",value:function(){for(var e=!0,t=0;t<NR_ROWS;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 = "+stringify(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<NR_ROWS;r++)this.rows[r].clear();var n=this.currRow+1-this.nrRollUpRows,i=this.lastOutputScreen;if(i){var a=i.rows[n].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(i.rows[n+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 = "+stringify(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="",n=-1,i=0;i<NR_ROWS;i++){var a=this.rows[i].getTextString();a&&(n=i+1,e?t.push("Row "+n+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(r=e?"["+t.join(" | ")+"]":t.join("\n")),r}},{key:"getTextAndFormat",value:function(){return this.rows}}])}(),Cea608Channel=function(){return _createClass(function e(t,r,n){_classCallCheck(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 CaptionScreen(n),this.nonDisplayedMemory=new CaptionScreen(n),this.lastOutputScreen=new CaptionScreen(n),this.currRollUpRow=this.displayedMemory.rows[NR_ROWS-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=n},[{key:"reset",value:function(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[NR_ROWS-1],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 n=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,function(){return n+": "+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: "+stringify(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))}}])}(),Cea608Parser=function(){return _createClass(function e(t,r,n){_classCallCheck(this,e),this.channels=[null,null,null],this.currentChannel=0,this.cmdHistory=createCmdHistory(),this.logger=void 0,this.field=void 0,this.outputFilters=void 0,this.logger=new CaptionsLogger,this.field=t,this.outputFilters=[null,r,n]},[{key:"getHandler",value:function(e){return this.outputFilters[e]}},{key:"setHandler",value:function(e,t){var r;this.outputFilters[e]=t,null==(r=this.channels[e])||r.setHandler(t)}},{key:"getChannel",value:function(e){var t=this.channels[e];return t||(t=this.channels[e]=new Cea608Channel(this.field+e-1,this.outputFilters[e],this.logger)),t}},{key:"addData",value:function(e,t){var r=this;this.logger.time=e;for(var n=function(e){var n=127&t[e],i=127&t[e+1],a=!1,s=null;if(0===n&&0===i)return 0;r.logger.log(3,function(){return"["+numArrayToHexArray([t[e],t[e+1]])+"] -> ("+numArrayToHexArray([n,i])+")"});var o=r.cmdHistory;if(n>=16&&n<=31){if(hasCmdRepeated(n,i,o))return setLastCmd(null,null,o),r.logger.log(3,function(){return"Repeated command ("+numArrayToHexArray([n,i])+") is dropped"}),0;setLastCmd(n,i,r.cmdHistory),(a=r.parseCmd(n,i))||(a=r.parseMidrow(n,i)),a||(a=r.parsePAC(n,i)),a||(a=r.parseBackgroundAttributes(n,i))}else setLastCmd(null,null,o);if(!a&&(s=r.parseChars(n,i))){var l=r.currentChannel;if(l&&l>0)r.getChannel(l).insertChars(s);else r.logger.log(2,"No channel found yet. TEXT-MODE?")}a||s||r.logger.log(2,function(){return"Couldn't parse cleaned data "+numArrayToHexArray([n,i])+" orig: "+numArrayToHexArray([t[e],t[e+1]])})},i=0;i<t.length;i+=2)n(i)}},{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,n=this.getChannel(r);return 20===e||21===e||28===e||29===e?32===t?n.ccRCL():33===t?n.ccBS():34===t?n.ccAOF():35===t?n.ccAON():36===t?n.ccDER():37===t?n.ccRU(2):38===t?n.ccRU(3):39===t?n.ccRU(4):40===t?n.ccFON():41===t?n.ccRDC():42===t?n.ccTR():43===t?n.ccRTD():44===t?n.ccEDM():45===t?n.ccCR():46===t?n.ccENM():47===t&&n.ccEOC():n.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 n=this.channels[r];return!!n&&(n.ccMIDROW(t),this.logger.log(3,function(){return"MIDROW ("+numArrayToHexArray([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 n=e<=23?1:2;return r=t>=64&&t<=95?1===n?rowsLowCh1[e]:rowsLowCh2[e]:1===n?rowsHighCh1[e]:rowsHighCh2[e],this.getChannel(n).setPAC(this.interpretPAC(r,t)),this.currentChannel=n,!0}},{key:"interpretPAC",value:function(e,t){var r,n={color:null,italics:!1,indent:null,underline:!1,row:e};return r=t>95?t-96:t-64,n.underline=!(1&~r),r<=13?n.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(n.italics=!0,n.color="white"):n.indent=4*Math.floor((r-16)/2),n}},{key:"parseChars",value:function(e,t){var r,n,i=null,a=null;(e>=25?(r=2,a=e-8):(r=1,a=e),a>=17&&a<=19)?(n=17===a?t+80:18===a?t+112:t+144,this.logger.log(2,function(){return"Special char '"+getCharForByte(n)+"' in channel "+r}),i=[n]):e>=32&&e<=127&&(i=0===t?[e]:[e,t]);return i&&this.logger.log(3,function(){return"Char codes = "+numArrayToHexArray(i).join(",")}),i}},{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 n={};16===e||24===e?(r=Math.floor((t-32)/2),n.background=backgroundColors[r],t%2==1&&(n.background=n.background+"_semi")):45===t?n.background="transparent":(n.foreground="black",47===t&&(n.underline=!0));var i=e<=23?1:2;return this.getChannel(i).setBkgData(n),!0}},{key:"reset",value:function(){for(var e=0;e<Object.keys(this.channels).length;e++){var t=this.channels[e];t&&t.reset()}setLastCmd(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 setLastCmd(e,t,r){r.a=e,r.b=t}function hasCmdRepeated(e,t,r){return r.a===e&&r.b===t}function createCmdHistory(){return{a:null,b:null}}var OutputFilter=function(){return _createClass(function e(t,r){_classCallCheck(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}}])}(),TimelineController=function(){return _createClass(function e(t){_classCallCheck(this,e),this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.cueCache={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=newVTTCCs(),this.captionsProperties=void 0,this.hls=t,this.config=t.config,this.Cues=t.config.cueHandler,this.cueCache={},this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},t.on(Events$2.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(Events$2.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Events$2.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Events$2.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(Events$2.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(Events$2.FRAG_LOADING,this.onFragLoading,this),t.on(Events$2.FRAG_LOADED,this.onFragLoaded,this),t.on(Events$2.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(Events$2.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(Events$2.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(Events$2.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(Events$2.BUFFER_APPENDED,this.onBufferAppended,this),t.on(Events$2.BUFFER_FLUSHING,this.onBufferFlushing,this)},[{key:"destroy",value:function(){var e=this.hls;e.off(Events$2.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Events$2.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events$2.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events$2.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Events$2.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(Events$2.FRAG_LOADING,this.onFragLoading,this),e.off(Events$2.FRAG_LOADED,this.onFragLoaded,this),e.off(Events$2.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(Events$2.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(Events$2.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(Events$2.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(Events$2.BUFFER_APPENDED,this.onBufferAppended,this),e.off(Events$2.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 OutputFilter(this,"textTrack1"),t=new OutputFilter(this,"textTrack2"),r=new OutputFilter(this,"textTrack3"),n=new OutputFilter(this,"textTrack4");this.cea608Parser1=new Cea608Parser(1,e,t),this.cea608Parser2=new Cea608Parser(3,r,n)}},{key:"addCues",value:function(e,t,r,n,i){for(var a=!1,s=i.length;s--;){var o=i[s],l=intersection(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||i.push([t,r]),this.config.renderTextTracksNatively){var u=this.cueCache[e];if(u){var c=this.Cues.newCue(null,t,r,n);c.length&&u.push.apply(u,c)}else{var d=this.captionsTracks[e].track;this.Cues.newCue(d,t,r,n)}}else{var h,f=this.Cues.newCue(null,t,r,n),v=null==(h=this.captionsProperties[e])?void 0:h.media;this.hls.trigger(Events$2.CUES_PARSED,{type:"captions",cues:f,track:e,closedCaptions:v})}}},{key:"onInitPtsFound",value:function(e,t){var r=this,n=t.id,i=t.timestampOffsets,a=this.unparsedVttFrags;n===PlaylistLevelType.MAIN&&(this.initPTS=i),a.length&&(this.unparsedVttFrags=[],a.forEach(function(e){r.initPTS[e.frag.cc]?r.onFragLoaded(Events$2.FRAG_LOADED,e):r.hls.trigger(Events$2.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e.frag,part:null,error:new Error("Subtitle discontinuity domain does not match main")})}))}},{key:"createCaptionsTrack",value:function(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}},{key:"createNativeTrack",value:function(e){if(!this.captionsTracks[e]){var t=this.captionsProperties,r=this.captionsTracks,n=this.cueCache,i=this.media,a=t[e],s=a.label,o=a.languageCode;i&&(n[e]=[],r[e]=createTrackNode(i,"captions",s,o,"hidden"))}}},{key:"createNonNativeTrack",value:function(e){if(!this.nonNativeCaptionsTracks[e]){var t=this.captionsProperties[e];if(t){var r={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=r,this.hls.trigger(Events$2.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[r]})}}}},{key:"onMediaAttaching",value:function(e,t){this.media=t.media}},{key:"onMediaDetaching",value:function(e,t){var r=!!t.transferMedia;if(this.media=null,!r){if(this.config.renderTextTracksNatively){var n=this.captionsTracks,i=this.cueCache;for(var a in n)n[a].remove(),delete i[a]}this.cueCache={},this.captionsTracks={},this.nonNativeCaptionsTracks={}}}},{key:"onManifestLoading",value:function(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=newVTTCCs(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}},{key:"onSubtitleTracksUpdated",value:function(e,t){var r=t.subtitleTracks||[];if(r.length&&!this.config.renderTextTracksNatively&&!subtitleOptionsIdentical(this.tracks,r)){var n=r.map(function(e){return{label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e}});this.hls.trigger(Events$2.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:n})}this.tracks=r}},{key:"onManifestLoaded",value:function(e,t){var r=this;this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(function(e){var t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(t){var n="textTrack".concat(t[1]),i=r.captionsProperties[n];i&&(i.label=e.name,e.lang&&(i.languageCode=e.lang),i.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===PlaylistLevelType.MAIN){var r,n,i=this.cea608Parser1,a=this.cea608Parser2,s=this.lastSn,o=t.frag,l=o.cc,u=o.sn,c=null!=(r=null==(n=t.part)?void 0:n.index)?r:-1;i&&a&&(u!==s+1||u===s&&c!==this.lastPartIndex+1||l!==this.lastCc)&&(i.reset(),a.reset()),this.lastCc=l,this.lastSn=u,this.lastPartIndex=c}}},{key:"onFragLoaded",value:function(e,t){var r,n=t.frag,i=t.payload;if(n.level<this.tracks.length&&n.type===PlaylistLevelType.SUBTITLE)if(i.byteLength||null!=(r=n.initSegment)&&null!=(r=r.data)&&r.byteLength){var a=n.decryptdata,s="stats"in t;if(null==a||!a.encrypted||s){var o=this.tracks[n.level],l=this.vttCCs;l[n.cc]||(l[n.cc]={start:n.start,prevCC:this.prevCC,new:!0},this.prevCC=n.cc),(null==o?void 0:o.textCodec)===IMSC1_CODEC?this._parseIMSC1(t):this._parseVTTs(t)}}else{var u="part"in t?t.part:null;this.hls.trigger(Events$2.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,part:u,error:new Error("Empty subtitle payload")})}}},{key:"_parseIMSC1",value:function(e){var t=this,r=e.frag,n=e.payload,i="part"in e?e.part:null,a=this.hls;parseIMSC1(n,this.initPTS[r.cc],function(e){t._appendCues(e,r.level),a.trigger(Events$2.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:r,part:i})},function(e){a.logger.log("Cannot parse IMSC1 (sn: ".concat(r.sn," @").concat(r.start,"): ").concat(e)),a.trigger(Events$2.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,part:i,error:e})})}},{key:"_parseVTTs",value:function(e){var t,r=this,n=e.frag,i=e.payload,a="part"in e?e.part:null,s=this.initPTS,o=this.unparsedVttFrags,l=s.length-1;if(s[n.cc]||-1!==l){var u=this.hls,c=null==(t=n.initSegment)?void 0:t.data;parseWebVTT(c?appendUint8Array(c,new Uint8Array(i)).buffer:i,this.initPTS[n.cc],this.vttCCs,n.cc,(a&&!c?a:n).start,function(e){r._appendCues(e,n.level),u.trigger(Events$2.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:n,part:a})},function(t){var i=t.message.startsWith("Missing initPTS");u.logger.log("".concat(i?"Deferred parsing of":"Cannot parse"," VTT cue (sn: ").concat(n.sn," @").concat(n.start,"): ").concat(t)),i?o.push(e):(r.config.enableIMSC1&&r._fallbackToIMSC1(e),u.trigger(Events$2.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,part:a,error:t}))})}else o.push(e)}},{key:"_fallbackToIMSC1",value:function(e){var t=this,r=e.frag,n=e.payload,i=this.tracks[r.level];i.textCodec||parseIMSC1(n,this.initPTS[r.cc],function(){i.textCodec=IMSC1_CODEC,t._parseIMSC1(e)},function(){i.textCodec="wvtt"})}},{key:"_appendCues",value:function(e,t){var r=this.hls;if(this.config.renderTextTracksNatively){var n,i=null==(n=this.tracks[t].trackNode)?void 0:n.track;if(!i||"disabled"===i.mode)return;e.forEach(function(e){return addCueToTrack(i,e)})}else{var a=this.tracks[t];if(!a)return;var s=a.default?"default":"subtitles"+t;r.trigger(Events$2.CUES_PARSED,{type:"subtitles",cues:e,track:s,subtitleTrack:a})}}},{key:"onFragDecrypted",value:function(e,t){t.frag.type===PlaylistLevelType.SUBTITLE&&this.onFragLoaded(Events$2.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,n=t.samples;if(r.type!==PlaylistLevelType.MAIN||"NONE"!==this.closedCaptionsForLevel(r))for(var i=0;i<n.length;i++){var a=n[i].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();var s=this.extractCea608Data(a);this.cea608Parser1.addData(n[i].pts,s[0]),this.cea608Parser2.addData(n[i].pts,s[1])}}}}},{key:"onBufferAppended",value:function(e,t){if(this.config.renderTextTracksNatively){var r,n=t.type,i=t.timeRanges;if("video"===n&&null!=(r=i[n])&&r.length){var a=this.captionsTracks,s=this.cueCache;Object.keys(s).forEach(function(e){var t,r=null==(t=a[e])?void 0:t.track;if(r)for(var n=s[e],i=0;i<n.length;i++)addCueToTrack(r,n[i]);delete s[e]})}}}},{key:"onBufferFlushing",value:function(e,t){var r=t.startOffset,n=t.endOffset,i=t.endOffsetSubtitles,a=t.type,s=this.media;if(s&&!(s.currentTime<n)){if(!a||"video"===a){var o=this.captionsTracks,l=this.cueCache;Object.keys(o).forEach(function(e){return removeCuesInRange(o[e].track,r,n)}),Object.keys(l).forEach(function(e){for(var t=l[e],i=t.length;i--;){var a=t[i];a.startTime>=r&&a.endTime<=n&&t.splice(i,1)}})}this.config.renderTextTracksNatively&&0===r&&void 0!==i&&this.tracks.forEach(function(e){var t,n=null==(t=e.trackNode)?void 0:t.track;n&&removeCuesInRange(n,r,i)})}}},{key:"extractCea608Data",value:function(e){for(var t=[[],[]],r=31&e[0],n=2,i=0;i<r;i++){var a=e[n++],s=127&e[n++],o=127&e[n++];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 intersection(e,t,r,n){return Math.min(t,n)-Math.max(e,r)}function newVTTCCs(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}var WHITESPACE_CHAR=/\s/,Cues={newCue:function(e,t,r,n){for(var i,a,s,o,l,u=[],c=self.VTTCue||self.TextTrackCue,d=0;d<n.rows.length;d++)if(s=!0,o=0,l="",!(i=n.rows[d]).isEmpty()){for(var h,f=0;f<i.chars.length;f++)WHITESPACE_CHAR.test(i.chars[f].uchar)&&s?o++:(l+=i.chars[f].uchar,s=!1);i.cueStartTime=t,t===r&&(r+=1e-4),o>=16?o--:o++;var v=fixLineBreaks(l.trim()),p=generateCueId(t,r,v);null!=e&&null!=(h=e.cues)&&h.getCueById(p)||((a=new c(t,r,v)).id=p,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 addCueToTrack(e,t)})),u}},BaseLoader=function(){return _createClass(function e(){_classCallCheck(this,e),this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=0,this.config=null,this.callbacks=null,this.context=null,this.stats=new LoadStats},[{key:"destroy",value:function(){this.callbacks=this.context=this.config=null,this.abortInternal(),this.stats=null}},{key:"load",value:function(e,t,r){var n=this.stats;if(n.loading.start)throw new Error("Loader can only be used once.");n.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=r,this.loadInternal()}},{key:"abort",value:function(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.getNetworkDetails())}},{key:"loadtimeout",value:function(){if(this.config){var e=this.config.loadPolicy.timeoutRetry;if(shouldRetry(e,this.stats.retry,!0))this.retry(e);else{var t;logger.warn("timeout while loading ".concat(null==(t=this.context)?void 0:t.url));var r=this.callbacks;r&&(this.abortInternal(),r.onTimeout(this.stats,this.context,this.getNetworkDetails()))}}}},{key:"retry",value:function(e){var t=this,r=this.context,n=this.stats;this.retryDelay=getRetryDelay(e,n.retry),n.retry++,logger.warn("".concat(status?"HTTP Status "+status:"Timeout"," while loading ").concat(null==r?void 0:r.url,", retrying ").concat(n.retry,"/").concat(e.maxNumRetry," in ").concat(this.retryDelay,"ms")),this.abortInternal(),this.resetInternalLoader(),self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(function(){return t.loadInternal()},this.retryDelay)}}])}();function fetchSupported(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}var BYTERANGE=/(\d+)-(\d+)\/(\d+)/,FetchLoader=function(){function e(t){var r;return _classCallCheck(this,e),(r=_callSuper(this,e)).fetchSetup=void 0,r.request=null,r.response=null,r.controller=null,r.fetchSetup=t.fetchSetup||getRequest,r}return _inherits(e,BaseLoader),_createClass(e,[{key:"destroy",value:function(){this.request=null,_superPropGet(e,"destroy",this)([]),this.response=null,this.controller=null,this.fetchSetup=null}},{key:"abortInternal",value:function(){self.clearTimeout(this.retryTimeout),this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}},{key:"getNetworkDetails",value:function(){return this.response}},{key:"resetInternalLoader",value:function(){this.response=null}},{key:"loadInternal",value:function(){var e=this,t=this.config,r=this.context,n=this.stats;if(t&&r){n.loading.first=0,n.loaded=0,n.aborted=!1,this.controller=new self.AbortController;var i=getRequestParameters(r,this.controller.signal),a="arraybuffer"===r.responseType,s=a?"byteLength":"length",o=t.loadPolicy,l=o.maxTimeToFirstByteMs,u=o.maxLoadTimeMs;this.request=this.fetchSetup(r,i),self.clearTimeout(this.requestTimeout),t.timeout=l&&isFiniteNumber(l)?l:u,this.requestTimeout=self.setTimeout(function(){e.loadtimeout()},t.timeout),(isPromise(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(function(i){var s;e.response=i;var o=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(e.requestTimeout),t.timeout=u,e.requestTimeout=self.setTimeout(function(){e.loadtimeout()},u-(o-n.loading.start)),!i.ok){var l=i.status,c=i.statusText;throw new FetchError(c||"fetch, bad network response",l,i)}n.loading.first=o,n.total=getContentLength(i.headers)||n.total;var d=null==(s=e.callbacks)?void 0:s.onProgress;return d&&isFiniteNumber(t.highWaterMark)?e.loadProgressively(i,n,r,t.highWaterMark,d):a?i.arrayBuffer():"json"===r.responseType?i.json():i.text()}).then(function(i){var a,o,l=e.response;if(!l)throw new Error("loader destroyed");self.clearTimeout(e.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);var u=i[s];u&&(n.loaded=n.total=u);var c={url:l.url,data:i,code:l.status},d=null==(a=e.callbacks)?void 0:a.onProgress;d&&!isFiniteNumber(t.highWaterMark)&&d(n,r,i,l),null==(o=e.callbacks)||o.onSuccess(c,n,r,l)}).catch(function(i){if(self.clearTimeout(e.requestTimeout),!n.aborted){var a,s=i&&i.code||0,o=i?i.message:null,l=t.loadPolicy.errorRetry;if(shouldRetry(l,n.retry,!1,{url:r.url,data:void 0,code:s}))e.retry(l);else logger.error("".concat(s," while loading ").concat(r.url)),null==(a=e.callbacks)||a.onError({code:s,text:o},r,i?i.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 n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,i=arguments.length>4?arguments[4]:void 0,a=new ChunkCache,s=e.body.getReader(),o=function(){return s.read().then(function(s){if(s.done)return a.dataLength&&i(t,r,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));var l=s.value,u=l.length;return t.loaded+=u,u<n||a.dataLength?(a.push(l),a.dataLength>=n&&i(t,r,a.flush().buffer,e)):i(t,r,l.buffer,e),o()}).catch(function(){return Promise.reject()})};return o()}}])}();function getRequestParameters(e,t){var r={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(_extends({},e.headers))};return e.rangeEnd&&r.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1)),r}function getByteRangeLength(e){var t=BYTERANGE.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}function getContentLength(e){var t=e.get("Content-Range");if(t){var r=getByteRangeLength(t);if(isFiniteNumber(r))return r}var n=e.get("Content-Length");if(n)return parseInt(n)}function getRequest(e,t){return new self.Request(e.url,t)}var FetchError=function(){function e(t,r,n){var i;return _classCallCheck(this,e),(i=_callSuper(this,e,[t])).code=void 0,i.details=void 0,i.code=r,i.details=n,i}return _inherits(e,_wrapNativeSuper(Error)),_createClass(e)}(),clamp=function(e,t,r){return Math.max(t,Math.min(e,r))},AGE_HEADER_LINE_REGEX=/^age:\s*[\d.]+\s*$/im,XhrLoader=function(){function e(t){var r;return _classCallCheck(this,e),(r=_callSuper(this,e)).xhrSetup=void 0,r.loader=null,r.xhrSetup=t.xhrSetup||null,r}return _inherits(e,BaseLoader),_createClass(e,[{key:"destroy",value:function(){_superPropGet(e,"destroy",this)([]),this.loader=null,this.xhrSetup=null}},{key:"abortInternal",value:function(){var e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))}},{key:"getNetworkDetails",value:function(){return this.loader}},{key:"resetInternalLoader",value:function(){this.loader=null}},{key:"loadInternal",value:function(){var e=this,t=this.config,r=this.context;if(t&&r){var n=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;var a=this.xhrSetup;a?Promise.resolve().then(function(){if(e.loader===n&&!e.stats.aborted)return a.call(e,n,r.url,r)}).catch(function(t){if(e.loader===n&&!e.stats.aborted)return n.open("GET",r.url,!0),a.call(e,n,r.url,r)}).then(function(){e.loader!==n||e.stats.aborted||e.openAndSendXhr(n,r,t)}).catch(function(t){var a;null==(a=e.callbacks)||a.onError({code:n.status,text:t.message},r,n,i)}):this.openAndSendXhr(n,r,t)}}},{key:"openAndSendXhr",value:function(e,t,r){e.readyState||e.open("GET",t.url,!0);var n=t.headers,i=r.loadPolicy,a=i.maxTimeToFirstByteMs,s=i.maxLoadTimeMs;if(n)for(var o in n)e.setRequestHeader(o,n[o]);t.rangeEnd&&e.setRequestHeader("Range","bytes=".concat(t.rangeStart,"-").concat(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),r.timeout=a&&isFiniteNumber(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 n=t.readyState,i=this.config;if(!r.aborted&&n>=2&&(0===r.loading.first&&(r.loading.first=Math.max(self.performance.now(),r.loading.start),i.timeout!==i.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),i.timeout=i.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.loadPolicy.maxLoadTimeMs-(r.loading.first-r.loading.start)))),4===n)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;var a=t.status,s="text"===t.responseType?t.responseText:null;if(a>=200&&a<300){var o=null!=s?s:t.response;if(null!=o){var l,u;r.loading.end=Math.max(self.performance.now(),r.loading.first);var c="arraybuffer"===t.responseType?o.byteLength:o.length;r.loaded=r.total=c,r.bwEstimate=8e3*r.total/(r.loading.end-r.loading.first);var d=null==(l=this.callbacks)?void 0:l.onProgress;d&&d(r,e,o,t);var h={url:t.responseURL,data:o,code:a};return e.rangeEnd&&c!==e.rangeEnd-e.rangeStart&&logger.warn("Payload length ".concat(c," does not match requested Range: bytes=").concat(e.rangeStart,"-").concat(e.rangeEnd-1)),void(null==(u=this.callbacks)||u.onSuccess(h,r,e,t))}}var f,v=i.loadPolicy.errorRetry;if(shouldRetry(v,r.retry,!1,{url:e.url,data:void 0,code:a}))this.retry(v);else logger.error("".concat(a," while loading ").concat(e.url)),null==(f=this.callbacks)||f.onError({code:a,text:t.statusText},e,t,r)}}}},{key:"loadprogress",value:function(e){var t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}},{key:"getCacheAge",value:function(){var e=null;if(this.loader&&AGE_HEADER_LINE_REGEX.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}}])}(),defaultLoadPolicy={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},hlsDefaultConfig=_objectSpread2(_objectSpread2({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,loopBackBufferFlush:void 0,startOnSegmentBoundary:!1,nextAudioTrackBufferFlushForwardOffset:.25,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,skipBufferHolePadding:.1,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveMaxUnchangedPlaylistRefresh:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,appendTimeout:1/0,ignorePlaylistParsingErrors:!1,loader:XhrLoader,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,handleMpegTsVideoIntegrityErrors:"process",abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,abrSwitchInterval:0,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:_requestMediaKeySystemAccess,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,emsgKLVSchemaUri:void 0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,iframeCacheLimit:2097152,useMediaCapabilities:!0,preserveManualLevelOnError:!1,errorPenaltyExpireMs:0,certLoadPolicy:{default:defaultLoadPolicy},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3,streamController:StreamController,abrController:AbrController,bufferController:BufferController,capLevelController:CapLevelController,errorController:ErrorController,fpsController:FPSController,id3TrackController:ID3TrackController,gapController:GapController,latencyController:LatencyController},timelineConfig()),{},{subtitleStreamController:SubtitleStreamController,subtitleTrackController:SubtitleTrackController,timelineController:TimelineController,audioStreamController:AudioStreamController,audioTrackController:AudioTrackController,emeController:EMEController,cmcdController:CMCDController,contentSteeringController:ContentSteeringController,iframeController:IFrameController,interstitialsController:InterstitialsController});function timelineConfig(){return{cueHandler:Cues,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function mergeConfig$1(e,t,r){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');if(void 0!==t.liveMaxUnchangedPlaylistRefresh){var n=t.liveMaxUnchangedPlaylistRefresh,i=clamp(n,2,1/0);i!==n&&r.warn('hls.js config: "liveMaxUnchangedPlaylistRefresh" clamped from '.concat(n," to ").concat(i,".")),t.liveMaxUnchangedPlaylistRefresh=i}var a=deepCpy(e),s=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(function(e){var n="".concat("level"===e?"playlist":e,"LoadPolicy"),i=void 0===t[n],o=[];s.forEach(function(r){var s="".concat(e,"Loading").concat(r),l=t[s];if(void 0!==l&&i){o.push(s);var u=a[n].default;switch(t[n]={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(n,'": ').concat(stringify(t[n])))}),_objectSpread2(_objectSpread2({},a),t)}function deepCpy(e){return e&&"object"===_typeof(e)?Array.isArray(e)?e.map(deepCpy):Object.keys(e).reduce(function(t,r){return t[r]=deepCpy(e[r]),t},{}):e}function enableStreamingMode(e,t){var r=e.loader;r!==FetchLoader&&r!==XhrLoader?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1):fetchSupported()&&(e.loader=FetchLoader,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}var LevelController=function(){function e(t,r){var n;return _classCallCheck(this,e),(n=_callSuper(this,e,[t,"level-controller"]))._levels=[],n._firstLevel=-1,n._maxAutoLevel=-1,n._startLevel=void 0,n.currentLevel=null,n.currentLevelIndex=-1,n.manualLevelIndex=-1,n.steering=void 0,n.lastABRSwitchTime=-1,n._iframeVariants=[],n.onParsedComplete=void 0,n.steering=r,n._registerListeners(),n}return _inherits(e,BasePlaylistController),_createClass(e,[{key:"_registerListeners",value:function(){var e=this.hls;e.on(Events$2.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events$2.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Events$2.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Events$2.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Events$2.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Events$2.ERROR,this.onError,this)}},{key:"_unregisterListeners",value:function(){var e=this.hls;e.off(Events$2.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events$2.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Events$2.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Events$2.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Events$2.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Events$2.ERROR,this.onError,this)}},{key:"destroy",value:function(){this._unregisterListeners(),this.steering=null,this.resetLevels(),_superPropGet(e,"destroy",this)([])}},{key:"stopLoad",value:function(){this._levels.forEach(function(e){e.loadError=0,e.fragmentError=0}),_superPropGet(e,"stopLoad",this)([])}},{key:"resetLevels",value:function(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1,this._iframeVariants=[]}},{key:"onManifestLoading",value:function(e,t){this.resetLevels()}},{key:"onManifestLoaded",value:function(e,t){var r=this,n=this.hls.config.preferManagedMediaSource,i=[],a={},s={},o=!1,l=!1,u=!1,c=!1;t.levels.forEach(function(e){var t=e.attrs,d=setTrackCodecsAndReturnSupported(e,n),h=e.audioCodec,f=e.videoCodec,v=e.imageCodec,p=e.width,g=e.height;if(d){o||(o=!(!p||!g)),l||(l=!!f),u||(u=!!h),c||(c=!!v);var y=t.CODECS,m=t["FRAME-RATE"],E=t["HDCP-LEVEL"],S=t["PATHWAY-ID"],T=t.RESOLUTION,k=t["VIDEO-RANGE"],_="".concat(S||".","-"),A="".concat(_).concat(e.bitrate,"-").concat(T,"-").concat(m,"-").concat(y,"-").concat(k,"-").concat(E);if(a[A])if(a[A].uri===e.url||e.attrs["PATHWAY-ID"])e.iframes||(a[A].addGroupId("audio",t.AUDIO),a[A].addGroupId("text",t.SUBTITLES));else{var b=s[A]+=1;e.attrs["PATHWAY-ID"]=new Array(b+1).join(".");var L=r.createLevel(e);a[A]=L,i.push(L)}else{var R=r.createLevel(e);a[A]=R,s[A]=1,i.push(R)}}else r.log('Some or all CODECS not supported "'.concat(t.CODECS,'"'))}),this.filterAndSortMediaOptions(i,t,o,l,u,c)}},{key:"createLevel",value:function(e){var t=new Level(e),r=e.supplemental;if(null!=r&&r.videoCodec&&!isVideoSupported(r.videoCodec,this.hls.config.preferManagedMediaSource)){var n=new Error('SUPPLEMENTAL-CODECS not supported "'.concat(r.videoCodec,'"'));this.log(n.message),t.supportedResult=getUnsupportedResult(n,[])}return t}},{key:"filterAndSortMediaOptions",value:function(e,t,r,n,i,a){var s,o=this,l=[],u=[],c=e,d=(null==(s=t.stats)?void 0:s.parsing)||{},h=this.hls.config.preferManagedMediaSource;if((r||n)&&i&&(c=c.filter(function(e){var t=e.videoCodec,r=e.videoRange,n=e.width,i=e.height;return(!!t||!(!n||!i))&&isVideoRange(r)})),n&&a&&(c=c.filter(function(e){return!e.imageCodec})),0===c.length)return Promise.resolve().then(function(){if(o.hls){var e="no level with compatible codecs found in manifest",r=e;t.levels.length&&(r="one or more CODECS in variant not supported: ".concat(stringify(t.levels.map(function(e){return e.attrs.CODECS}).filter(function(e,t,r){return r.indexOf(e)===t}))),o.warn(r),e+=" (".concat(r,")"));var n=new Error(e);o.hls.trigger(Events$2.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:n,reason:r})}}),void(d.end=performance.now());t.audioTracks&&assignTrackIdsByGroup(l=t.audioTracks.filter(function(e){return!e.audioCodec||isAudioSupported(e.audioCodec,h)})),t.subtitles&&assignTrackIdsByGroup(u=t.subtitles);var f=c.slice(0);c.sort(function(e,t){if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return VideoRangeValues.indexOf(e.videoRange)-VideoRangeValues.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){var n=videoCodecPreferenceValue(e.videoCodec),i=videoCodecPreferenceValue(t.videoCodec);if(n!==i)return i-n}if(e.uri===t.uri&&e.codecSet!==t.codecSet){var a=codecsSetSelectionPreferenceValue(e.codecSet),s=codecsSetSelectionPreferenceValue(t.codecSet);if(a!==s)return s-a}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0});var v=f[0];if(this.steering&&(c=this.steering.filterParsedLevels(c)).length!==f.length)for(var p=0;p<f.length;p++)if(f[p].pathwayId===c[0].pathwayId){v=f[p];break}this._levels=c;for(var g=0;g<c.length;g++)if(c[g]===v){var y;this._firstLevel=g;var m=v.bitrate,E=this.hls.bandwidthEstimate;if(this.log("manifest loaded, ".concat(c.length," level(s) found, first bitrate: ").concat(m)),void 0===(null==(y=this.hls.userConfig)?void 0:y.abrEwmaDefaultEstimate)){var S=Math.min(m,this.hls.config.abrEwmaDefaultEstimateMax);S>E&&E===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=S)}break}var T=t.iframeVariants.filter(function(e){return setTrackCodecsAndReturnSupported(e,h)});this._iframeVariants=T;var k=i&&!n,_=this.hls.config,A=!(!_.audioStreamController||!_.audioTrackController),b={levels:c,audioTracks:l,subtitleTracks:u,iframeVariants:T,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:i,video:n,altAudio:A&&!k&&l.some(function(e){return!!e.url})};d.end=performance.now(),this.hls.trigger(Events$2.MANIFEST_PARSED,b)}},{key:"iframeVariants",get:function(){return 0===this._iframeVariants.length?null:this._iframeVariants}},{key:"levels",get:function(){return 0===this._levels.length?null:this._levels}},{key:"loadLevelObj",get:function(){return this.currentLevel}},{key:"level",get:function(){return this.currentLevelIndex},set:function(e){var t=this._levels;if(0!==t.length){if(e<0||e>=t.length){var r=new Error("invalid level idx"),n=e<0;if(this.hls.trigger(Events$2.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.LEVEL_SWITCH_ERROR,level:e,fatal:n,error:r,reason:r.message}),n)return;e=Math.min(e,t.length-1)}var i=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,i!==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(i).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(Events$2.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===LoaderContextType.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}},{key:"onFragBuffered",value:function(e,t){var r=t.frag;if(r.type===PlaylistLevelType.MAIN){var n=r.elementaryStreams;if(!Object.keys(n).some(function(e){return!!n[e]}))return;var i=this._levels[r.level];null!=i&&i.loadError&&(this.log("Resetting level error count of ".concat(i.loadError," on frag buffered")),i.loadError=0)}}},{key:"onLevelLoaded",value:function(e,t){var r,n,i=t.level,a=t.details,s=t.levelInfo;if(!s)return this.warn("Invalid level index ".concat(i)),void(null!=(n=t.deliveryDirectives)&&n.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(i,t,o)}else null!=(r=t.deliveryDirectives)&&r.skip&&(a.deltaUpdateFailed=!0)}},{key:"loadPlaylist",value:function(t){_superPropGet(e,"loadPlaylist",this)([]),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)}},{key:"loadingPlaylist",value:function(t,r){_superPropGet(e,"loadingPlaylist",this)([t,r]);var n=this.getUrlWithDirectives(t.uri,r),i=this.currentLevelIndex,a=t.attrs["PATHWAY-ID"],s=t.details,o=null==s?void 0:s.age;this.log("Loading level index ".concat(i).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(n)),this.hls.trigger(Events$2.LEVEL_LOADING,{url:n,level:i,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:r||null})}},{key:"nextLoadLevel",get:function(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},set:function(e){var t=this.currentLevelIndex;if(-1===this.manualLevelIndex&&e!==t&&-1!==e){var r=this.hls.config.abrSwitchInterval;if(r>0){var n=performance.now(),i=n-this.lastABRSwitchTime,a=1e3*r;if(this.lastABRSwitchTime>-1&&i<a)return void this.warn("Preventing ABR level switch: ".concat(t," -> ").concat(e," (").concat(Math.round(i),"ms < ").concat(a,"ms / ").concat(r,"s)"));this.lastABRSwitchTime=n,this.log("Allowing ABR level switch: ".concat(t," -> ").concat(e," (").concat(Math.round(i),"ms >= ").concat(a,"ms / ").concat(r,"s)"))}}this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}},{key:"removeLevel",value:function(e){var t,r=this;if(1!==this._levels.length){var n=this._levels.filter(function(t,n){return n!==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)});reassignFragmentLevelIndexes(n),this._levels=n,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 i=n.length-1;this._firstLevel=Math.min(this._firstLevel,i),this._startLevel&&(this._startLevel=Math.min(this._startLevel,i)),this.hls.trigger(Events$2.LEVELS_UPDATED,{levels:n})}}},{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,n=e.maxHdcpLevel;this._maxAutoLevel!==r&&(this._maxAutoLevel=r,this.hls.trigger(Events$2.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:r,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:n}))}}])}();function isAudioSupported(e,t){return areCodecsMediaSourceSupported(e,"audio",t)}function isVideoSupported(e,t){return areCodecsMediaSourceSupported(e,"video",t)}function setTrackCodecsAndReturnSupported(e,t){var r=e.audioCodec,n=e.videoCodec;r&&(e.audioCodec=r=getCodecCompatibleName(r,t)||void 0),n&&(n=e.videoCodec=convertAVC1ToAVCOTI(n));var i=e.unknownCodecs;return!((null==i?void 0:i.length)||0||r&&!isAudioSupported(r,t)||n&&!isVideoSupported(n,t))}function assignTrackIdsByGroup(e){var t={};e.forEach(function(e){var r=e.groupId||"";e.id=t[r]=t[r]||0,t[r]++})}var KeyLoader=function(){function e(t,r){var n;return _classCallCheck(this,e),(n=_callSuper(this,e,["key-loader",r])).config=void 0,n.keyLoaderInfo={},n.emeController=null,n.config=t,n}return _inherits(e,Logger$1),_createClass(e,[{key:"abort",value:function(e){for(var t in this.keyLoaderInfo){var r=this.keyLoaderInfo[t].loader;if(r){var n;if(e&&e!==(null==(n=r.context)?void 0:n.frag.type))return;r.abort()}}}},{key:"destroy",value:function(){for(var e in this.keyLoaderInfo){var t=this.keyLoaderInfo[e].loader;t&&t.destroy()}this.emeController=null,this.keyLoaderInfo={}}},{key:"loadClear",value:function(e,t,r){return this.emeController?this.emeController.loadClear(e,t,r):null}},{key:"load",value:function(e,t){var r=this;return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(function(n){return r.loadInternal(e,t,n)}):this.loadInternal(e,t)}},{key:"loadInternal",value:function(e,t,r){var n=this;r&&e.setKeyFormat(r);var i=e.decryptdata;if(!i){var a=new Error(r?"Expected frag.decryptdata to be defined after setting format ".concat(r):"Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ".concat(this.emeController&&this.config.emeEnabled,")"));return Promise.reject(createKeyLoadError(e,ErrorDetails.KEY_LOAD_ERROR,a))}var s=e;switch(i.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===i.keyFormat?this.loadKeyHTTP(s):t?t.then(function(){return n.loadKeyEME(s)}):this.loadKeyEME(s);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(s);default:return Promise.reject(createKeyLoadError(e,ErrorDetails.KEY_LOAD_ERROR,new Error('Key supplied with unsupported METHOD: "'.concat(i.method,'"'))))}}},{key:"loadKeyEME",value:function(e){if(this.emeController&&this.config.emeEnabled){var t;if(!e.decryptdata.keyId&&null!=(t=e.initSegment)&&t.data){var r=parseKeyIdsFromTenc(e.initSegment.data);if(r.length){var n=r[0],i=e.decryptdata.uri;if(n.some(function(e){return 0!==e}))this.log("Using keyId found in init segment ".concat(arrayToHex(n)," keyUri: ").concat(i)),LevelKey.setKeyIdForUri(i,n);else{var a=LevelKey.addKeyIdForUri(i);this.log("Patching empty keyId with ".concat(arrayToHex(a)," keyUri: ").concat(i)),n=a}e.decryptdata.keyId=n}}return this.emeController.loadKey(e).then(function(){return{frag:e,keyInfo:{decryptdata:e.decryptdata}}})}return Promise.reject(createKeyLoadError(e,ErrorDetails.KEY_LOAD_ERROR,new Error("emeEnabled with controller: ".concat(this.emeController&&this.config.emeEnabled,")"))))}},{key:"loadKeyHTTP",value:function(e){var t=this,r=e.decryptdata,n=r.uri;if(!n)return Promise.reject(createKeyLoadError(e,ErrorDetails.KEY_LOAD_ERROR,new Error('Invalid key URI: "'.concat(n,'"'))));var i=this.keyLoaderInfo[n];if(i){if(i.decryptdata.key)return r.key=i.decryptdata.key,i.keyLoadPromise=null,Promise.resolve({frag:e,keyInfo:i});if(i.keyLoadPromise)return i.keyLoadPromise.then(function(t){return r.key=i.decryptdata.key,_objectSpread2(_objectSpread2({},t),{},{frag:e})})}this.log("Loading".concat(r.keyId?" keyId: "+arrayToHex(r.keyId):""," URI: ").concat(r.uri," from ").concat(e.type," ").concat(e.level));var a=this.config,s=new(0,a.loader)(a);e.keyLoader=s;var o=this.keyLoaderInfo[n]={decryptdata:r,keyLoadPromise:null,loader:s};return o.keyLoadPromise=new Promise(function(r,i){var l={type:LoaderContextType.KEY,keyInfo:o,frag:e,responseType:"arraybuffer",url:n},u=a.keyLoadPolicy.default,c={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:function(e,n,a,s){var o=a.frag,l=a.keyInfo,u=a.url;if(!o.decryptdata||l!==t.keyLoaderInfo[u])return i(createKeyLoadError(o,ErrorDetails.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),s));l.decryptdata.key=o.decryptdata.key=new Uint8Array(e.data),o.keyLoader=l.loader=l.keyLoadPromise=null,r({frag:o,keyInfo:l})},onError:function(r,a,s,o){t.resetLoader(a),i(createKeyLoadError(e,ErrorDetails.KEY_LOAD_ERROR,new Error("HTTP Error ".concat(r.code," loading key ").concat(r.text)),s,_objectSpread2({url:n,data:void 0},r)))},onTimeout:function(r,n,a){t.resetLoader(n),i(createKeyLoadError(e,ErrorDetails.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),a))},onAbort:function(r,n,a){t.resetLoader(n),i(createKeyLoadError(e,ErrorDetails.INTERNAL_ABORTED,new Error("key loading aborted"),a))}};s.load(l,c,d)})}},{key:"resetLoader",value:function(e){var t=e.frag,r=e.keyInfo,n=e.url,i=r.loader;t.keyLoader===i&&(t.keyLoader=r.loader=r.keyLoadPromise=null),delete this.keyLoaderInfo[n],i&&i.destroy()}}])}();function createKeyLoadError(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ErrorDetails.KEY_LOAD_ERROR,r=arguments.length>2?arguments[2]:void 0,n=arguments.length>3?arguments[3]:void 0,i=arguments.length>4?arguments[4]:void 0;return new LoadError({type:ErrorTypes.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:i,error:r,networkDetails:n||null})}function mapContextToLevelType(e){switch(e.type){case LoaderContextType.AUDIO_TRACK:return PlaylistLevelType.AUDIO;case LoaderContextType.SUBTITLE_TRACK:return PlaylistLevelType.SUBTITLE;default:return PlaylistLevelType.MAIN}}function getResponseUrl(e,t){var r=e.url;return void 0!==r&&0!==r.indexOf("data:")||(r=t.url),r}var PlaylistLoader=function(){return _createClass(function e(t){_classCallCheck(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(Events$2.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events$2.LEVEL_LOADING,this.onLevelLoading,this),e.on(Events$2.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(Events$2.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(Events$2.LEVELS_UPDATED,this.onLevelsUpdated,this)}},{key:"unregisterListeners",value:function(){var e=this.hls;e.off(Events$2.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events$2.LEVEL_LOADING,this.onLevelLoading,this),e.off(Events$2.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(Events$2.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(Events$2.LEVELS_UPDATED,this.onLevelsUpdated,this)}},{key:"createInternalLoader",value:function(e){var t=this.hls.config,r=t.pLoader,n=t.loader,i=new(r||n)(t);return this.loaders[e.type]=i,i}},{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:LoaderContextType.MANIFEST,url:r,deliveryDirectives:null,levelOrTrack:null})}},{key:"onLevelLoading",value:function(e,t){var r=t.id,n=t.level,i=t.pathwayId,a=t.url,s=t.deliveryDirectives,o=t.levelInfo;this.load({id:r,level:n,pathwayId:i,responseType:"text",type:LoaderContextType.LEVEL,url:a,deliveryDirectives:s,levelOrTrack:o})}},{key:"onAudioTrackLoading",value:function(e,t){var r=t.id,n=t.groupId,i=t.url,a=t.deliveryDirectives,s=t.track;this.load({id:r,groupId:n,level:null,responseType:"text",type:LoaderContextType.AUDIO_TRACK,url:i,deliveryDirectives:a,levelOrTrack:s})}},{key:"onSubtitleTrackLoading",value:function(e,t){var r=t.id,n=t.groupId,i=t.url,a=t.deliveryDirectives,s=t.track;this.load({id:r,groupId:n,level:null,responseType:"text",type:LoaderContextType.SUBTITLE_TRACK,url:i,deliveryDirectives:a,levelOrTrack:s})}},{key:"onLevelsUpdated",value:function(e,t){var r=this.loaders[LoaderContextType.LEVEL];if(r){var n=r.context;n&&!t.levels.some(function(e){return e===n.levelOrTrack})&&(r.abort(),delete this.loaders[LoaderContextType.LEVEL])}}},{key:"load",value:function(e){var t,r,n,i=this,a=this.hls.config,s=this.getInternalLoader(e);if(s){var o=this.hls.logger,l=s.context;if((null==l?void 0:l.levelOrTrack)===e.levelOrTrack&&(l.url===e.url||l.deliveryDirectives&&!e.deliveryDirectives))return void(l.url===e.url?o.log("[playlist-loader]: ignore ".concat(e.url," ongoing request")):o.log("[playlist-loader]: ignore ".concat(e.url," in favor of ").concat(l.url)));o.log("[playlist-loader]: aborting previous loader for type: ".concat(e.type)),s.abort()}if((r=e.type===LoaderContextType.MANIFEST?a.manifestLoadPolicy.default:_extends({},a.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),isFiniteNumber(null==(t=e.deliveryDirectives)?void 0:t.part))&&(e.type===LoaderContextType.LEVEL&&null!==e.level?n=this.hls.levels[e.level].details:e.type===LoaderContextType.AUDIO_TRACK&&null!==e.id?n=this.hls.audioTracks[e.id].details:e.type===LoaderContextType.SUBTITLE_TRACK&&null!==e.id&&(n=this.hls.subtitleTracks[e.id].details),n)){var u=n.partTarget,c=n.targetduration;if(u&&c){var d=1e3*Math.max(3*u,.8*c);r=_extends({},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,n){var a=i.getInternalLoader(r);i.resetInternalLoader(r.type);var s=e.data;t.parsing.start=performance.now(),M3U8Parser.isMediaPlaylist(s)||r.type!==LoaderContextType.MANIFEST?i.handleTrackOrLevelPlaylist(e,t,r,n||null,a):i.handleMasterPlaylist(e,t,r,n)},onError:function(e,t,r,n){i.handleNetworkError(t,r,!1,e,n)},onTimeout:function(e,t,r){i.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,n=t.startPosition,i=e.forceStartLoad;(r||i)&&(this.hls.logger.log("".concat(r?"auto":"force"," startLoad with configured startPosition ").concat(n)),this.hls.startLoad(n))}}},{key:"handleMasterPlaylist",value:function(e,t,r,n){var i=this,a=this.hls,s=e.data,o=getResponseUrl(e,r),l=M3U8Parser.parseMasterPlaylist(s,o);if(l.playlistParsingError)return t.parsing.end=performance.now(),void this.handleManifestParsingError(e,r,l.playlistParsingError,n,t);var u=l.contentSteering,c=l.levels,d=l.iframeVariants,h=l.sessionData,f=l.sessionKeys,v=l.startTimeOffset,p=l.variableList;this.variableList=p,c.forEach(function(e){var t=e.unknownCodecs;if(t)for(var r=i.hls.config.preferManagedMediaSource,n=e.audioCodec,a=e.videoCodec,s=t.length;s--;){var o=t[s];areCodecsMediaSourceSupported(o,"audio",r)?(e.audioCodec=n=n?"".concat(n,",").concat(o):o,sampleEntryCodesISO.audio[n.substring(0,4)]=2,t.splice(s,1)):areCodecsMediaSourceSupported(o,"video",r)&&(e.videoCodec=a=a?"".concat(a,",").concat(o):o,sampleEntryCodesISO.video[a.substring(0,4)]=2,t.splice(s,1))}});var g=M3U8Parser.parseMasterPlaylistMedia(s,o,l),y=g.AUDIO,m=void 0===y?[]:y,E=g.SUBTITLES,S=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 AttrList({}),bitrate:0,url:""})));a.trigger(Events$2.MANIFEST_LOADED,{levels:c,audioTracks:m,subtitles:E,iframeVariants:d,captions:S,contentSteering:u,url:o,stats:t,networkDetails:n,sessionData:h,sessionKeys:f,startTimeOffset:v,variableList:p})}},{key:"handleTrackOrLevelPlaylist",value:function(e,t,r,n,i){var a=this.hls,s=r.id,o=r.level,l=r.type,u=getResponseUrl(e,r),c=isFiniteNumber(o)?o:isFiniteNumber(s)?s:0,d=mapContextToLevelType(r),h=M3U8Parser.parseLevelPlaylist(e.data,u,c,d,0,this.variableList);if(l===LoaderContextType.MANIFEST){var f={attrs:new AttrList({}),bitrate:0,details:h,name:"",url:u};h.requestScheduled=t.loading.start+computeReloadInterval(h,0),a.trigger(Events$2.MANIFEST_LOADED,{levels:[f],audioTracks:[],iframeVariants:[],url:u,stats:t,networkDetails:n,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),r.levelDetails=h,this.handlePlaylistLoaded(h,e,t,r,n,i)}},{key:"handleManifestParsingError",value:function(e,t,r,n,i){this.hls.trigger(Events$2.ERROR,{type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.MANIFEST_PARSING_ERROR,fatal:t.type===LoaderContextType.MANIFEST,url:e.url,err:r,error:r,reason:r.message,response:e,context:t,networkDetails:n,stats:i})}},{key:"handleNetworkError",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3?arguments[3]:void 0,i=arguments.length>4?arguments[4]:void 0,a="A network ".concat(r?"timeout":"error"+(n?" (status "+n.code+")":"")," occurred while loading ").concat(e.type);e.type===LoaderContextType.LEVEL?a+=": ".concat(e.level," id: ").concat(e.id):e.type!==LoaderContextType.AUDIO_TRACK&&e.type!==LoaderContextType.SUBTITLE_TRACK||(a+=" id: ".concat(e.id,' group-id: "').concat(e.groupId,'"'));var s=new Error(a);this.hls.logger.warn("[playlist-loader]: ".concat(a));var o=ErrorDetails.UNKNOWN,l=!1,u=this.getInternalLoader(e);switch(e.type){case LoaderContextType.MANIFEST:o=r?ErrorDetails.MANIFEST_LOAD_TIMEOUT:ErrorDetails.MANIFEST_LOAD_ERROR,l=!0;break;case LoaderContextType.LEVEL:o=r?ErrorDetails.LEVEL_LOAD_TIMEOUT:ErrorDetails.LEVEL_LOAD_ERROR,l=!1;break;case LoaderContextType.AUDIO_TRACK:o=r?ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:ErrorDetails.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case LoaderContextType.SUBTITLE_TRACK:o=r?ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:ErrorDetails.SUBTITLE_LOAD_ERROR,l=!1}u&&this.resetInternalLoader(e.type);var c={type:ErrorTypes.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:u,context:e,error:s,networkDetails:t,stats:i};if(n){var d=e.url;t&&"url"in t&&(d=t.url),c.response=_objectSpread2({url:d,data:void 0},n)}this.hls.trigger(Events$2.ERROR,c)}},{key:"handlePlaylistLoaded",value:function(e,t,r,n,i,a){var s=this.hls,o=n.type,l=n.level,u=n.levelOrTrack,c=n.id,d=n.groupId,h=n.deliveryDirectives,f=getResponseUrl(t,n),v=mapContextToLevelType(n),p="number"==typeof n.level&&v===PlaylistLevelType.MAIN?l:void 0;u&&"iframes"in u&&u.iframes&&!e.iframesOnly&&(e.playlistParsingError=new Error("EXT-X-I-FRAME-STREAM-INF media playlist MUST contain an EXT-X-I-FRAMES-ONLY tag"),e.iframesOnly=!0);var g=e.playlistParsingError;if(g){if(this.hls.logger.warn("".concat(g," ").concat(e.url)),!s.config.ignorePlaylistParsingErrors)return void s.trigger(Events$2.ERROR,{type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:g,reason:g.message,response:t,context:n,level:p,parent:v,networkDetails:i,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 LoaderContextType.MANIFEST:case LoaderContextType.LEVEL:if(p)if(u){if(u!==s.levels[p]){var y=s.levels.indexOf(u);y>-1&&(p=y)}}else p=0;s.trigger(Events$2.LEVEL_LOADED,{details:e,levelInfo:u||s.levels[0],level:p||0,id:c||0,stats:r,networkDetails:i,deliveryDirectives:h,withoutMultiVariant:o===LoaderContextType.MANIFEST,context:n});break;case LoaderContextType.AUDIO_TRACK:s.trigger(Events$2.AUDIO_TRACK_LOADED,{details:e,track:u,id:c||0,groupId:d||"",stats:r,networkDetails:i,deliveryDirectives:h,context:n});break;case LoaderContextType.SUBTITLE_TRACK:s.trigger(Events$2.SUBTITLE_TRACK_LOADED,{details:e,track:u,id:c||0,groupId:d||"",stats:r,networkDetails:i,deliveryDirectives:h,context:n})}else{var m=e.playlistParsingError=new Error("No Segments found in Playlist");s.trigger(Events$2.ERROR,{type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:m,reason:m.message,response:t,context:n,level:p,parent:v,networkDetails:i,stats:r})}}}])}(),Hls=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};_classCallCheck(this,e),this.config=void 0,this.userConfig=void 0,this.logger=void 0,this._url=null,this.streamController=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new EventEmitter,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.iframeController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;var r=this.logger=enableLogs(t.debug||!1,"Hls instance",t.loggerId||t.assetPlayerId),n=this.config=mergeConfig$1(e.DefaultConfig,t,r);this.userConfig=t,n.progressive&&enableStreamingMode(n,r);var i=n.streamController,a=n.abrController,s=n.bufferController,o=n.capLevelController,l=n.errorController,u=n.fpsController,c=n.id3TrackController,d=n.iframeController,h=n.gapController,f=new l(this),v=this.abrController=new a(this),p=new FragmentTracker(this),g=n.interstitialsController,y=g?this.interstitialsController=new g(this,e):null,m=s?this.bufferController=new s(this,p):null,E=o?this.capLevelController=new o(this):null,S=u?new u(this):null,T=n.cmcdController,k=T?this.cmcdController=new T(this):null,_=new PlaylistLoader(this),A=n.contentSteeringController,b=A?new A(this):null,L=this.levelController=new LevelController(this,b),R=c?new c(this):void 0,C=new KeyLoader(this.config,this.logger),I=this.streamController=new i(this,p,C),P=this.gapController=h?new h(this,p):void 0;E&&E.setStreamController(I);var D=[_,L,I];y&&D.splice(1,0,y),b&&D.splice(1,0,b),this.networkControllers=D;var w=[v];m&&w.push(m),P&&w.push(P),E&&w.push(E),S&&(S.setStreamController(I),w.push(S)),R&&w.push(R),w.push(p),this.audioTrackController=this.createController(n.audioTrackController,D);var O=n.audioStreamController;O&&D.push(this.audioStreamController=new O(this,p,C)),this.subtitleTrackController=this.createController(n.subtitleTrackController,D);var x=n.subtitleStreamController;x&&D.push(this.subtititleStreamController=new x(this,p,C)),this.createController(n.timelineController,w),C.emeController=this.emeController=this.createController(n.emeController,w),k&&w.push(k),this.latencyController=this.createController(n.latencyController,w),this.coreComponents=w,this.iframeController=d?new d(this,e):void 0,D.push(f);var M=f.onErrorOut;"function"==typeof M&&this.on(Events$2.ERROR,M,f),this.on(Events$2.MANIFEST_LOADED,_.onManifestLoaded,_)}return _createClass(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,n=arguments.length>3?arguments[3]:void 0;this._emitter.off(e,t,r,n)}},{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(n){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+n.message+'". Here is a stacktrace:',n),!this.triggeringException){this.triggeringException=!0;var r=e===Events$2.ERROR;this.trigger(Events$2.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.INTERNAL_EXCEPTION,fatal:r,event:e,error:n}),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(Events$2.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(function(e){return e.destroy()}),this.networkControllers.length=0,this.coreComponents.forEach(function(e){return e.destroy()}),this.coreComponents.length=0,this.iframeController=void 0;var e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}},{key:"attachMedia",value:function(e){if(!e||"media"in e&&!e.media){var t=new Error("attachMedia failed: invalid argument (".concat(e,")"));this.trigger(Events$2.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.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,n=r?e.media:e,i=r?e:{media:n};this._media=n,this.trigger(Events$2.MEDIA_ATTACHING,i)}}},{key:"detachMedia",value:function(){this.logger.log("detachMedia");var e={};this.trigger(Events$2.MEDIA_DETACHING,e),this._media=null,this.trigger(Events$2.MEDIA_DETACHED,e)}},{key:"transferMedia",value:function(){var e;this._media=null;var t=(null==(e=this.bufferController)?void 0:e.transferMedia())||null,r={transferMedia:t};return this.trigger(Events$2.MEDIA_DETACHING,r),this.trigger(Events$2.MEDIA_DETACHED,r),t}},{key:"loadSource",value:function(e){var t;this.stopLoad();var r=this.media,n=this._url,i=this._url=urlToolkitExports.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log("loadSource:".concat(i)),r&&n&&(n!==i||null!=(t=this.bufferController)&&t.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(r)),this.trigger(Events$2.MANIFEST_LOADING,{url:e})}},{key:"url",get:function(){return this._url}},{key:"hasEnoughToStart",get:function(){return this.streamController.hasEnoughToStart}},{key:"startPosition",get:function(){return this.streamController.startPositionValue}},{key:"startLoad",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:-1,t=arguments.length>1?arguments[1]:void 0;this.logger.log("startLoad(".concat(e+(t?", <skip seek to start>":""),")")),this.started=!0,this.resumeBuffering();for(var r=0;r<this.networkControllers.length&&(this.networkControllers[r].startLoad(e,t),this.started&&this.networkControllers);r++);}},{key:"stopLoad",value:function(){this.logger.log("stopLoad"),this.started=!1;for(var e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!this.started&&this.networkControllers);e++);}},{key:"loadingEnabled",get:function(){return this.started&&this.streamController.state!==State.STOPPED}},{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=_defineProperty$1({},PlaylistLevelType.MAIN,this.streamController.inFlightFrag);return this.audioStreamController&&(e[PlaylistLevelType.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[PlaylistLevelType.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}},{key:"swapAudioCodec",value:function(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}},{key:"recoverMediaError",value:function(){this.logger.log("recoverMediaError");var e=this._media,t=this.started,r=null==e?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&(r?this.startLoad(r):this.config.autoStartLoad||this.startLoad()))}},{key:"removeLevel",value:function(e){this.levelController.removeLevel(e)}},{key:"sessionId",get:function(){var e=this._sessionId;return e||(e=this._sessionId=uuid()),e}},{key:"levels",get:function(){var e=this.levelController.levels;return e||[]}},{key:"latestLevelDetails",get:function(){return this.streamController.getLevelDetails()||null}},{key:"loadLevelObj",get:function(){return this.levelController.loadLevelObj}},{key:"currentLevel",get:function(){return this.streamController.currentLevel},set:function(e){this.logger.log("set currentLevel:".concat(e)),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}},{key:"nextLevel",get:function(){return this.streamController.nextLevel},set:function(e){this.logger.log("set nextLevel:".concat(e)),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}},{key:"loadLevel",get:function(){return this.levelController.level},set:function(e){this.logger.log("set loadLevel:".concat(e)),this.levelController.manualLevel=e}},{key:"nextLoadLevel",get:function(){return this.levelController.nextLoadLevel},set:function(e){this.levelController.nextLoadLevel=e}},{key:"firstLevel",get:function(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)},set:function(e){this.logger.log("set firstLevel:".concat(e)),this.levelController.firstLevel=e}},{key:"startLevel",get:function(){var e=this.levelController.startLevel;return-1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e},set:function(e){this.logger.log("set startLevel:".concat(e)),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}},{key:"capLevelToPlayerSize",get:function(){return this.config.capLevelToPlayerSize},set:function(e){var t=this.capLevelController,r=!!e;t&&r!==this.config.capLevelToPlayerSize&&(r?t.startCapping():(t.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=r)}},{key:"autoLevelCapping",get:function(){return this._autoLevelCapping},set:function(e){this._autoLevelCapping!==e&&(this.logger.log("set autoLevelCapping:".concat(e)),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}},{key:"bandwidthEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.getEstimate():NaN},set:function(e){this.abrController.resetEstimator(e)}},{key:"abrEwmaDefaultEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.defaultEstimate:NaN}},{key:"ttfbEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.getEstimateTTFB():NaN}},{key:"maxHdcpLevel",get:function(){return this._maxHdcpLevel},set:function(e){isHdcpLevel(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,n=0;n<r;n++)if(e[n].maxBitrate>=t)return n;return 0}},{key:"maxAutoLevel",get:function(){var e,t=this.levels,r=this.autoLevelCapping,n=this.maxHdcpLevel;if(e=-1===r&&null!=t&&t.length?t.length-1:r,n)for(var i=e;i--;){var a=t[i].attrs["HDCP-LEVEL"];if(a&&a<=n)return i}return e}},{key:"firstAutoLevel",get:function(){return this.abrController.firstAutoLevel}},{key:"nextAutoLevel",get:function(){return this.abrController.nextAutoLevel},set:function(e){this.abrController.nextAutoLevel=e}},{key:"playingDate",get:function(){return this.streamController.currentProgramDateTime}},{key:"mainForwardBufferInfo",get:function(){return this.streamController.getMainFwdBufferInfo()}},{key:"audioForwardBufferInfo",get:function(){var e;return(null==(e=this.audioStreamController)?void 0:e.getFwdBufferInfo())||null}},{key:"maxBufferLength",get:function(){return this.streamController.maxBufferLength}},{key:"setAudioOption",value:function(e){var t;return(null==(t=this.audioTrackController)?void 0:t.setAudioOption(e))||null}},{key:"setSubtitleOption",value:function(e){var t;return(null==(t=this.subtitleTrackController)?void 0:t.setSubtitleOption(e))||null}},{key:"allAudioTracks",get:function(){var e=this.audioTrackController;return e?e.allAudioTracks:[]}},{key:"audioTracks",get:function(){var e=this.audioTrackController;return e?e.audioTracks:[]}},{key:"audioTrack",get:function(){var e=this.audioTrackController;return e?e.audioTrack:-1},set:function(e){var t=this.audioTrackController;t&&(t.audioTrack=e)}},{key:"nextAudioTrack",get:function(){var e,t;return null!=(e=null==(t=this.audioStreamController)?void 0:t.nextAudioTrack)?e:-1},set:function(e){var t=this.audioTrackController;t&&(t.nextAudioTrack=e)}},{key:"allSubtitleTracks",get:function(){var e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}},{key:"subtitleTracks",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTracks:[]}},{key:"subtitleTrack",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTrack:-1},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}},{key:"media",get:function(){return this._media}},{key:"subtitleDisplay",get:function(){var e=this.subtitleTrackController;return!!e&&e.subtitleDisplay},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}},{key:"lowLatencyMode",get:function(){return this.config.lowLatencyMode},set:function(e){this.config.lowLatencyMode=e}},{key:"liveSyncPosition",get:function(){var e,t;return null!=(e=null==(t=this.latencyController)?void 0:t.liveSyncPosition)?e:null}},{key:"latency",get:function(){var e;return(null==(e=this.latencyController)?void 0:e.latency)||0}},{key:"maxLatency",get:function(){var e;return(null==(e=this.latencyController)?void 0:e.maxLatency)||0}},{key:"targetLatency",get:function(){var e;return(null==(e=this.latencyController)?void 0:e.targetLatency)||null},set:function(e){this.latencyController&&(this.latencyController.targetLatency=e)}},{key:"drift",get:function(){var e;return(null==(e=this.latencyController)?void 0:e.drift)||null}},{key:"forceStartLoad",get:function(){return this.streamController.forceStartLoad}},{key:"pathways",get:function(){return this.levelController.pathways}},{key:"pathwayPriority",get:function(){return this.levelController.pathwayPriority},set:function(e){this.levelController.pathwayPriority=e}},{key:"bufferedToEnd",get:function(){var e;return!(null==(e=this.bufferController)||!e.bufferedToEnd)}},{key:"interstitialsManager",get:function(){return this.interstitialsController?this.interstitialsController.interstitialsManager:null}},{key:"iframeVariants",get:function(){var e=this.levelController.iframeVariants;return e||[]}},{key:"createIFramePlayer",value:function(e){return this._url&&this.iframeController?this.iframeController.createIFramePlayer(e):null}},{key:"createImageIFramePlayer",value:function(e){return this._url&&this.iframeController?this.iframeController.createImageIFramePlayer(e):null}},{key:"getMediaDecodingInfo",value:function(e){return getMediaDecodingInfoPromise(e,getAudioTracksByGroup(arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.allAudioTracks),navigator.mediaCapabilities)}}],[{key:"version",get:function(){return version}},{key:"isMSESupported",value:function(){return _isMSESupported()}},{key:"isSupported",value:function(){return _isSupported()}},{key:"getMediaSource",value:function(){return _getMediaSource2()}},{key:"Events",get:function(){return Events$2}},{key:"MetadataSchema",get:function(){return MetadataSchema}},{key:"ErrorTypes",get:function(){return ErrorTypes}},{key:"ErrorDetails",get:function(){return ErrorDetails}},{key:"DefaultConfig",get:function(){return e.defaultConfig?e.defaultConfig:hlsDefaultConfig},set:function(t){e.defaultConfig=t}}])}();Hls.defaultConfig=void 0;var isIos=/iPhone|iPad|iPod|iOS/i.test(navigator.userAgent),isIosTablet=function(){if("undefined"==typeof navigator)return!1;var e=navigator.userAgent||"",t=navigator.platform||"",r="number"==typeof navigator.maxTouchPoints?navigator.maxTouchPoints:0;return!!/iPad/i.test(e)||(!!(/Macintosh/i.test(e)&&r>1)||"MacIntel"===t&&r>1)},isIosEnvironment=function(){return isIos||isIosTablet()},isAndroid=function(){return"undefined"!=typeof navigator&&/Android/i.test(navigator.userAgent||"")},isUcLikeBrowser=function(){if("undefined"==typeof navigator)return!1;var e=navigator.userAgent||"";return/UCBrowser|UCWEB|UBrowser|Quark|AliApp|QHBrowser/i.test(e)},isMiBrowser=function(){if("undefined"==typeof navigator)return!1;var e=navigator.userAgent||"";return!!/MiuiBrowser|XiaoMi|Xiaomi|MiBrowser|XMSDK|Redmi|POCO|MIUI/i.test(e)||!("undefined"==typeof window||!window.miui&&!window.MIUI)},HEVC_CODEC_CANDIDATES=["hvc1.1.6.L93.B0","hev1.1.6.L93.B0","hvc1","hev1"];function isPlayTypeSupported(e){return"probably"===e||"maybe"===e}var canNativePlayHevc=function(){if("undefined"==typeof document)return{supported:!1,detail:""};var e=document.createElement("video");if(!e||"function"!=typeof e.canPlayType)return{supported:!1,detail:""};for(var t=0;t<HEVC_CODEC_CANDIDATES.length;t++){var r=HEVC_CODEC_CANDIDATES[t],n='video/mp4; codecs="'.concat(r,'"'),i=e.canPlayType(n);if(isPlayTypeSupported(i))return{supported:!0,detail:i,codec:r,mime:n}}return{supported:!1,detail:""}},isSafariBrowser=function(){if("undefined"==typeof navigator)return!1;var e=navigator.userAgent||"";return!!isIosEnvironment()||/Safari/i.test(e)&&!/Chrome|Chromium|CriOS|Edg|Android/i.test(e)},canNativePlayHls=function(){if("undefined"==typeof document)return!1;var e=document.createElement("video");return!(!e||"function"!=typeof e.canPlayType)&&(isPlayTypeSupported(e.canPlayType("application/vnd.apple.mpegurl"))||isPlayTypeSupported(e.canPlayType("application/x-mpegURL")))},canVideoPlayHevcHls=function(){var e=!!(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).isEncrypt,t=isSafariBrowser(),r=canNativePlayHls(),n=canNativePlayHevc(),i=n.supported;return e?{supported:!1,reason:"encrypted",nativeHls:r,nativeHevc:i,isSafariLike:t}:r&&t?i?{supported:!0,reason:"ok",nativeHls:r,nativeHevc:i,isSafariLike:t,nativeHevcDetail:n}:{supported:!1,reason:"no_native_hevc",nativeHls:r,nativeHevc:i,isSafariLike:t}:{supported:!1,reason:"no_native_hls",nativeHls:r,nativeHevc:i,isSafariLike:t}},getDeviceType=function(){var e=navigator.userAgent.toLowerCase(),t=/android|webos|iphone|ipod|blackberry|iemobile|opera mini/.test(e);return/ipad/.test(e)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1?"ipad":t?"h5":"pc"},playerCss=".ylc-player-container,\r\n.ylc-live-player-container {\r\n position: relative;\r\n width: 100%;\r\n height: 100%;\r\n background: #000;\r\n overflow: hidden;\r\n isolation: isolate;\r\n transform: translateZ(0);\r\n -webkit-transform: translateZ(0);\r\n}\r\n\r\n.ylc-video-player,\r\n.ylc-live-player-video {\r\n position: relative;\r\n z-index: 0;\r\n width: 100%;\r\n height: 100%;\r\n background: #000;\r\n overflow: hidden;\r\n object-fit: contain;\r\n pointer-events: none;\r\n -webkit-appearance: none;\r\n appearance: none;\r\n}\r\n\r\n.ylc-video-player::-webkit-media-controls,\r\n.ylc-video-player::-webkit-media-controls-enclosure,\r\n.ylc-video-player::-webkit-media-controls-overlay-enclosure,\r\n.ylc-video-player::-webkit-media-controls-panel,\r\n.ylc-video-player::-webkit-media-controls-start-playback-button,\r\n.ylc-video-player::-webkit-media-controls-overlay-play-button,\r\n.ylc-video-player::-webkit-media-controls-timeline,\r\n.ylc-video-player::-webkit-media-controls-current-time-display,\r\n.ylc-video-player::-webkit-media-controls-time-remaining-display,\r\n.ylc-video-player::-webkit-media-controls-mute-button,\r\n.ylc-video-player::-webkit-media-controls-toggle-closed-captions-button,\r\n.ylc-video-player::-webkit-media-controls-volume-slider,\r\n.ylc-video-player::-webkit-media-controls-fullscreen-button,\r\n.ylc-video-player::-webkit-media-controls-play-button,\r\n.ylc-video-player::-internal-media-controls-overflow-button {\r\n display: none !important;\r\n opacity: 0 !important;\r\n pointer-events: none !important;\r\n -webkit-appearance: none !important;\r\n visibility: hidden !important;\r\n width: 0 !important;\r\n height: 0 !important;\r\n max-height: 0 !important;\r\n}\r\n\r\n.ylc-video-canvas-mirror {\r\n position: absolute;\r\n left: 0;\r\n top: 0;\r\n width: 100%;\r\n height: 100%;\r\n z-index: 1;\r\n background: #000;\r\n pointer-events: none;\r\n display: block;\r\n}\r\n\r\n.ylc-video-touch-mask {\r\n position: absolute;\r\n left: 0;\r\n top: 0;\r\n width: 100%;\r\n height: 100%;\r\n z-index: 2;\r\n background: transparent;\r\n}\r\n\r\n.ylc-video-player-loading {\r\n display: none;\r\n position: absolute;\r\n left: 50%;\r\n top: 50%;\r\n z-index: 3;\r\n width: 48px;\r\n height: 48px;\r\n margin: -24px 0 0 -24px;\r\n pointer-events: none;\r\n}\r\n\r\n.ylc-video-player-loading.is-show {\r\n display: block;\r\n}\r\n\r\n.ylc-video-player-loading-spinner {\r\n width: 100%;\r\n height: 100%;\r\n box-sizing: border-box;\r\n border: 3px solid rgba(255, 255, 255, 0.25);\r\n border-top-color: #fff;\r\n border-radius: 50%;\r\n animation: ylc-player-spin 0.7s linear infinite;\r\n}\r\n\r\n@keyframes ylc-player-spin {\r\n to {\r\n transform: rotate(360deg);\r\n }\r\n}\r\n\r\n.ylc-video-player-control {\r\n position: absolute;\r\n bottom: 0;\r\n left: 0;\r\n width: 100%;\r\n height: 65px;\r\n z-index: 2147483646;\r\n padding: 8px;\r\n background: linear-gradient(180deg, rgba(8, 9, 13, 0), rgba(8, 9, 13, 0.8));\r\n box-sizing: border-box;\r\n pointer-events: auto;\r\n}\r\n\r\n.ylc-video-player-progerss {\r\n display: flex;\r\n align-items: center;\r\n position: relative;\r\n width: 100%;\r\n height: 30px;\r\n}\r\n\r\n.ylc-video-player-progress-hover-time {\r\n display: none;\r\n position: absolute;\r\n bottom: calc(100% - 4px);\r\n left: 0;\r\n z-index: 100;\r\n padding: 2px 6px;\r\n background: rgba(0, 0, 0, 0.75);\r\n color: #fff;\r\n font-size: 12px;\r\n line-height: 16px;\r\n border-radius: 2px;\r\n white-space: nowrap;\r\n pointer-events: none;\r\n transform: translateX(-50%);\r\n}\r\n\r\n.ylc-video-player-progress-hover-time.is-show {\r\n display: block;\r\n}\r\n\r\n.ylc-video-player-progress-line-bg {\r\n position: absolute;\r\n left: 0;\r\n width: 100%;\r\n height: 3px;\r\n z-index: 9;\r\n background: hsla(0, 15%, 90%, 0.4);\r\n cursor: pointer;\r\n}\r\n\r\n.ylc-video-player-progress-line {\r\n position: absolute;\r\n left: 0;\r\n width: 0;\r\n height: 3px;\r\n z-index: 99;\r\n background: #fff;\r\n cursor: pointer;\r\n}\r\n\r\n.ylc-video-player-progress-line-dot {\r\n position: absolute;\r\n left: 0;\r\n width: 15px;\r\n height: 15px;\r\n z-index: 99;\r\n border-radius: 50%;\r\n background: #fff;\r\n cursor: pointer;\r\n}\r\n\r\n.ylc-video-player-btn-bar-container {\r\n display: flex;\r\n justify-content: space-between;\r\n position: relative;\r\n width: 100%;\r\n}\r\n\r\n.ylc-video-player-btn-bar-left,\r\n.ylc-video-player-btn-bar-right {\r\n display: flex;\r\n align-items: center;\r\n}\r\n\r\n.ylc-video-player-play-button,\r\n.ylc-video-player-pause-button {\r\n display: block;\r\n width: 20px;\r\n height: 20px;\r\n cursor: pointer;\r\n}\r\n\r\n.ylc-video-player-pause-button {\r\n display: none;\r\n}\r\n\r\n.ylc-video-player-current-time,\r\n.ylc-video-player-total-time,\r\n.ylc-video-player-time-split {\r\n color: #fff;\r\n font-size: 12px;\r\n}\r\n\r\n.ylc-video-player-current-time {\r\n margin-left: 10px;\r\n}\r\n\r\n.ylc-video-player-time-split {\r\n padding: 0 5px;\r\n}\r\n\r\n.ylc-video-player-rate-button,\r\n.ylc-video-player-line-button {\r\n position: relative;\r\n color: #fff;\r\n font-size: 12px;\r\n margin-left: 10px;\r\n cursor: pointer;\r\n user-select: none;\r\n}\r\n\r\n.ylc-video-player-volume-button,\r\n.ylc-video-player-mute-button,\r\n.ylc-video-player-exit-full-screen-button {\r\n width: 20px;\r\n height: 20px;\r\n cursor: pointer;\r\n margin-left: 10px;\r\n}\r\n\r\n.ylc-video-player-full-screen-button {\r\n width: 16px;\r\n height: 16px;\r\n cursor: pointer;\r\n margin-left: 10px;\r\n}\r\n\r\n.ylc-video-player-mute-button,\r\n.ylc-video-player-exit-full-screen-button {\r\n display: none;\r\n}\r\n\r\n.ylc-video-player-rate-list,\r\n.ylc-video-player-line-panel {\r\n display: none;\r\n position: absolute;\r\n left: 50%;\r\n bottom: 100%;\r\n transform: translateX(-50%);\r\n z-index: 20;\r\n min-width: 72px;\r\n margin: 0;\r\n padding: 6px 0;\r\n list-style: none;\r\n background: rgba(0, 0, 0, 0.85);\r\n border-radius: 4px;\r\n}\r\n\r\n.ylc-video-player-line-panel {\r\n padding: 0 0 12px;\r\n background: transparent;\r\n min-width: auto;\r\n}\r\n\r\n.ylc-video-player-line-list {\r\n min-width: 72px;\r\n margin: 0;\r\n padding: 6px 0;\r\n list-style: none;\r\n background: rgba(0, 0, 0, 0.85);\r\n border-radius: 4px;\r\n}\r\n\r\n.ylc-video-player-rate-item,\r\n.ylc-video-player-line-item {\r\n padding: 8px 14px;\r\n text-align: center;\r\n white-space: nowrap;\r\n cursor: pointer;\r\n}\r\n\r\n.ylc-video-player-rate-item.active,\r\n.ylc-video-player-line-item.active {\r\n font-weight: 600;\r\n}\r\n\r\n.ylc-live-player-badge {\r\n position: absolute;\r\n top: 12px;\r\n left: 12px;\r\n padding: 2px 8px;\r\n border-radius: 2px;\r\n background: #e53935;\r\n color: #fff;\r\n font-size: 12px;\r\n font-weight: 600;\r\n letter-spacing: 1px;\r\n z-index: 2;\r\n}\r\n\r\n.ylc-live-player-status {\r\n position: absolute;\r\n left: 50%;\r\n top: 50%;\r\n transform: translate(-50%, -50%);\r\n color: rgba(255, 255, 255, 0.85);\r\n font-size: 14px;\r\n z-index: 2;\r\n pointer-events: none;\r\n}\r\n\r\n.ylc-live-player-controls {\r\n position: absolute;\r\n left: 0;\r\n right: 0;\r\n bottom: 0;\r\n height: 48px;\r\n display: flex;\r\n align-items: center;\r\n padding: 0 12px;\r\n box-sizing: border-box;\r\n background: linear-gradient(transparent, rgba(0, 0, 0, 0.65));\r\n z-index: 2;\r\n}\r\n\r\n.ylc-live-player-controls img {\r\n width: 28px;\r\n height: 28px;\r\n margin-right: 10px;\r\n cursor: pointer;\r\n user-select: none;\r\n}\r\n\r\n.ylc-live-pause-button,\r\n.ylc-live-exit-full-screen-button {\r\n display: none;\r\n}\r\n",injected=!1;function injectPlayerStyle(){if(!injected&&"undefined"!=typeof document)if(document.querySelector("[data-hx-player-style]"))injected=!0;else{injected=!0;var e=document.createElement("style");e.setAttribute("data-hx-player-style","1"),e.textContent=playerCss,document.head.appendChild(e)}}var INJECTED_CONTROL_CLASS=/quark-video-controls|browser-video-controls|uc-video-controls|ucbrowser|ali-video-controls|qh-video-controls|miui-video|mi-video-controls|xiaomi-video|video-overlay-controls|mibrowser|mi-browser|video-player-controller|native-video-controls|sys-video-controls/i,YLC_OWN_CLASS=/^ylc-/,KEEP_TAGS=/^(SCRIPT|STYLE|LINK|META)$/,nativeMetaInjected=!1;function injectNativeControlHideStyle(){if(injectPlayerStyle(),!nativeMetaInjected&&"undefined"!=typeof document){if(nativeMetaInjected=!0,!document.querySelector('meta[name="x5-video-player-type"]')){var e=document.createElement("meta");e.setAttribute("name","x5-video-player-type"),e.setAttribute("content","h5"),document.head.appendChild(e)}if(!document.querySelector('meta[name="x5-video-player-fullscreen"]')){var t=document.createElement("meta");t.setAttribute("name","x5-video-player-fullscreen"),t.setAttribute("content","false"),document.head.appendChild(t)}}}function isYlcOwnNode(e){if(!e||1!==e.nodeType)return!1;if(e.getAttribute&&e.getAttribute("data-ylc"))return!0;var t=e.className&&String(e.className);return!!t&&String(t).split(/\s+/).some(function(e){return YLC_OWN_CLASS.test(e)})}function isInjectedControlNode(e){if(!e||1!==e.nodeType||isYlcOwnNode(e))return!1;if(KEEP_TAGS.test(e.tagName))return!1;var t=e.className&&String(e.className),r=e.id&&String(e.id),n="".concat(t||""," ").concat(r||"");return!!INJECTED_CONTROL_CLASS.test(n)||!(!e.getAttribute||!e.getAttribute("data-browser-controls"))}function isLikelyHijackOverlay(e){if(isInjectedControlNode(e))return!0;if(!e||1!==e.nodeType||isYlcOwnNode(e))return!1;if(KEEP_TAGS.test(e.tagName))return!1;var t=e.className&&String(e.className),r=e.id&&String(e.id),n="".concat(t||""," ").concat(r||"");return/video|media|player/i.test(n)&&/control|toolbar|bar|overlay|panel/i.test(n)}function hideInjectedNode(e){if(e&&1===e.nodeType){try{return void e.remove()}catch(t){}try{e.style.setProperty("display","none","important"),e.style.setProperty("opacity","0","important"),e.style.setProperty("pointer-events","none","important"),e.style.setProperty("visibility","hidden","important")}catch(t){}}}function _stripNativeControls(e){e&&(e.controls=!1,e.setAttribute("controlsList","nodownload nofullscreen noremoteplayback noplaybackrate"),e.hasAttribute("controls")&&e.removeAttribute("controls"))}var NativeHijackGuard=function(){return _createClass(function e(){_classCallCheck(this,e)},null,[{key:"injectStyle",value:function(){injectNativeControlHideStyle()}},{key:"stripNativeControls",value:function(e){_stripNativeControls(e)}},{key:"attach",value:function(e){injectNativeControlHideStyle(),_stripNativeControls(e);var t=function(e){isInjectedControlNode(e)&&hideInjectedNode(e)},r=function(e){isLikelyHijackOverlay(e)&&hideInjectedNode(e)},n=new MutationObserver(function(t){t.forEach(function(t){"attributes"!==t.type?t.addedNodes.forEach(function(t){r(t),_stripNativeControls(e)}):_stripNativeControls(e)})});n.observe(e,{attributes:!0,attributeFilter:["controls"],childList:!0,subtree:!0});var i=new MutationObserver(function(e){e.forEach(function(e){e.addedNodes.forEach(r)})}),a=new MutationObserver(function(e){e.forEach(function(e){e.addedNodes.forEach(function(e){e&&1===e.nodeType&&t(e)})})}),s=isAndroid()?50:200,o=setInterval(function(){_stripNativeControls(e);var r=e.parentElement;r&&Array.from(r.children).forEach(function(r){r!==e&&t(r)})},s),l=setTimeout(function(){if(e.parentElement){i.observe(e.parentElement,{childList:!0,subtree:!1});var t=e.closest(".ylc-player-container");t&&a.observe(t,{childList:!0})}},0),u=["play","playing","pause","loadedmetadata","loadeddata","canplay","seeking","seeked"],c=function(){return _stripNativeControls(e)};u.forEach(function(t){return e.addEventListener(t,c)});var d=function(t){t&&"function"==typeof t.preventDefault&&t.preventDefault();try{e.webkitExitFullScreen&&e.webkitExitFullScreen()}catch(err){}_stripNativeControls(e)};e.addEventListener("webkitbeginfullscreen",d);var h=e.remove;return e.remove=function(){clearInterval(o),clearTimeout(l),n.disconnect(),i.disconnect(),a.disconnect(),u.forEach(function(t){return e.removeEventListener(t,c)}),e.removeEventListener("webkitbeginfullscreen",d),h.call(this)},isUcLikeBrowser()&&e.setAttribute("airplay","allow"),e}}])}(),ICON_BASE="https://shanhu-live-user-1317978474.cos.accelerate.myqcloud.com/web/shplayer_icon";function getVodTemplate(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.showControls,r=void 0===t||t,n=e.currentLine,i=2===Number(void 0===n?1:n)?2:1,a=r?'\n <div class="ylc-video-player-control">\n <div class="ylc-video-player-progerss">\n <div class="ylc-video-player-progress-hover-time">00:00</div>\n <div class="ylc-video-player-progress-line-dot"></div>\n <div class="ylc-video-player-progress-line-bg"></div>\n <div class="ylc-video-player-progress-line"></div>\n </div>\n <div class="ylc-video-player-btn-bar-container">\n <div class="ylc-video-player-btn-bar-left">\n <img class="ylc-video-player-play-button" src="'.concat(ICON_BASE,'/play_pause.png" alt="">\n <img class="ylc-video-player-pause-button" src="').concat(ICON_BASE,'/new_play_pause.png" alt="">\n <span id="ylcCurrentTime" class="ylc-video-player-current-time">00:00 </span>\n <span class="ylc-video-player-time-split">/</span>\n <span id="ylcTotalTime" class="ylc-video-player-total-time">00:00</span>\n </div>\n <div class="ylc-video-player-btn-bar-right">\n \x3c!-- 切线路 UI 暂时关闭\n <div class="ylc-video-player-line-button">\n <span class="ylc-video-player-line-label">').concat(2===i?"线路2":"线路1",'</span>\n <div class="ylc-video-player-line-panel">\n <ul class="ylc-video-player-line-list">\n <li class="ylc-video-player-line-item').concat(1===i?" active":"",'" data-value="1">线路1</li>\n <li class="ylc-video-player-line-item').concat(2===i?" active":"",'" data-value="2">线路2</li>\n </ul>\n </div>\n </div>\n --\x3e\n <div class="ylc-video-player-rate-button">\n <span>倍数</span>\n <ul class="ylc-video-player-rate-list">\n <li class="ylc-video-player-rate-item" data-value="3">3.0X</li>\n <li class="ylc-video-player-rate-item" data-value="2">2.0X</li>\n <li class="ylc-video-player-rate-item active" data-value="1">1.0X</li>\n <li class="ylc-video-player-rate-item" data-value="0.5">0.5X</li>\n </ul>\n </div>\n <img class="ylc-video-player-volume-button" src="').concat(ICON_BASE,'/yinliang.png" alt="">\n <img class="ylc-video-player-mute-button" src="').concat(ICON_BASE,'/jingyin.png" alt="">\n <img class="ylc-video-player-full-screen-button" src="').concat(ICON_BASE,'/ylc_full_screen.png" alt="">\n <img class="ylc-video-player-exit-full-screen-button" src="').concat(ICON_BASE,'/ylc_exit_screen.png" alt="">\n </div>\n </div>\n </div>'):"";return'\n <div class="ylc-player-container">\n <div class="ylc-video-touch-mask" data-ylc="touch-mask"></div>\n <div class="ylc-video-player-loading" aria-hidden="true">\n <div class="ylc-video-player-loading-spinner"></div>\n </div>\n '.concat(a,"\n </div>\n ")}function getLiveTemplate(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.showControls,r=void 0===t||t,n=e.muted,i=void 0!==n&&n,a=r?'\n <div class="ylc-live-player-controls">\n <img class="ylc-live-play-button" src="'.concat(ICON_BASE,'/play_pause.png" title="播放" alt="">\n <img class="ylc-live-pause-button" src="').concat(ICON_BASE,'/new_play_pause.png" title="暂停" alt="">\n <img class="ylc-live-volume-button" src="').concat(ICON_BASE,'/yinliang.png" title="声音" alt="" style="').concat(i?"display:none":"",'">\n <img class="ylc-live-mute-button" src="').concat(ICON_BASE,'/jingyin.png" title="静音" alt="" style="').concat(i?"":"display:none",'">\n <img class="ylc-live-full-screen-button" src="').concat(ICON_BASE,'/ylc_full_screen.png" title="全屏" alt="">\n <img class="ylc-live-exit-full-screen-button" src="').concat(ICON_BASE,'/ylc_exit_screen.png" title="退出全屏" alt="">\n </div>'):"";return'\n <div class="ylc-live-player-container">\n <div class="ylc-live-player-badge">LIVE</div>\n <div class="ylc-live-player-status"></div>\n '.concat(a,"\n </div>\n ")}function parseTemplate(e){var t=document.createElement("div");return t.innerHTML=e.trim(),t.firstElementChild}var Ui=function(){function e(){_classCallCheck(this,e)}return _createClass(e,null,[{key:"injectStyle",value:function(){injectPlayerStyle(),NativeHijackGuard.injectStyle()}},{key:"createVideoElement",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=document.createElement("video");t.className="ylc-video-player",t.muted=!!e.muted,e.poster&&(t.poster=e.poster),NativeHijackGuard.stripNativeControls(t),t.setAttribute("x5-video-player-type","h5"),t.setAttribute("x5-video-player-fullscreen","false"),t.setAttribute("x5-video-orientation","portrait"),t.setAttribute("x5-playsinline","true"),t.setAttribute("crossorigin","anonymous"),t.crossOrigin="anonymous",t.setAttribute("playsinline","true"),t.setAttribute("webkit-inline","true"),t.setAttribute("webkit-playsinline","true"),t.setAttribute("x-webkit-airplay","allow"),t.setAttribute("preload","metadata"),t.setAttribute("disablePictureInPicture","true"),t.setAttribute("controlsList","nodownload nofullscreen noremoteplayback noplaybackrate"),t.playsInline=!0,t.disablePictureInPicture=!0,"disableRemotePlayback"in t&&(t.disableRemotePlayback=!0),t.setAttribute("t7-video-player-type","inline"),t.setAttribute("t7-video-player-fullscreen","false"),isUcLikeBrowser()&&t.setAttribute("airplay","allow");var r=t.play.bind(t);return t.play=function(){return t.setAttribute("t7-video-player-type","inline"),t.setAttribute("x5-video-player-type","h5"),t.setAttribute("x5-video-player-fullscreen","false"),t.controls=!1,t.removeAttribute("controls"),r()},NativeHijackGuard.attach(t),t}},{key:"mount",value:function(t){e.injectStyle();var r=parseTemplate(getVodTemplate({showControls:!(!t.options||!t.options.controls),currentLine:t.currentLine})),n=e.createVideoElement(t.options||{});return n.controls=!1,n.removeAttribute("controls"),r.insertBefore(n,r.firstChild),t.container=r,t.videoElm=n,t.touchMask=r.querySelector(".ylc-video-touch-mask"),t.loadingElm=r.querySelector(".ylc-video-player-loading"),r}}])}(),Events$1=function(){return _createClass(function e(t){_classCallCheck(this,e),this.target=t,this.eventsQueue={}},[{key:"on",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];this.eventsQueue[e]||(this.eventsQueue[e]={methods:[],onceFlags:[]}),this.eventsQueue[e].methods.includes(t)||(this.eventsQueue[e].methods.push(t),this.eventsQueue[e].onceFlags.push(!!r))}},{key:"once",value:function(e,t){this.on(e,t,!0)}},{key:"emit",value:function(e){for(var t=this,r=arguments.length,n=new Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];var a=this.eventsQueue[e];if(a){var s=a.methods,o=a.onceFlags,l=[],u=[];s.forEach(function(r,i){try{r.apply(t.target,n)}catch(a){console.error("[VideoPlayer Events]",e,a)}o[i]||(l.push(r),u.push(!1))}),a.methods=l,a.onceFlags=u}}},{key:"off",value:function(e,t){var r=this.eventsQueue[e];if(r)if(t){var n=r.methods.indexOf(t);n>=0&&(r.methods.splice(n,1),r.onceFlags.splice(n,1)),r.methods.length||delete this.eventsQueue[e]}else delete this.eventsQueue[e]}},{key:"removeAll",value:function(){this.eventsQueue={}}}])}(),DEFAULT_WS_BASE="wss://log-reporting.huaxiacloud.net/ws",DEFAULT_CONNECT_TIMEOUT_MS=1e4,DEFAULT_RECONNECT_DELAY_MS=2e3,DEFAULT_MAX_RECONNECT=5,LogWebSocket=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};_classCallCheck(this,e),this.options=_objectSpread2$1({baseUrl:DEFAULT_WS_BASE,connectTimeoutMs:DEFAULT_CONNECT_TIMEOUT_MS,reconnectDelayMs:DEFAULT_RECONNECT_DELAY_MS,maxReconnect:DEFAULT_MAX_RECONNECT,autoReconnect:!0},t),this.ws=null,this.userId=null!=this.options.userId?String(this.options.userId):"",this.terminal=this.options.terminal||e.detectTerminal(),this.sessionId="",this._manualClose=!1,this._connecting=!1,this._reconnectCount=0,this._connectTimer=null,this._reconnectTimer=null,this._pendingQueue=[],this._connectingPromise=null}return _createClass(e,[{key:"connected",get:function(){return!(!this.ws||this.ws.readyState!==WebSocket.OPEN)}},{key:"buildUrl",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.userId,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.terminal,r=this.options.baseUrl||DEFAULT_WS_BASE,n="user_id=".concat(encodeURIComponent(String(e)),"&terminal=").concat(encodeURIComponent(t));return r.includes("?")?"".concat(r,"&").concat(n):"".concat(r,"?").concat(n)}},{key:"connect",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return null!=t.userId&&(this.userId=String(t.userId)),t.terminal&&(this.terminal=t.terminal),this.connected?Promise.resolve(this):this._connecting?this._connectingPromise||Promise.resolve(this):(this._manualClose=!1,this._connecting=!0,this.sessionId="",this._connectingPromise=new Promise(function(t,r){var n=!1,i="";try{i=e.buildUrl()}catch(s){return e._connecting=!1,e._logError("连接参数错误",s),void r(s)}e._clearConnectTimer(),e._clearReconnectTimer();try{e.ws=new WebSocket(i)}catch(s){return e._connecting=!1,e._logError("创建 WebSocket 失败",s),e._scheduleReconnect(),void r(s)}var a=e.options.connectTimeoutMs||DEFAULT_CONNECT_TIMEOUT_MS;e._connectTimer=setTimeout(function(){var t=new Error("[LogWebSocket] 连接超时(".concat(a,"ms): ").concat(i));if(e._logError("连接超时",t),"function"==typeof e.options.onTimeout)try{e.options.onTimeout(t)}catch(s){}try{e.ws&&e.ws.close()}catch(s){}e.ws=null,e._connecting=!1,n||(n=!0,r(t)),e._scheduleReconnect()},a),e.ws.onopen=function(){if(e._clearConnectTimer(),e._connecting=!1,e._reconnectCount=0,e._logInfo("连接成功",{url:i}),"function"==typeof e.options.onOpen)try{e.options.onOpen()}catch(s){}n||(n=!0,t(e))},e.ws.onmessage=function(t){if(e._handleMessage(t.data),"function"==typeof e.options.onMessage)try{e.options.onMessage(t.data,t)}catch(s){}},e.ws.onerror=function(t){if(e._logError("连接异常",t),"function"==typeof e.options.onError)try{e.options.onError(t)}catch(s){}},e.ws.onclose=function(t){if(e._clearConnectTimer(),e._connecting=!1,e.ws=null,e.sessionId="",e._logInfo("连接关闭",{code:t.code,reason:t.reason}),"function"==typeof e.options.onClose)try{e.options.onClose(t)}catch(s){}n||(n=!0,r(new Error("[LogWebSocket] 连接关闭 code=".concat(t.code)))),e._manualClose||!1===e.options.autoReconnect||e._scheduleReconnect()}}),this._connectingPromise)}},{key:"report",value:function(e){var t=e;if(!this.connected||!this.sessionId)return this._pendingQueue.push(t),this.connected||this._connecting||this._manualClose||!this.userId||this.connect().catch(function(){}),!1;try{return this.ws.send(this._normalizePayload(t)),!0}catch(r){return this._logError("上报失败",r),this._pendingQueue.push(t),!1}}},{key:"_handleMessage",value:function(e){var t=e;if("string"==typeof e)try{t=JSON.parse(e)}catch(n){return}if(t&&"object"===_typeof(t)){var r=t.session_id||t.sessionId;("session"===t.type||r)&&r&&(this.sessionId=String(r),this._logInfo("收到 session_id",{sessionId:this.sessionId}),this._flushPending())}}},{key:"disconnect",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"client disconnect";if(this._manualClose=!0,this._connecting=!1,this._clearConnectTimer(),this._clearReconnectTimer(),this._reconnectCount=0,this.sessionId="",this.ws){try{this.ws.close(e,t)}catch(r){this._logError("断开连接失败",r)}this.ws=null}}},{key:"clearPending",value:function(){this._pendingQueue=[]}},{key:"_normalizePayload",value:function(e){if(null==e)return"";if("string"==typeof e){try{var t=JSON.parse(e);if(t&&"object"===_typeof(t)&&!Array.isArray(t))return JSON.stringify(this._attachSessionId(t))}catch(r){}return e}if(e instanceof ArrayBuffer||e instanceof Blob)return e;if("object"===_typeof(e))try{return JSON.stringify(this._attachSessionId(e))}catch(r){return String(e)}return String(e)}},{key:"_attachSessionId",value:function(e){var t=_objectSpread2$1({},e);return this.sessionId&&(null==t.playSessionId&&(t.playSessionId=this.sessionId),t.content&&"object"===_typeof(t.content)&&!Array.isArray(t.content)&&(t.content=_objectSpread2$1({},t.content),null==t.content.playSessionId&&(t.content.playSessionId=this.sessionId))),t}},{key:"_flushPending",value:function(){var e=this;this.connected&&this.sessionId&&this._pendingQueue.length&&this._pendingQueue.splice(0,this._pendingQueue.length).forEach(function(t){try{e.ws.send(e._normalizePayload(t))}catch(r){e._logError("补发队列失败",r),e._pendingQueue.push(t)}})}},{key:"_scheduleReconnect",value:function(){var e=this;if(!this._manualClose&&!1!==this.options.autoReconnect){var t=this.options.maxReconnect;if(-1!==t&&this._reconnectCount>=t)this._logError("重试次数已达上限,停止重连",{maxReconnect:t,reconnectCount:this._reconnectCount});else if(!this._reconnectTimer){this._reconnectCount+=1;var r=this.options.reconnectDelayMs||DEFAULT_RECONNECT_DELAY_MS,n=Math.min(r*Math.pow(1.5,this._reconnectCount-1),3e4);this._logInfo("准备重试连接",{reconnectCount:this._reconnectCount,delay:n}),this._reconnectTimer=setTimeout(function(){e._reconnectTimer=null,e.connect().catch(function(){})},n)}}}},{key:"_clearConnectTimer",value:function(){this._connectTimer&&(clearTimeout(this._connectTimer),this._connectTimer=null)}},{key:"_clearReconnectTimer",value:function(){this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null)}},{key:"_logInfo",value:function(e,t){void 0!==t?console.log("[LogWebSocket] ".concat(e),t):console.log("[LogWebSocket] ".concat(e))}},{key:"_logError",value:function(e,t){void 0!==t?console.error("[LogWebSocket] ".concat(e),t):console.error("[LogWebSocket] ".concat(e))}}],[{key:"getInstance",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return e._instance?t&&Object.keys(t).length&&(e._instance.options=_objectSpread2$1(_objectSpread2$1({},e._instance.options),t),null!=t.userId&&(e._instance.userId=String(t.userId)),t.terminal&&(e._instance.terminal=t.terminal)):e._instance=new e(t),e._instance}},{key:"connect",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return e.getInstance(t).connect(t)}},{key:"report",value:function(t){return e.getInstance().report(t)}},{key:"getSessionId",value:function(){return e._instance&&e._instance.sessionId||""}},{key:"disconnect",value:function(t,r){e._instance&&e._instance.disconnect(t,r)}},{key:"isConnected",value:function(){return!(!e._instance||!e._instance.connected)}},{key:"detectTerminal",value:function(){return getDeviceType()}}])}();_defineProperty$1(LogWebSocket,"_instance",null);var METRIC_SAMPLE_EVERY=10,EVENT_NAME={info:"流程日志",error:"错误日志",click:"点击事件日志",operate:"操作日志",fetch:"接口日志",metric:"指标日志"},Logger=function(){function e(){_classCallCheck(this,e)}return _createClass(e,null,[{key:"setAppContext",value:function(){var t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).appId;null!=t&&(e._appId=t)}},{key:"info",value:function(t,r){e._report("info",t,r)}},{key:"error",value:function(t,r){e._report("error",t,r)}},{key:"click",value:function(t,r){e._report("click",t,r)}},{key:"operate",value:function(t,r){e._report("operate",t,r)}},{key:"fetch",value:function(t,r){e._report("fetch",t,r)}},{key:"metric",value:function(t,r){var n=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).sampleEvery,i=void 0===n?METRIC_SAMPLE_EVERY:n;e._metricCount+=1,i>1&&e._metricCount%i!==1||e._report("metric",t,r)}},{key:"_report",value:function(t,r,n){LogWebSocket.report({content:{eventType:t,eventName:EVENT_NAME[t]||"流程日志",eventCode:"",errorCode:"error"===t?"error":"",message:r,params:n,appId:e._appId}})}}])}();_defineProperty$1(Logger,"_metricCount",0),_defineProperty$1(Logger,"_appId","");var TsDecrypt=function(){function e(){_classCallCheck(this,e)}return _createClass(e,null,[{key:"loadWasm",value:(i=_asyncToGenerator(_regenerator().m(function t(){return _regenerator().w(function(t){for(;;)switch(t.n){case 0:if(!e.module){t.n=1;break}return t.a(2,e.module);case 1:if(!e.loadPromise){t.n=2;break}return t.a(2,e.loadPromise);case 2:return e.isLoading=!0,e.loadPromise=e._loadWasmOnce().then(function(t){return e.module=t,e.isLoading=!1,t}).catch(function(t){throw e.isLoading=!1,e.loadPromise=null,t}),t.a(2,e.loadPromise)}},t)})),function(){return i.apply(this,arguments)})},{key:"_loadWasmOnce",value:(n=_asyncToGenerator(_regenerator().m(function t(){var r,n,i,a,s,o,l,u,c,d,h,f;return _regenerator().w(function(t){for(;;)switch(t.n){case 0:return r=Date.now(),n="".concat(e.baseUrl,"/decryptor/decryptor.js?v=").concat(r),i="".concat(e.baseUrl,"/decryptor/decryptor.wasm?v=").concat(r),t.n=1,fetch(n);case 1:if((a=t.v).ok){t.n=2;break}throw new Error("Failed to fetch decryptor.js: ".concat(a.status));case 2:return t.n=3,a.text();case 3:return s=t.v,t.n=4,fetch(i);case 4:if((o=t.v).ok){t.n=5;break}throw new Error("Failed to fetch decryptor.wasm: ".concat(o.status));case 5:return h=Uint8Array,t.n=6,o.arrayBuffer();case 6:if(f=t.v,l=new h(f),s=(s=(s=s.replace(/import\.meta\.url/g,JSON.stringify(n))).replace(/import\.meta/g,"{}")).replace(/export\s+default\s+Module\s*;?/,"window.__decryptorModuleExport = Module;"),(u=document.createElement("script")).type="text/javascript",u.textContent=s,document.head.appendChild(u),c=window.__decryptorModuleExport,u.remove(),delete window.__decryptorModuleExport,"function"==typeof c){t.n=7;break}throw new Error("Module export not found");case 7:return t.n=8,c({wasmBinary:l,locateFile:function(e){return e&&-1!==String(e).indexOf(".wasm")?i:e}});case 8:return d=t.v,t.a(2,d)}},t)})),function(){return n.apply(this,arguments)})},{key:"normalizeFileId",value:function(e){if("string"==typeof e&&e.trim())return e.trim();if(e&&"object"===_typeof(e)){var t=e.fileid,r=e.fileId;if("string"==typeof t&&t.trim())return t.trim();if("string"==typeof r&&r.trim())return r.trim()}throw new Error("invalid fileid")}},{key:"normalizeAuthCipher",value:function(e,t){if("string"==typeof t&&t.trim())return t.trim();if(e&&"object"===_typeof(e)){var r=e.authCipher,n=e.authToken,i=e.encryptedAuth;if("string"==typeof r&&r.trim())return r.trim();if("string"==typeof n&&n.trim())return n.trim();if("string"==typeof i&&i.trim())return i.trim()}throw new Error("invalid authCipher")}},{key:"decryptSegment",value:(r=_asyncToGenerator(_regenerator().m(function t(r,n,i){var a,s,o,l,u,c,d,h,f,v,p,g,y,m,E,S,T,k;return _regenerator().w(function(t){for(;;)switch(t.p=t.n){case 0:return t.n=1,e.loadWasm();case 1:if(a=t.v,s=a.cwrap("decrypt_ts_segment","number",["number","number","number","number","number","number"]),o=a.cwrap("free_buffer",null,["number"]),l=a.cwrap("last_error","number",[]),u=e.normalizeFileId(n),c=e.normalizeAuthCipher(n,i),d=a._malloc(r.length),a.HEAPU8.set(r,d),h=u.length+1,f=a._malloc(h),a.stringToUTF8(u,f,h),v=c.length+1,p=a._malloc(v),a.stringToUTF8(c,p,v),g=a._malloc(4),y=a._malloc(4),t.p=2,0===(m=s(d,r.length,f,p,g,y))){t.n=3;break}throw E=l(),new Error("decrypt_ts_segment failed(".concat(m,"): ").concat(a.UTF8ToString(E)));case 3:return S=a.getValue(g,"*"),T=a.getValue(y,"i32"),(k=new Uint8Array(T)).set(a.HEAPU8.subarray(S,S+T)),o(S),t.a(2,k);case 4:return t.p=4,a._free(d),a._free(f),a._free(p),a._free(g),a._free(y),t.f(4);case 5:return t.a(2)}},t,null,[[2,,4,5]])})),function(e,t,n){return r.apply(this,arguments)})},{key:"decrypt",value:(t=_asyncToGenerator(_regenerator().m(function t(r,n,i){var a;return _regenerator().w(function(t){for(;;)if(0===t.n)return a="string"==typeof n?n:Array.from(n).map(function(e){return String.fromCharCode(e)}).join(""),t.a(2,e.decryptSegment(r,a,i))},t)})),function(e,r,n){return t.apply(this,arguments)})},{key:"init",value:function(){console.log("TsDecrypt initialized")}}]);var t,r,n,i}();_defineProperty$1(TsDecrypt,"module",null),_defineProperty$1(TsDecrypt,"isLoading",!1),_defineProperty$1(TsDecrypt,"loadPromise",null),_defineProperty$1(TsDecrypt,"baseUrl","https://wanzibook-res-1317978474.cos.ap-guangzhou.myqcloud.com/web/ffmpeglib");var type,hasRequiredType,tsMappingStore=new Map,getGroupKey=function(e){var t;return(null==e||null===(t=e[0])||void 0===t?void 0:t.url)||null},getCache=function(e){var t=getGroupKey(e);return t&&tsMappingStore.get(t)||null},parseM3u8ForTsUrls=function(e,t){for(var r=[],n=e.split("\n"),i=new URL(t),a=0;a<n.length;a++){var s=n[a].trim();if(s&&!s.startsWith("#")&&s.includes(".ts")){var o=s;if(!o.startsWith("http"))if(o.startsWith("/"))o="".concat(i.protocol,"//").concat(i.host).concat(o);else{var l=i.pathname.substring(0,i.pathname.lastIndexOf("/")+1);o="".concat(i.protocol,"//").concat(i.host).concat(l).concat(o)}r.push(o)}}return r},buildTsMapFromContents=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!e||!e.length)return{validCdnIndices:[],baseM3u8Url:null};var r=e[0].url,n=[];if(e.forEach(function(e,r){var i=t[e.url];i&&n.push({index:r,url:e.url,tsUrls:parseM3u8ForTsUrls(i,e.url)})}),0===n.length)return{validCdnIndices:[],baseM3u8Url:null};var i=n[0].tsUrls.length,a=n.filter(function(e){return e.tsUrls.length===i}),s={};a.forEach(function(e){s[e.index]=e.tsUrls});var o=a.map(function(e){return e.index});return tsMappingStore.set(r,{tsMap:s,validCdnIndices:o,baseM3u8Url:r}),{validCdnIndices:o,baseM3u8Url:r}},getCdnFallbackOrder=function(e){var t=getCache(e);return t&&t.validCdnIndices.length?t.validCdnIndices.slice():e&&e.length?e.map(function(e,t){return t}):[]},getTsUrlByCdnIndex=function(e,t,r){var n=getCache(e);if(!n)return null;var i=n.tsMap[r];return!i||t<0||t>=i.length?null:i[t]},CustomLoader=function(){function e(t){var r;if(_classCallCheck(this,e),(r=_callSuper(this,e,[t])).cdnList=t.cdnList||[],r.switchCdn=t.switchCdn||!1,r.isEncrypt=t.isEncrypt||!1,r.encryptedData=t.encryptedData||"",r.fileId=t.fileId||"",r.m3u8Cache=t.m3u8Cache||null,r.switchCdn&&r.cdnList.length>0)try{buildTsMapFromContents(r.cdnList,r.m3u8Cache||{})}catch(n){}return r}return _inherits(e,Hls.DefaultConfig.loader),_createClass(e,[{key:"load",value:function(t,r,n){var i=t&&t.url,a=t&&t.frag;if(i&&i.match(/\.ts(\?.*)?$/)&&a)return this.stats&&this.stats.loading&&(this.stats.loading.start=performance.now()),void(this.switchCdn?this.loadTsWithCdnFailover(t,r,n):this.loadTsOnce(i,t,r,n));_superPropGet(e,"load",this)([t,r,n])}},{key:"loadTsWithCdnFailover",value:function(e,t,r){var n=this,i=e.frag,a=e.url,s=getCdnFallbackOrder(this.cdnList);if(s.length){var o=function(t){if(t>=s.length)r.onError({code:0,text:"all cdn failed"},e,null,n.stats);else{var l=s[t],u=getTsUrlByCdnIndex(n.cdnList,i.sn,l)||a;n.customDownload(u,function(i,a){a?o(t+1):n.deliverTsData(u,i,e,r)})}};o(0)}else this.loadTsOnce(a,e,t,r)}},{key:"loadTsOnce",value:function(e,t,r,n){var i=this;this.customDownload(e,function(r,a){a?n.onError({code:0,text:a.message},t,null,i.stats):i.deliverTsData(e,r,t,n)})}},{key:"deliverTsData",value:function(e,t,r,n){var i=this.stats;i&&i.loading&&(i.loading.first=i.loading.first||performance.now(),i.loading.end=performance.now(),i.loaded=i.total=t.byteLength);var a=function(t){n.onSuccess({url:e,data:t},i,r,null)};if(this.isEncrypt){var s=new Uint8Array(t);TsDecrypt.decrypt(s,this.fileId,this.encryptedData).then(a).catch(function(){n.onError({code:0,text:"decrypt failed"},r,null,i)})}else a(t)}},{key:"customDownload",value:function(e,t){fetch(e).then(function(e){if(!e.ok)throw new Error("HTTP ".concat(e.status));return e.arrayBuffer()}).then(function(e){return t(e,null)}).catch(function(e){return t(null,e)})}},{key:"abort",value:function(){}},{key:"abortFragment",value:function(){}}])}(),CustomPlaylistLoader=function(){return _createClass(function e(t){_classCallCheck(this,e),this.config=t||{},this.context=null,this.stats={aborted:!1,loaded:0,retry:0,total:0,chunkCount:0,bwEstimate:0,loading:{start:0,end:0,first:0},parsing:{start:0,end:0},buffering:{start:0,end:0,first:0}}},[{key:"load",value:function(e,t,r){var n=this;this.context=e;var i=e.url;this.stats.loading.start=performance.now(),this.stats.aborted=!1;var a=this.config.m3u8Cache&&this.config.m3u8Cache[i];if(a)return this.stats.loading.first=this.stats.loading.start,void Promise.resolve().then(function(){n.deliverPlaylist(i,a,r)});fetch(i,{method:"GET",headers:{Accept:"application/vnd.apple.mpegurl, */*"}}).then(function(e){if(!e.ok)throw new Error("HTTP ".concat(e.status,": ").concat(e.statusText));return n.stats.loading.first=performance.now(),e.text()}).then(function(e){n.config.m3u8Cache&&(n.config.m3u8Cache[i]=e),n.deliverPlaylist(i,e,r)}).catch(function(t){r.onError({code:t.status||0,text:t.message},e,null,n.stats)})}},{key:"deliverPlaylist",value:function(e,t,r){this.stats.loading.end=performance.now(),this.stats.loaded=t.length,this.stats.total=t.length,this.stats.parsing.start=performance.now();var n=t.replace(/#EXT-X-KEY:[^\r\n]*\r?\n?/g,"");this.stats.parsing.end=performance.now(),r.onSuccess({url:e,data:n,code:200},this.stats,this.context,null)}},{key:"abort",value:function(){}},{key:"destroy",value:function(){this.context=null}},{key:"getCacheAge",value:function(){return null}},{key:"getResponseHeader",value:function(){return null}}])}(),HlsPlayer=function(){return _createClass(function e(){_classCallCheck(this,e)},null,[{key:"createHlsInstance",value:function(e,t,r,n){TsDecrypt.loadWasm();var i=new Hls({loader:CustomLoader,pLoader:CustomPlaylistLoader,cdnList:r,switchCdn:t,isEncrypt:n.isEncrypt,encryptedData:n.encryptedData,fileId:n.fileId,m3u8Cache:n.m3u8Cache||null,fragLoadingTimeOut:864e5,manifestLoadingTimeOut:864e5,levelLoadingTimeOut:864e5});return i.attachMedia(e),i.on(Hls.Events.ERROR,function(e,t){if(t&&"bufferAppendError"===t.details&&t.fatal&&i)try{i.recoverMediaError()}catch(r){}}),i}},{key:"startLoad",value:function(e,t){if(!e)throw new Error("HLS 实例不存在");e.loadSource(t)}},{key:"destroyHlsInstance",value:function(e){e&&e.destroy()}}])}(),ControlBtn=function(){return _createClass(function e(){_classCallCheck(this,e)},null,[{key:"changeBtnStatus",value:function(e){e.options.controls&&(e.playButton.style.display="playing"===e.status?"none":"block",e.pauseButton.style.display="playing"===e.status?"block":"none")}}])}(),ControlTime=function(){return _createClass(function e(){_classCallCheck(this,e)},null,[{key:"timeDouble",value:function(e){return e<10?"0".concat(e):e}},{key:"dealTime",value:function(e){var t=Math.floor(e/60),r=Math.floor(e%60);return"".concat(this.timeDouble(t),":").concat(this.timeDouble(r))}},{key:"updateDurationTime",value:function(e){if(e.options.controls){var t=e.videoElm.duration;e.totalTimeElm.textContent=this.dealTime(t)}}},{key:"updateCurrentTime",value:function(e,t){if(e.options.controls&&e.timeElm){var r=null!=t?t:e.videoElm.currentTime;Number.isFinite(r)&&(e.timeElm.textContent=this.dealTime(r))}}}])}(),ControlProgress=function(){return _createClass(function e(){_classCallCheck(this,e)},null,[{key:"updateLine",value:function(e,t){if(e.options.controls&&e.progressLine){var r=t;if(null==r){var n=e.videoElm&&e.videoElm.duration;if(!n||!Number.isFinite(n))return;r=e.videoElm.currentTime/n}Number.isFinite(r)&&(r=Math.max(0,Math.min(1,r)),e.progressLine.style.width="".concat(100*r,"%"),this.updateLineDot(e,r))}}},{key:"updateLineDot",value:function(e,t){e.options.controls&&e.progressLineDot&&(e.progressLineDot.style.left="".concat(100*t,"%"))}}])}(),ControlFullScreen=function(){function e(){_classCallCheck(this,e)}return _createClass(e,null,[{key:"getFullscreenTarget",value:function(e){var t=e&&e.options&&e.options.fullscreenElement;if(!t)return e.container;if(t instanceof HTMLElement)return t;if("string"==typeof t){var r=document.querySelector(t);if(r)return r;var n=document.getElementById(t.replace(/^#/,""));if(n)return n}return e.container}},{key:"changeFullScreen",value:function(e,t){e.isFullScreen=t,t?(e.exitFullScreenButton.style.display="block",e.fullScreenButton.style.display="none"):(e.exitFullScreenButton.style.display="none",e.fullScreenButton.style.display="block")}},{key:"fullScreen",value:function(t){if(isIos||isIosTablet())t.videoElm&&t.videoElm.webkitEnterFullscreen?t.videoElm.webkitEnterFullscreen():console.warn("iOS video fullscreen not supported");else{var r=e.getFullscreenTarget(t);r.requestFullscreen?r.requestFullscreen():r.mozRequestFullScreen?r.mozRequestFullScreen():r.webkitRequestFullScreen&&(r.webkitRequestFullScreen(),setTimeout(function(){document.dispatchEvent(new Event("fullscreenchange"))},0))}}},{key:"exitFullScreen",value:function(e){isIos?e.videoElm&&e.videoElm.webkitExitFullscreen&&e.videoElm.webkitExitFullscreen():document.exitFullscreen?document.exitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}}])}(),ControlVolume=function(){function e(){_classCallCheck(this,e)}return _createClass(e,null,[{key:"changeVolume",value:function(t,r){e.sync(t,r)}},{key:"sync",value:function(e,t){e.videoElm&&(e.videoElm.muted=!t),e.options&&e.options.controls&&e.volumeButton&&e.muteButton&&(t?(e.volumeButton.style.display="block",e.muteButton.style.display="none"):(e.volumeButton.style.display="none",e.muteButton.style.display="block"))}}])}(),SliderDrag=function(){return _createClass(function e(t,r){_classCallCheck(this,e),_defineProperty$1(this,"events",{}),this.slider=t,this.track=r,this.isDragging=!1,this.startX=0,this.startLeft=0,this.maxOffset=0,this.init()},[{key:"init",value:function(){this.maxOffset=this.track.offsetWidth,this.bindEvents()}},{key:"bindEvents",value:function(){var e=this;this.slider.addEventListener("mousedown",function(t){e.startDrag(t)}),document.addEventListener("mousemove",function(t){e.isDragging&&e.onDrag(t)}),document.addEventListener("mouseup",function(){e.stopDrag()}),this.slider.addEventListener("touchstart",function(t){e.startDragTouch(t)}),document.addEventListener("touchmove",function(t){e.isDragging&&e.onDragTouch(t)}),document.addEventListener("touchend",function(){e.stopDrag()})}},{key:"startDrag",value:function(e){e.preventDefault(),this.isDragging=!0,this.maxOffset=this.track.offsetWidth,this.startX=e.clientX,this.startLeft=this.slider.offsetLeft,this.slider.classList.add("dragging"),this.emit("dragstart",this.getCurrentValue())}},{key:"onDrag",value:function(e){if(this.isDragging){e.preventDefault();var t=e.clientX-this.startX,r=this.startLeft+t;r=Math.max(0,Math.min(this.maxOffset,r)),this.slider.style.left=r+"px",this.emit("drag",this.getCurrentValue())}}},{key:"stopDrag",value:function(){this.isDragging&&(this.isDragging=!1,this.slider.classList.remove("dragging"),this.emit("dragend",this.getCurrentValue()))}},{key:"startDragTouch",value:function(e){e.preventDefault(),this.isDragging=!0,this.maxOffset=this.track.offsetWidth;var t=e.touches[0];this.startX=t.clientX,this.startLeft=this.slider.offsetLeft,this.slider.classList.add("dragging"),this.emit("dragstart",this.getCurrentValue())}},{key:"onDragTouch",value:function(e){if(this.isDragging){e.preventDefault();var t=e.touches[0].clientX-this.startX,r=this.startLeft+t;r=Math.max(0,Math.min(this.maxOffset,r)),this.slider.style.left=r+"px",this.emit("drag",this.getCurrentValue())}}},{key:"getCurrentValue",value:function(){return this.slider.offsetLeft/this.maxOffset}},{key:"setValue",value:function(e){var t=(e=Math.max(0,Math.min(1,e)))*this.maxOffset;this.slider.style.left=t+"px"}},{key:"on",value:function(e,t){this.events[e]||(this.events[e]=[]),this.events[e].push(t)}},{key:"emit",value:function(e,t){this.events[e]&&this.events[e].forEach(function(e){return e(t)})}}])}(),ControlRate=function(){function e(){_classCallCheck(this,e)}return _createClass(e,null,[{key:"getList",value:function(e){var t=e&&e.container||e&&e.videoElm&&e.videoElm.parentElement;return t?t.querySelector(".ylc-video-player-rate-list"):null}},{key:"changeRate",value:function(t,r){t.videoElm.playbackRate=Number(r);var n=e.getList(t);if(n){n.querySelectorAll("li.ylc-video-player-rate-item").forEach(function(e){e.classList.remove("active")});var i=n.querySelector('li[data-value="'.concat(r,'"]'));i&&i.classList.add("active")}}},{key:"showRatePannel",value:function(t){var r=e.getList(t);r&&(r.style.display="block")}},{key:"hideRatePannel",value:function(t){var r=e.getList(t);r&&(r.style.display="none")}}])}(),ControlLine=function(){function e(){_classCallCheck(this,e)}return _createClass(e,null,[{key:"getRoot",value:function(e){return e.container||e.videoElm&&e.videoElm.parentElement}},{key:"getPanel",value:function(t){var r=e.getRoot(t);return r?r.querySelector(".ylc-video-player-line-panel"):null}},{key:"changeLineUI",value:function(t,r){var n=e.getRoot(t);if(n){var i=n.querySelector(".ylc-video-player-line-list"),a=n.querySelector(".ylc-video-player-line-label");if(i){i.querySelectorAll("li.ylc-video-player-line-item").forEach(function(e){e.classList.remove("active")});var s=i.querySelector('li[data-value="'.concat(r,'"]'));s&&s.classList.add("active"),a&&(a.textContent=2===Number(r)?"线路2":"线路1")}}}},{key:"showLinePannel",value:function(t){var r=e.getPanel(t);r&&(r.style.display="block")}},{key:"hideLinePannel",value:function(t){var r=e.getPanel(t);r&&(r.style.display="none")}}])}(),ControlBar=function(){function e(t){_classCallCheck(this,e),this.player=t,this.progressLineBg=null,this.rateButton=null,this._lineHideTimer=null}return _createClass(e,[{key:"collectRefs",value:function(){var e=this.player,t=function(t){return e.container.querySelector(t)};e.playButton=t(".ylc-video-player-play-button"),e.pauseButton=t(".ylc-video-player-pause-button"),e.timeElm=t(".ylc-video-player-current-time"),e.totalTimeElm=t(".ylc-video-player-total-time"),this.progressWrap=t(".ylc-video-player-progerss"),this.progressLineBg=t(".ylc-video-player-progress-line-bg"),e.progressLine=t(".ylc-video-player-progress-line"),e.progressLineDot=t(".ylc-video-player-progress-line-dot"),e.progressHoverTime=t(".ylc-video-player-progress-hover-time"),e.fullScreenButton=t(".ylc-video-player-full-screen-button"),e.exitFullScreenButton=t(".ylc-video-player-exit-full-screen-button"),e.volumeButton=t(".ylc-video-player-volume-button"),e.muteButton=t(".ylc-video-player-mute-button"),this.rateButton=t(".ylc-video-player-rate-button"),ControlVolume.sync(e,!e.videoElm.muted)}},{key:"bind",value:function(){var e=this,t=this.player;if(t.playButton){t.playButton.addEventListener("click",function(){Logger.click("VideoPlayer日志-点击了内部播放按钮"),t.play()}),t.pauseButton.addEventListener("click",function(){Logger.click("VideoPlayer日志-点击了内部暂停按钮"),t.pause()});var r=function(e,r){var n=t.videoElm&&t.videoElm.duration;if(n&&Number.isFinite(n)){var i=(e.clientX-r.left)/r.width;Number.isFinite(i)&&t.seek(Math.max(0,Math.min(1,i))*n)}};t.progressLine.addEventListener("click",function(t){Logger.click("VideoPlayer日志-点击了内部进度条快进"),r(t,e.progressLineBg.getBoundingClientRect())}),this.progressLineBg.addEventListener("click",function(e){Logger.click("VideoPlayer日志-点击了内部进度条背景快进"),r(e,e.target.getBoundingClientRect())});this.progressWrap&&(this.progressWrap.addEventListener("mousemove",function(r){var n=t.videoElm&&t.videoElm.duration,i=t.progressHoverTime,a=e.progressLineBg;if(i&&a)if(!n||!Number.isFinite(n)||n<=0)i.classList.remove("is-show");else{var s=a.getBoundingClientRect();if(s.width){var o=Math.max(0,Math.min(1,(r.clientX-s.left)/s.width));i.textContent=ControlTime.dealTime(o*n),i.classList.add("is-show");var l=i.offsetWidth/2,u=Math.max(l,Math.min(s.width-l,o*s.width));i.style.left="".concat(u,"px")}}}),this.progressWrap.addEventListener("mouseleave",function(){t.progressHoverTime&&t.progressHoverTime.classList.remove("is-show")})),t.progressSlider=new SliderDrag(t.progressLineDot,this.progressLineBg),t.progressSlider.on("drag",function(e){var r=t.videoElm&&t.videoElm.duration;ControlProgress.updateLine(t,e),Number.isFinite(r)&&ControlTime.updateCurrentTime(t,e*r),Logger.operate("VideoPlayer日志-正在拖拽内部进度条快进")}),t.progressSlider.on("dragend",function(e){var r=t.videoElm&&t.videoElm.duration;Logger.operate("VideoPlayer日志-结束拖拽内部进度条快进",{value:e,duration:r}),r&&Number.isFinite(r)&&t.seek(e*r)}),t.fullScreenButton.addEventListener("click",function(){Logger.click("VideoPlayer日志-点击了内部全屏按钮"),t.requestFullscreen(),t.events.emit("fullscreenchange",!0)}),t.exitFullScreenButton.addEventListener("click",function(){Logger.click("VideoPlayer日志-点击了内部退出全屏按钮"),t.exitFullscreen(),t.events.emit("fullscreenchange",!1)}),t.volumeButton.addEventListener("click",function(){Logger.click("VideoPlayer日志-点击了静音按钮"),ControlVolume.changeVolume(t,!1),t.events.emit("volumechange",!1)}),t.muteButton.addEventListener("click",function(){Logger.click("VideoPlayer日志-点击了开启音量按钮"),ControlVolume.changeVolume(t,!0),t.events.emit("volumechange",!0)}),this.rateButton.addEventListener("mouseenter",function(){t.events.emit("ratePannelChange",!0),ControlRate.showRatePannel(t)}),this.rateButton.addEventListener("mouseleave",function(){t.events.emit("ratePannelChange",!1),ControlRate.hideRatePannel(t)});var n=this.rateButton.querySelector(".ylc-video-player-rate-list");n&&n.querySelectorAll("li.ylc-video-player-rate-item").forEach(function(e){e.addEventListener("click",function(){ControlRate.changeRate(t,e.getAttribute("data-value")||1)})})}}},{key:"_bindLineButton",value:function(){var e=this,t=this.player,r=t.lineButton;if(r){var n=function(){e._lineHideTimer&&(clearTimeout(e._lineHideTimer),e._lineHideTimer=null)};r.addEventListener("mouseenter",function(){n(),t.events.emit("linePannelChange",!0),ControlLine.showLinePannel(t)}),r.addEventListener("mouseleave",function(){n(),e._lineHideTimer=setTimeout(function(){t.events.emit("linePannelChange",!1),ControlLine.hideLinePannel(t)},320)}),r.addEventListener("click",function(e){if(!(e.target&&e.target.closest&&e.target.closest(".ylc-video-player-line-item"))){e.stopPropagation(),n();var i=r.querySelector(".ylc-video-player-line-panel");if(i){var a="none"===i.style.display||!i.style.display;t.events.emit("linePannelChange",a),a?ControlLine.showLinePannel(t):ControlLine.hideLinePannel(t)}}});var i=r.querySelector(".ylc-video-player-line-list");i&&i.querySelectorAll("li.ylc-video-player-line-item").forEach(function(e){e.addEventListener("pointerdown",function(){var r=_asyncToGenerator(_regenerator().m(function r(n){var i;return _regenerator().w(function(r){for(;;)switch(r.p=r.n){case 0:return n.preventDefault(),n.stopPropagation(),i=Number(e.getAttribute("data-value"))||1,ControlLine.hideLinePannel(t),r.p=1,r.n=2,t.switchLine(i);case 2:r.v&&ControlLine.changeLineUI(t,i),r.n=4;break;case 3:r.p=3,r.v;case 4:return r.a(2)}},r,null,[[1,3]])}));return function(e){return r.apply(this,arguments)}}())})}}}],[{key:"mount",value:function(t){if(!(t&&t.options&&t.options.controls&&t.container))return null;var r=new e(t);return r.collectRefs(),r.bind(),r}}])}(),commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function getAugmentedNamespace(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if("function"==typeof t){var r=function e(){return this instanceof e?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,n.get?n:{enumerable:!0,get:function(){return e[t]}})}),r}function requireType(){return hasRequiredType?type:(hasRequiredType=1,type=TypeError)}var objectInspect,hasRequiredObjectInspect,sideChannelList,hasRequiredSideChannelList,esObjectAtoms,hasRequiredEsObjectAtoms,esErrors,hasRequiredEsErrors,_eval,hasRequired_eval,range,hasRequiredRange,ref,hasRequiredRef,syntax,hasRequiredSyntax,uri,hasRequiredUri,abs,hasRequiredAbs,floor,hasRequiredFloor,max,hasRequiredMax,min,hasRequiredMin,pow,hasRequiredPow,round,hasRequiredRound,_isNaN,hasRequired_isNaN,sign,hasRequiredSign,gOPD,hasRequiredGOPD,gopd,hasRequiredGopd,esDefineProperty,hasRequiredEsDefineProperty,shams,hasRequiredShams,hasSymbols,hasRequiredHasSymbols,Reflect_getPrototypeOf,hasRequiredReflect_getPrototypeOf,Object_getPrototypeOf,hasRequiredObject_getPrototypeOf,implementation,hasRequiredImplementation,functionBind,hasRequiredFunctionBind,functionCall,hasRequiredFunctionCall,functionApply,hasRequiredFunctionApply,reflectApply,hasRequiredReflectApply,actualApply,hasRequiredActualApply,callBindApplyHelpers,hasRequiredCallBindApplyHelpers,get,hasRequiredGet,getProto,hasRequiredGetProto,hasown,hasRequiredHasown,getIntrinsic,hasRequiredGetIntrinsic,callBound,hasRequiredCallBound,sideChannelMap,hasRequiredSideChannelMap,sideChannelWeakmap,hasRequiredSideChannelWeakmap,sideChannel,hasRequiredSideChannel,formats,hasRequiredFormats,utils$2,hasRequiredUtils,stringify_1,hasRequiredStringify,parse,hasRequiredParse,lib,hasRequiredLib,__viteBrowserExternal={},__viteBrowserExternal$1=Object.freeze({__proto__:null,default:__viteBrowserExternal}),require$$0=getAugmentedNamespace(__viteBrowserExternal$1);function requireObjectInspect(){if(hasRequiredObjectInspect)return objectInspect;hasRequiredObjectInspect=1;var e="function"==typeof Map&&Map.prototype,t=Object.getOwnPropertyDescriptor&&e?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,r=e&&t&&"function"==typeof t.get?t.get:null,n=e&&Map.prototype.forEach,i="function"==typeof Set&&Set.prototype,a=Object.getOwnPropertyDescriptor&&i?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,s=i&&a&&"function"==typeof a.get?a.get:null,o=i&&Set.prototype.forEach,l="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,u="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,c="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,d=Boolean.prototype.valueOf,h=Object.prototype.toString,f=Function.prototype.toString,v=String.prototype.match,p=String.prototype.slice,g=String.prototype.replace,y=String.prototype.toUpperCase,m=String.prototype.toLowerCase,E=RegExp.prototype.test,S=Array.prototype.concat,T=Array.prototype.join,k=Array.prototype.slice,_=Math.floor,A="function"==typeof BigInt?BigInt.prototype.valueOf:null,b=Object.getOwnPropertySymbols,L="function"==typeof Symbol&&"symbol"===_typeof(Symbol.iterator)?Symbol.prototype.toString:null,R="function"==typeof Symbol&&"object"===_typeof(Symbol.iterator),C="function"==typeof Symbol&&Symbol.toStringTag&&(_typeof(Symbol.toStringTag)===R||"symbol")?Symbol.toStringTag:null,I=Object.prototype.propertyIsEnumerable,P=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null);function D(e,t){if(e===1/0||e===-1/0||e!=e||e&&e>-1e3&&e<1e3||E.call(/e/,t))return t;var r=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof e){var n=e<0?-_(-e):_(e);if(n!==e){var i=String(n),a=p.call(t,i.length+1);return g.call(i,r,"$&_")+"."+g.call(g.call(a,/([0-9]{3})/g,"$&_"),/_$/,"")}}return g.call(t,r,"$&_")}var w=require$$0,O=w.custom,x=$(O)?O:null,M={__proto__:null,double:'"',single:"'"},F={__proto__:null,double:/(["\\])/g,single:/(['\\])/g};function N(e,t,r){var n=r.quoteStyle||t,i=M[n];return i+e+i}function U(e){return g.call(String(e),/"/g,"&quot;")}function B(e){return!C||!("object"===_typeof(e)&&(C in e||void 0!==e[C]))}function G(e){return"[object Array]"===j(e)&&B(e)}function H(e){return"[object RegExp]"===j(e)&&B(e)}function $(e){if(R)return e&&"object"===_typeof(e)&&e instanceof Symbol;if("symbol"===_typeof(e))return!0;if(!e||"object"!==_typeof(e)||!L)return!1;try{return L.call(e),!0}catch(t){}return!1}objectInspect=function e(t,i,a,h){var y=i||{};if(V(y,"quoteStyle")&&!V(M,y.quoteStyle))throw new TypeError('option "quoteStyle" must be "single" or "double"');if(V(y,"maxStringLength")&&("number"==typeof y.maxStringLength?y.maxStringLength<0&&y.maxStringLength!==1/0:null!==y.maxStringLength))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var E=!V(y,"customInspect")||y.customInspect;if("boolean"!=typeof E&&"symbol"!==E)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(V(y,"indent")&&null!==y.indent&&"\t"!==y.indent&&!(parseInt(y.indent,10)===y.indent&&y.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(V(y,"numericSeparator")&&"boolean"!=typeof y.numericSeparator)throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var _=y.numericSeparator;if(void 0===t)return"undefined";if(null===t)return"null";if("boolean"==typeof t)return t?"true":"false";if("string"==typeof t)return W(t,y);if("number"==typeof t){if(0===t)return 1/0/t>0?"0":"-0";var b=String(t);return _?D(t,b):b}if("bigint"==typeof t){var O=String(t)+"n";return _?D(t,O):O}var F=void 0===y.depth?5:y.depth;if(void 0===a&&(a=0),a>=F&&F>0&&"object"===_typeof(t))return G(t)?"[Array]":"[Object]";var K=function(e,t){var r;if("\t"===e.indent)r="\t";else{if(!("number"==typeof e.indent&&e.indent>0))return null;r=T.call(Array(e.indent+1)," ")}return{base:r,prev:T.call(Array(t+1),r)}}(y,a);if(void 0===h)h=[];else if(q(h,t)>=0)return"[Circular]";function Y(t,r,n){if(r&&(h=k.call(h)).push(r),n){var i={depth:y.depth};return V(y,"quoteStyle")&&(i.quoteStyle=y.quoteStyle),e(t,i,a+1,h)}return e(t,y,a+1,h)}if("function"==typeof t&&!H(t)){var ee=function(e){if(e.name)return e.name;var t=v.call(f.call(e),/^function\s*([\w$]+)/);if(t)return t[1];return null}(t),te=Z(t,Y);return"[Function"+(ee?": "+ee:" (anonymous)")+"]"+(te.length>0?" { "+T.call(te,", ")+" }":"")}if($(t)){var re=R?g.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):L.call(t);return"object"!==_typeof(t)||R?re:z(re)}if(function(e){if(!e||"object"!==_typeof(e))return!1;if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return!0;return"string"==typeof e.nodeName&&"function"==typeof e.getAttribute}(t)){for(var ne="<"+m.call(String(t.nodeName)),ie=t.attributes||[],ae=0;ae<ie.length;ae++)ne+=" "+ie[ae].name+"="+N(U(ie[ae].value),"double",y);return ne+=">",t.childNodes&&t.childNodes.length&&(ne+="..."),ne+="</"+m.call(String(t.nodeName))+">"}if(G(t)){if(0===t.length)return"[]";var se=Z(t,Y);return K&&!function(e){for(var t=0;t<e.length;t++)if(q(e[t],"\n")>=0)return!1;return!0}(se)?"["+J(se,K)+"]":"[ "+T.call(se,", ")+" ]"}if(function(e){return"[object Error]"===j(e)&&B(e)}(t)){var oe=Z(t,Y);return"cause"in Error.prototype||!("cause"in t)||I.call(t,"cause")?0===oe.length?"["+String(t)+"]":"{ ["+String(t)+"] "+T.call(oe,", ")+" }":"{ ["+String(t)+"] "+T.call(S.call("[cause]: "+Y(t.cause),oe),", ")+" }"}if("object"===_typeof(t)&&E){if(x&&"function"==typeof t[x]&&w)return w(t,{depth:F-a});if("symbol"!==E&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!r||!e||"object"!==_typeof(e))return!1;try{r.call(e);try{s.call(e)}catch(ne){return!0}return e instanceof Map}catch(t){}return!1}(t)){var le=[];return n&&n.call(t,function(e,r){le.push(Y(r,t,!0)+" => "+Y(e,t))}),Q("Map",r.call(t),le,K)}if(function(e){if(!s||!e||"object"!==_typeof(e))return!1;try{s.call(e);try{r.call(e)}catch(t){return!0}return e instanceof Set}catch(n){}return!1}(t)){var ue=[];return o&&o.call(t,function(e){ue.push(Y(e,t))}),Q("Set",s.call(t),ue,K)}if(function(e){if(!l||!e||"object"!==_typeof(e))return!1;try{l.call(e,l);try{u.call(e,u)}catch(ne){return!0}return e instanceof WeakMap}catch(t){}return!1}(t))return X("WeakMap");if(function(e){if(!u||!e||"object"!==_typeof(e))return!1;try{u.call(e,u);try{l.call(e,l)}catch(ne){return!0}return e instanceof WeakSet}catch(t){}return!1}(t))return X("WeakSet");if(function(e){if(!c||!e||"object"!==_typeof(e))return!1;try{return c.call(e),!0}catch(t){}return!1}(t))return X("WeakRef");if(function(e){return"[object Number]"===j(e)&&B(e)}(t))return z(Y(Number(t)));if(function(e){if(!e||"object"!==_typeof(e)||!A)return!1;try{return A.call(e),!0}catch(t){}return!1}(t))return z(Y(A.call(t)));if(function(e){return"[object Boolean]"===j(e)&&B(e)}(t))return z(d.call(t));if(function(e){return"[object String]"===j(e)&&B(e)}(t))return z(Y(String(t)));if("undefined"!=typeof window&&t===window)return"{ [object Window] }";if("undefined"!=typeof globalThis&&t===globalThis||void 0!==commonjsGlobal&&t===commonjsGlobal)return"{ [object globalThis] }";if(!function(e){return"[object Date]"===j(e)&&B(e)}(t)&&!H(t)){var ce=Z(t,Y),de=P?P(t)===Object.prototype:t instanceof Object||t.constructor===Object,he=t instanceof Object?"":"null prototype",fe=!de&&C&&Object(t)===t&&C in t?p.call(j(t),8,-1):he?"Object":"",ve=(de||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(fe||he?"["+T.call(S.call([],fe||[],he||[]),": ")+"] ":"");return 0===ce.length?ve+"{}":K?ve+"{"+J(ce,K)+"}":ve+"{ "+T.call(ce,", ")+" }"}return String(t)};var K=Object.prototype.hasOwnProperty||function(e){return e in this};function V(e,t){return K.call(e,t)}function j(e){return h.call(e)}function q(e,t){if(e.indexOf)return e.indexOf(t);for(var r=0,n=e.length;r<n;r++)if(e[r]===t)return r;return-1}function W(e,t){if(e.length>t.maxStringLength){var r=e.length-t.maxStringLength,n="... "+r+" more character"+(r>1?"s":"");return W(p.call(e,0,t.maxStringLength),t)+n}var i=F[t.quoteStyle||"single"];return i.lastIndex=0,N(g.call(g.call(e,i,"\\$1"),/[\x00-\x1f]/g,Y),"single",t)}function Y(e){var t=e.charCodeAt(0),r={8:"b",9:"t",10:"n",12:"f",13:"r"}[t];return r?"\\"+r:"\\x"+(t<16?"0":"")+y.call(t.toString(16))}function z(e){return"Object("+e+")"}function X(e){return e+" { ? }"}function Q(e,t,r,n){return e+" ("+t+") {"+(n?J(r,n):T.call(r,", "))+"}"}function J(e,t){if(0===e.length)return"";var r="\n"+t.prev+t.base;return r+T.call(e,","+r)+"\n"+t.prev}function Z(e,t){var r=G(e),n=[];if(r){n.length=e.length;for(var i=0;i<e.length;i++)n[i]=V(e,i)?t(e[i],e):""}var a,s="function"==typeof b?b(e):[];if(R){a={};for(var o=0;o<s.length;o++)a["$"+s[o]]=s[o]}for(var l in e)V(e,l)&&(r&&String(Number(l))===l&&l<e.length||R&&a["$"+l]instanceof Symbol||(E.call(/[^\w$]/,l)?n.push(t(l,e)+": "+t(e[l],e)):n.push(l+": "+t(e[l],e))));if("function"==typeof b)for(var u=0;u<s.length;u++)I.call(e,s[u])&&n.push("["+t(s[u])+"]: "+t(e[s[u]],e));return n}return objectInspect}function requireSideChannelList(){if(hasRequiredSideChannelList)return sideChannelList;hasRequiredSideChannelList=1;var e=requireObjectInspect(),t=requireType(),r=function(e,t,r){for(var n,i=e;null!=(n=i.next);i=n)if(n.key===t)return i.next=n.next,r||(n.next=e.next,e.next=n),n};return sideChannelList=function(){var n,i={assert:function(r){if(!i.has(r))throw new t("Side channel does not contain "+e(r))},delete:function(e){var t=function(e,t){if(e)return r(e,t,!0)}(n,e);return t&&n&&!n.next&&(n=void 0),!!t},get:function(e){return function(e,t){if(e){var n=r(e,t);return n&&n.value}}(n,e)},has:function(e){return function(e,t){return!!e&&!!r(e,t)}(n,e)},set:function(e,t){n||(n={next:void 0}),function(e,t,n){var i=r(e,t);i?i.value=n:e.next={key:t,next:e.next,value:n}}(n,e,t)}};return i}}function requireEsObjectAtoms(){return hasRequiredEsObjectAtoms?esObjectAtoms:(hasRequiredEsObjectAtoms=1,esObjectAtoms=Object)}function requireEsErrors(){return hasRequiredEsErrors?esErrors:(hasRequiredEsErrors=1,esErrors=Error)}function require_eval(){return hasRequired_eval?_eval:(hasRequired_eval=1,_eval=EvalError)}function requireRange(){return hasRequiredRange?range:(hasRequiredRange=1,range=RangeError)}function requireRef(){return hasRequiredRef?ref:(hasRequiredRef=1,ref=ReferenceError)}function requireSyntax(){return hasRequiredSyntax?syntax:(hasRequiredSyntax=1,syntax=SyntaxError)}function requireUri(){return hasRequiredUri?uri:(hasRequiredUri=1,uri=URIError)}function requireAbs(){return hasRequiredAbs?abs:(hasRequiredAbs=1,abs=Math.abs)}function requireFloor(){return hasRequiredFloor?floor:(hasRequiredFloor=1,floor=Math.floor)}function requireMax(){return hasRequiredMax?max:(hasRequiredMax=1,max=Math.max)}function requireMin(){return hasRequiredMin?min:(hasRequiredMin=1,min=Math.min)}function requirePow(){return hasRequiredPow?pow:(hasRequiredPow=1,pow=Math.pow)}function requireRound(){return hasRequiredRound?round:(hasRequiredRound=1,round=Math.round)}function require_isNaN(){return hasRequired_isNaN?_isNaN:(hasRequired_isNaN=1,_isNaN=Number.isNaN||function(e){return e!=e})}function requireSign(){if(hasRequiredSign)return sign;hasRequiredSign=1;var e=require_isNaN();return sign=function(t){return e(t)||0===t?t:t<0?-1:1}}function requireGOPD(){return hasRequiredGOPD?gOPD:(hasRequiredGOPD=1,gOPD=Object.getOwnPropertyDescriptor)}function requireGopd(){if(hasRequiredGopd)return gopd;hasRequiredGopd=1;var e=requireGOPD();if(e)try{e([],"length")}catch(t){e=null}return gopd=e}function requireEsDefineProperty(){if(hasRequiredEsDefineProperty)return esDefineProperty;hasRequiredEsDefineProperty=1;var e=Object.defineProperty||!1;if(e)try{e({},"a",{value:1})}catch(t){e=!1}return esDefineProperty=e}function requireShams(){return hasRequiredShams?shams:(hasRequiredShams=1,shams=function(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"===_typeof(Symbol.iterator))return!0;var e={},t=Symbol("test"),r=Object(t);if("string"==typeof t)return!1;if("[object Symbol]"!==Object.prototype.toString.call(t))return!1;if("[object Symbol]"!==Object.prototype.toString.call(r))return!1;for(var n in e[t]=42,e)return!1;if("function"==typeof Object.keys&&0!==Object.keys(e).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(e).length)return!1;var i=Object.getOwnPropertySymbols(e);if(1!==i.length||i[0]!==t)return!1;if(!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var a=Object.getOwnPropertyDescriptor(e,t);if(42!==a.value||!0!==a.enumerable)return!1}return!0})}function requireHasSymbols(){if(hasRequiredHasSymbols)return hasSymbols;hasRequiredHasSymbols=1;var e="undefined"!=typeof Symbol&&Symbol,t=requireShams();return hasSymbols=function(){return"function"==typeof e&&("function"==typeof Symbol&&("symbol"===_typeof(e("foo"))&&("symbol"===_typeof(Symbol("bar"))&&t())))}}function requireReflect_getPrototypeOf(){return hasRequiredReflect_getPrototypeOf?Reflect_getPrototypeOf:(hasRequiredReflect_getPrototypeOf=1,Reflect_getPrototypeOf="undefined"!=typeof Reflect&&Reflect.getPrototypeOf||null)}function requireObject_getPrototypeOf(){return hasRequiredObject_getPrototypeOf?Object_getPrototypeOf:(hasRequiredObject_getPrototypeOf=1,Object_getPrototypeOf=requireEsObjectAtoms().getPrototypeOf||null)}function requireImplementation(){if(hasRequiredImplementation)return implementation;hasRequiredImplementation=1;var e=Object.prototype.toString,t=Math.max,r=function(e,t){for(var r=[],n=0;n<e.length;n+=1)r[n]=e[n];for(var i=0;i<t.length;i+=1)r[i+e.length]=t[i];return r};return implementation=function(n){var i=this;if("function"!=typeof i||"[object Function]"!==e.apply(i))throw new TypeError("Function.prototype.bind called on incompatible "+i);for(var a,s=function(e,t){for(var r=[],n=t,i=0;n<e.length;n+=1,i+=1)r[i]=e[n];return r}(arguments,1),o=t(0,i.length-s.length),l=[],u=0;u<o;u++)l[u]="$"+u;if(a=Function("binder","return function ("+function(e,t){for(var r="",n=0;n<e.length;n+=1)r+=e[n],n+1<e.length&&(r+=t);return r}(l,",")+"){ return binder.apply(this,arguments); }")(function(){if(this instanceof a){var e=i.apply(this,r(s,arguments));return Object(e)===e?e:this}return i.apply(n,r(s,arguments))}),i.prototype){var c=function(){};c.prototype=i.prototype,a.prototype=new c,c.prototype=null}return a},implementation}function requireFunctionBind(){if(hasRequiredFunctionBind)return functionBind;hasRequiredFunctionBind=1;var e=requireImplementation();return functionBind=Function.prototype.bind||e}function requireFunctionCall(){return hasRequiredFunctionCall?functionCall:(hasRequiredFunctionCall=1,functionCall=Function.prototype.call)}function requireFunctionApply(){return hasRequiredFunctionApply?functionApply:(hasRequiredFunctionApply=1,functionApply=Function.prototype.apply)}function requireReflectApply(){return hasRequiredReflectApply?reflectApply:(hasRequiredReflectApply=1,reflectApply="undefined"!=typeof Reflect&&Reflect&&Reflect.apply)}function requireActualApply(){if(hasRequiredActualApply)return actualApply;hasRequiredActualApply=1;var e=requireFunctionBind(),t=requireFunctionApply(),r=requireFunctionCall(),n=requireReflectApply();return actualApply=n||e.call(r,t)}function requireCallBindApplyHelpers(){if(hasRequiredCallBindApplyHelpers)return callBindApplyHelpers;hasRequiredCallBindApplyHelpers=1;var e=requireFunctionBind(),t=requireType(),r=requireFunctionCall(),n=requireActualApply();return callBindApplyHelpers=function(i){if(i.length<1||"function"!=typeof i[0])throw new t("a function is required");return n(e,r,i)}}function requireGet(){if(hasRequiredGet)return get;hasRequiredGet=1;var e,t=requireCallBindApplyHelpers(),r=requireGopd();try{e=[].__proto__===Array.prototype}catch(s){if(!s||"object"!==_typeof(s)||!("code"in s)||"ERR_PROTO_ACCESS"!==s.code)throw s}var n=!!e&&r&&r(Object.prototype,"__proto__"),i=Object,a=i.getPrototypeOf;return get=n&&"function"==typeof n.get?t([n.get]):"function"==typeof a&&function(e){return a(null==e?e:i(e))}}function requireGetProto(){if(hasRequiredGetProto)return getProto;hasRequiredGetProto=1;var e=requireReflect_getPrototypeOf(),t=requireObject_getPrototypeOf(),r=requireGet();return getProto=e?function(t){return e(t)}:t?function(e){if(!e||"object"!==_typeof(e)&&"function"!=typeof e)throw new TypeError("getProto: not an object");return t(e)}:r?function(e){return r(e)}:null}function requireHasown(){if(hasRequiredHasown)return hasown;hasRequiredHasown=1;var e=Function.prototype.call,t=Object.prototype.hasOwnProperty,r=requireFunctionBind();return hasown=r.call(e,t)}function requireGetIntrinsic(){if(hasRequiredGetIntrinsic)return getIntrinsic;var e;hasRequiredGetIntrinsic=1;var t=requireEsObjectAtoms(),r=requireEsErrors(),n=require_eval(),i=requireRange(),a=requireRef(),s=requireSyntax(),o=requireType(),l=requireUri(),u=requireAbs(),c=requireFloor(),d=requireMax(),h=requireMin(),f=requirePow(),v=requireRound(),p=requireSign(),g=Function,y=function(e){try{return g('"use strict"; return ('+e+").constructor;")()}catch(t){}},m=requireGopd(),E=requireEsDefineProperty(),S=function(){throw new o},T=m?function(){try{return S}catch(e){try{return m(arguments,"callee").get}catch(t){return S}}}():S,k=requireHasSymbols()(),_=requireGetProto(),A=requireObject_getPrototypeOf(),b=requireReflect_getPrototypeOf(),L=requireFunctionApply(),R=requireFunctionCall(),C={},I="undefined"!=typeof Uint8Array&&_?_(Uint8Array):e,P={__proto__:null,"%AggregateError%":"undefined"==typeof AggregateError?e:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?e:ArrayBuffer,"%ArrayIteratorPrototype%":k&&_?_([][Symbol.iterator]()):e,"%AsyncFromSyncIteratorPrototype%":e,"%AsyncFunction%":C,"%AsyncGenerator%":C,"%AsyncGeneratorFunction%":C,"%AsyncIteratorPrototype%":C,"%Atomics%":"undefined"==typeof Atomics?e:Atomics,"%BigInt%":"undefined"==typeof BigInt?e:BigInt,"%BigInt64Array%":"undefined"==typeof BigInt64Array?e:BigInt64Array,"%BigUint64Array%":"undefined"==typeof BigUint64Array?e:BigUint64Array,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?e:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":r,"%eval%":eval,"%EvalError%":n,"%Float16Array%":"undefined"==typeof Float16Array?e:Float16Array,"%Float32Array%":"undefined"==typeof Float32Array?e:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?e:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?e:FinalizationRegistry,"%Function%":g,"%GeneratorFunction%":C,"%Int8Array%":"undefined"==typeof Int8Array?e:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?e:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?e:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":k&&_?_(_([][Symbol.iterator]())):e,"%JSON%":"object"===("undefined"==typeof JSON?"undefined":_typeof(JSON))?JSON:e,"%Map%":"undefined"==typeof Map?e:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&k&&_?_((new Map)[Symbol.iterator]()):e,"%Math%":Math,"%Number%":Number,"%Object%":t,"%Object.getOwnPropertyDescriptor%":m,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?e:Promise,"%Proxy%":"undefined"==typeof Proxy?e:Proxy,"%RangeError%":i,"%ReferenceError%":a,"%Reflect%":"undefined"==typeof Reflect?e:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?e:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&k&&_?_((new Set)[Symbol.iterator]()):e,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?e:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":k&&_?_(""[Symbol.iterator]()):e,"%Symbol%":k?Symbol:e,"%SyntaxError%":s,"%ThrowTypeError%":T,"%TypedArray%":I,"%TypeError%":o,"%Uint8Array%":"undefined"==typeof Uint8Array?e:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?e:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?e:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?e:Uint32Array,"%URIError%":l,"%WeakMap%":"undefined"==typeof WeakMap?e:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?e:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?e:WeakSet,"%Function.prototype.call%":R,"%Function.prototype.apply%":L,"%Object.defineProperty%":E,"%Object.getPrototypeOf%":A,"%Math.abs%":u,"%Math.floor%":c,"%Math.max%":d,"%Math.min%":h,"%Math.pow%":f,"%Math.round%":v,"%Math.sign%":p,"%Reflect.getPrototypeOf%":b};if(_)try{null.error}catch(V){var D=_(_(V));P["%Error.prototype%"]=D}var w=function e(t){var r;if("%AsyncFunction%"===t)r=y("async function () {}");else if("%GeneratorFunction%"===t)r=y("function* () {}");else if("%AsyncGeneratorFunction%"===t)r=y("async function* () {}");else if("%AsyncGenerator%"===t){var n=e("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else if("%AsyncIteratorPrototype%"===t){var i=e("%AsyncGenerator%");i&&_&&(r=_(i.prototype))}return P[t]=r,r},O={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},x=requireFunctionBind(),M=requireHasown(),F=x.call(R,Array.prototype.concat),N=x.call(L,Array.prototype.splice),U=x.call(R,String.prototype.replace),B=x.call(R,String.prototype.slice),G=x.call(R,RegExp.prototype.exec),H=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,$=/\\(\\)?/g,K=function(e,t){var r,n=e;if(M(O,n)&&(n="%"+(r=O[n])[0]+"%"),M(P,n)){var i=P[n];if(i===C&&(i=w(n)),void 0===i&&!t)throw new o("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:r,name:n,value:i}}throw new s("intrinsic "+e+" does not exist!")};return getIntrinsic=function(e,t){if("string"!=typeof e||0===e.length)throw new o("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof t)throw new o('"allowMissing" argument must be a boolean');if(null===G(/^%?[^%]*%?$/,e))throw new s("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var r=function(e){var t=B(e,0,1),r=B(e,-1);if("%"===t&&"%"!==r)throw new s("invalid intrinsic syntax, expected closing `%`");if("%"===r&&"%"!==t)throw new s("invalid intrinsic syntax, expected opening `%`");var n=[];return U(e,H,function(e,t,r,i){n[n.length]=r?U(i,$,"$1"):t||e}),n}(e),n=r.length>0?r[0]:"",i=K("%"+n+"%",t),a=i.name,l=i.value,u=!1,c=i.alias;c&&(n=c[0],N(r,F([0,1],c)));for(var d=1,h=!0;d<r.length;d+=1){var f=r[d],v=B(f,0,1),p=B(f,-1);if(('"'===v||"'"===v||"`"===v||'"'===p||"'"===p||"`"===p)&&v!==p)throw new s("property names with quotes must have matching quotes");if("constructor"!==f&&h||(u=!0),M(P,a="%"+(n+="."+f)+"%"))l=P[a];else if(null!=l){if(!(f in l)){if(!t)throw new o("base intrinsic for "+e+" exists, but the property is not available.");return}if(m&&d+1>=r.length){var g=m(l,f);l=(h=!!g)&&"get"in g&&!("originalValue"in g.get)?g.get:l[f]}else h=M(l,f),l=l[f];h&&!u&&(P[a]=l)}}return l},getIntrinsic}function requireCallBound(){if(hasRequiredCallBound)return callBound;hasRequiredCallBound=1;var e=requireGetIntrinsic(),t=requireCallBindApplyHelpers(),r=t([e("%String.prototype.indexOf%")]);return callBound=function(n,i){var a=e(n,!!i);return"function"==typeof a&&r(n,".prototype.")>-1?t([a]):a}}function requireSideChannelMap(){if(hasRequiredSideChannelMap)return sideChannelMap;hasRequiredSideChannelMap=1;var e=requireGetIntrinsic(),t=requireCallBound(),r=requireObjectInspect(),n=requireType(),i=e("%Map%",!0),a=t("Map.prototype.get",!0),s=t("Map.prototype.set",!0),o=t("Map.prototype.has",!0),l=t("Map.prototype.delete",!0),u=t("Map.prototype.size",!0);return sideChannelMap=!!i&&function(){var e,t={assert:function(e){if(!t.has(e))throw new n("Side channel does not contain "+r(e))},delete:function(t){if(e){var r=l(e,t);return 0===u(e)&&(e=void 0),r}return!1},get:function(t){if(e)return a(e,t)},has:function(t){return!!e&&o(e,t)},set:function(t,r){e||(e=new i),s(e,t,r)}};return t}}function requireSideChannelWeakmap(){if(hasRequiredSideChannelWeakmap)return sideChannelWeakmap;hasRequiredSideChannelWeakmap=1;var e=requireGetIntrinsic(),t=requireCallBound(),r=requireObjectInspect(),n=requireSideChannelMap(),i=requireType(),a=e("%WeakMap%",!0),s=t("WeakMap.prototype.get",!0),o=t("WeakMap.prototype.set",!0),l=t("WeakMap.prototype.has",!0),u=t("WeakMap.prototype.delete",!0);return sideChannelWeakmap=a?function(){var e,t,c={assert:function(e){if(!c.has(e))throw new i("Side channel does not contain "+r(e))},delete:function(r){if(a&&r&&("object"===_typeof(r)||"function"==typeof r)){if(e)return u(e,r)}else if(n&&t)return t.delete(r);return!1},get:function(r){return a&&r&&("object"===_typeof(r)||"function"==typeof r)&&e?s(e,r):t&&t.get(r)},has:function(r){return a&&r&&("object"===_typeof(r)||"function"==typeof r)&&e?l(e,r):!!t&&t.has(r)},set:function(r,i){a&&r&&("object"===_typeof(r)||"function"==typeof r)?(e||(e=new a),o(e,r,i)):n&&(t||(t=n()),t.set(r,i))}};return c}:n}function requireSideChannel(){if(hasRequiredSideChannel)return sideChannel;hasRequiredSideChannel=1;var e=requireType(),t=requireObjectInspect(),r=requireSideChannelList(),n=requireSideChannelMap(),i=requireSideChannelWeakmap()||n||r;return sideChannel=function(){var r,n={assert:function(r){if(!n.has(r)){var i=r&&Object(r)===r?"the given object key":t(r);throw new e("Side channel does not contain "+i)}},delete:function(e){return!!r&&r.delete(e)},get:function(e){return r&&r.get(e)},has:function(e){return!!r&&r.has(e)},set:function(e,t){r||(r=i()),r.set(e,t)}};return n}}function requireFormats(){if(hasRequiredFormats)return formats;hasRequiredFormats=1;var e=String.prototype.replace,t=/%20/g,r="RFC3986";return formats={default:r,formatters:{RFC1738:function(r){return e.call(r,t,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:r}}function requireUtils(){if(hasRequiredUtils)return utils$2;hasRequiredUtils=1;var e=requireFormats(),t=requireSideChannel(),r=requireEsDefineProperty(),n=Object.prototype.hasOwnProperty,i=Array.isArray,a=t(),s=function(e,t){return a.set(e,t),e},o=function(e){return a.has(e)},l=function(e){return a.get(e)},u=function(e,t){a.set(e,t)},c=function(){for(var e=[],t=0;t<256;++t)e[e.length]="%"+((t<16?"0":"")+t.toString(16)).toUpperCase();return e}(),d=function(e,t){for(var r=t&&t.plainObjects?{__proto__:null}:{},n=0;n<e.length;++n)void 0!==e[n]&&(r[n]=e[n]);return r},h=function(e,t,n){"__proto__"===t&&r?r(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0}):e[t]=n},f=1024;return utils$2={arrayToObject:d,assign:function(e,t){return Object.keys(t).reduce(function(e,r){return h(e,r,t[r]),e},e)},combine:function(e,t,r,n,a){if(o(e)){if(a)throw new RangeError("Array limit exceeded. Only "+r+" element"+(1===r?"":"s")+" allowed in an array.");for(var c=i(t)?t:[t],h=l(e),f=0;f<c.length;++f)e[h+=1]=c[f];return u(e,h),e}var v=[].concat(e,t);if(v.length>r){if(a)throw new RangeError("Array limit exceeded. Only "+r+" element"+(1===r?"":"s")+" allowed in an array.");return s(d(v,{plainObjects:n}),v.length-1)}return v},compact:function(e){for(var r=[{obj:{o:e},prop:"o"}],n=t(),a=0;a<r.length;++a)for(var s=r[a],o=s.obj[s.prop],l=Object.keys(o),u=0;u<l.length;++u){var c=l[u],d=o[c];"object"!==_typeof(d)||null===d||n.has(d)||(r[r.length]={obj:o,prop:c},n.set(d,!0))}return function(e){for(;e.length>1;){var t=e.pop(),r=t.obj[t.prop];if(i(r)){for(var n=[],a=0;a<r.length;++a)void 0!==r[a]&&(n[n.length]=r[a]);t.obj[t.prop]=n}}}(r),e},decode:function(e,t,r){var n=e.replace(/\+/g," ");if("iso-8859-1"===r)return n.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(n)}catch(i){return n}},encode:function(t,r,n,i,a){if(0===t.length)return t;var s=t;if("symbol"===_typeof(t)?s=Symbol.prototype.toString.call(t):"string"!=typeof t&&(s=String(t)),"iso-8859-1"===n)return escape(s).replace(/%u[0-9a-f]{4}/gi,function(e){return"%26%23"+parseInt(e.slice(2),16)+"%3B"});for(var o="",l=0;l<s.length;l+=f){var u=s.length>=f?s.slice(l,l+f):s;if(l+f<s.length){var d=u.charCodeAt(u.length-1);d>=55296&&d<=56319&&(u=u.slice(0,-1),l-=1)}for(var h=[],v=0;v<u.length;++v){var p=u.charCodeAt(v);45===p||46===p||95===p||126===p||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||a===e.RFC1738&&(40===p||41===p)?h[h.length]=u.charAt(v):p<128?h[h.length]=c[p]:p<2048?h[h.length]=c[192|p>>6]+c[128|63&p]:p<55296||p>=57344?h[h.length]=c[224|p>>12]+c[128|p>>6&63]+c[128|63&p]:(v+=1,p=65536+((1023&p)<<10|1023&u.charCodeAt(v)),h[h.length]=c[240|p>>18]+c[128|p>>12&63]+c[128|p>>6&63]+c[128|63&p])}o+=h.join("")}return o},isBuffer:function(e){return!(!e||"object"!==_typeof(e))&&!(!e.constructor||"function"!=typeof e.constructor.isBuffer||!e.constructor.isBuffer(e))},isOverflow:o,isRegExp:function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},markOverflow:s,maybeMap:function(e,t){if(i(e)){for(var r=[],n=0;n<e.length;n+=1)r[r.length]=t(e[n]);return r}return t(e)},merge:function e(t,r,a){if(!r)return t;if("object"!==_typeof(r)&&"function"!=typeof r){if(i(t)){var c=t.length;if(a&&"number"==typeof a.arrayLimit&&c>=a.arrayLimit){if(a.throwOnLimitExceeded)throw new RangeError("Array limit exceeded. Only "+a.arrayLimit+" element"+(1===a.arrayLimit?"":"s")+" allowed in an array.");return s(d(t.concat(r),a),c)}t[c]=r}else{if(!t||"object"!==_typeof(t))return[t,r];if(o(t)){var f=l(t)+1;t[f]=r,u(t,f)}else{if(a&&a.strictMerge)return[t,r];(a&&(a.plainObjects||a.allowPrototypes)||!n.call(Object.prototype,r))&&(t[r]=!0)}}return t}if(!t||"object"!==_typeof(t)){if(o(r)){for(var v=Object.keys(r),p=a&&a.plainObjects?{__proto__:null,0:t}:{0:t},g=0;g<v.length;g++){p[parseInt(v[g],10)+1]=r[v[g]]}return s(p,l(r)+1)}var y=[t].concat(r);if(a&&"number"==typeof a.arrayLimit&&y.length>a.arrayLimit){if(a.throwOnLimitExceeded)throw new RangeError("Array limit exceeded. Only "+a.arrayLimit+" element"+(1===a.arrayLimit?"":"s")+" allowed in an array.");return s(d(y,a),y.length-1)}return y}var m=t;if(i(t)&&!i(r)&&(m=d(t,a)),i(t)&&i(r)){if(r.forEach(function(r,i){if(n.call(t,i)){var s=t[i];s&&"object"===_typeof(s)&&r&&"object"===_typeof(r)?t[i]=e(s,r,a):t[t.length]=r}else t[i]=r}),a&&"number"==typeof a.arrayLimit&&t.length>a.arrayLimit){if(a.throwOnLimitExceeded)throw new RangeError("Array limit exceeded. Only "+a.arrayLimit+" element"+(1===a.arrayLimit?"":"s")+" allowed in an array.");return s(d(t,a),t.length-1)}return t}return Object.keys(r).reduce(function(t,i){var c=r[i];if(n.call(t,i)?h(t,i,e(t[i],c,a)):h(t,i,c),o(r)&&!o(t)&&s(t,l(r)),o(t)){var d=parseInt(i,10);String(d)===i&&d>=0&&d>l(t)&&u(t,d)}return t},m)}},utils$2}function requireStringify(){if(hasRequiredStringify)return stringify_1;hasRequiredStringify=1;var e=requireSideChannel(),t=requireUtils(),r=requireFormats(),n=Object.prototype.hasOwnProperty,i={brackets:function(e){return e+"[]"},comma:"comma",indices:function(e,t){return e+"["+t+"]"},repeat:function(e){return e}},a=Array.isArray,s=Array.prototype.push,o=function(e,t){s.apply(e,a(t)?t:[t])},l=Date.prototype.toISOString,u=r.default,c={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,commaRoundTrip:!1,delimiter:"&",depth:1/0,encode:!0,encodeDotInKeys:!1,encoder:t.encode,encodeValuesOnly:!1,filter:void 0,format:u,formatter:r.formatters[u],indices:!1,serializeDate:function(e){return l.call(e)},skipNulls:!1,strictNullHandling:!1},d={},h=function r(n,i,s,l,u,h,f,v,p,g,y,m,E,S,T,k,_,A,b,L){var R=n;if(L>b)throw new RangeError("Input depth exceeded depth option of "+b);for(var C,I=A,P=0,D=!1;void 0!==(I=I.get(d))&&!D;){var w=I.get(n);if(P+=1,void 0!==w){if(w===P)throw new RangeError("Cyclic object value");D=!0}void 0===I.get(d)&&(P=0)}if((R="function"==typeof g?g(i,R):R)instanceof Date?R=E(R):"comma"===s&&a(R)&&(R=t.maybeMap(R,function(e){return e instanceof Date?E(e):e})),null===R){if(h)return T(p&&!k?p(i,c.encoder,_,"key",S):i);R=""}if("string"==typeof(C=R)||"number"==typeof C||"boolean"==typeof C||"symbol"===_typeof(C)||"bigint"==typeof C||t.isBuffer(R))return p?[T(k?i:p(i,c.encoder,_,"key",S))+"="+T(p(R,c.encoder,_,"value",S))]:[T(i)+"="+T(String(R))];var O,x=[];if(void 0===R)return x;if("comma"===s&&a(R))k&&p&&(R=t.maybeMap(R,function(e){return null==e?e:p(e)})),O=[{value:R.length>0?R.join(",")||null:void 0}];else if(a(g))O=g;else{var M=Object.keys(R);O=y?M.sort(y):M}var F=v?String(i).replace(/\./g,"%2E"):String(i),N=l&&a(R)&&1===R.length?F+"[]":F;if(u&&a(R)&&0===R.length&&0===Object.keys(R).length)return N+"[]";for(var U=0;U<O.length;++U){var B=O[U],G="object"===_typeof(B)&&B&&void 0!==B.value?B.value:R[B];if(!f||null!==G){var H=m&&v?String(B).replace(/\./g,"%2E"):String(B),$=a(R)?"function"==typeof s?s(N,H):N:N+(m?"."+H:"["+H+"]");A.set(n,P);var K=e();K.set(d,A),o(x,r(G,$,s,l,u,h,f,v,"comma"===s&&k&&a(R)?null:p,g,y,m,E,S,T,k,_,K,b,L+1))}}return x};return stringify_1=function(t,s){var l,u=t,d=function(e){if(!e)return c;if(void 0!==e.allowEmptyArrays&&"boolean"!=typeof e.allowEmptyArrays)throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(void 0!==e.encodeDotInKeys&&"boolean"!=typeof e.encodeDotInKeys)throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(null!==e.encoder&&void 0!==e.encoder&&"function"!=typeof e.encoder)throw new TypeError("Encoder has to be a function.");var t=e.charset||c.charset;if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var s=r.default;if(void 0!==e.format){if(!n.call(r.formatters,e.format))throw new TypeError("Unknown format option provided.");s=e.format}var o,l=r.formatters[s],u=c.filter;if(("function"==typeof e.filter||a(e.filter))&&(u=e.filter),o=e.arrayFormat in i?e.arrayFormat:"indices"in e?e.indices?"indices":"repeat":c.arrayFormat,"commaRoundTrip"in e&&"boolean"!=typeof e.commaRoundTrip)throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var d=void 0===e.allowDots?!0===e.encodeDotInKeys||c.allowDots:!!e.allowDots;return{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:c.addQueryPrefix,allowDots:d,allowEmptyArrays:"boolean"==typeof e.allowEmptyArrays?!!e.allowEmptyArrays:c.allowEmptyArrays,arrayFormat:o,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:c.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:void 0===e.delimiter?c.delimiter:e.delimiter,depth:"number"==typeof e.depth?e.depth:c.depth,encode:"boolean"==typeof e.encode?e.encode:c.encode,encodeDotInKeys:"boolean"==typeof e.encodeDotInKeys?e.encodeDotInKeys:c.encodeDotInKeys,encoder:"function"==typeof e.encoder?e.encoder:c.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:c.encodeValuesOnly,filter:u,format:s,formatter:l,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:c.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:c.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:c.strictNullHandling}}(s);"function"==typeof d.filter?u=(0,d.filter)("",u):a(d.filter)&&(l=d.filter);var f=[];if("object"!==_typeof(u)||null===u)return"";var v=i[d.arrayFormat],p="comma"===v&&d.commaRoundTrip;l||(l=Object.keys(u)),d.sort&&l.sort(d.sort);for(var g=e(),y=0;y<l.length;++y){var m=l[y];if(null!=m){var E=u[m];if(!d.skipNulls||null!==E){var S=d.encodeDotInKeys?String(m).replace(/\./g,"%2E"):String(m);o(f,h(E,S,v,p,d.allowEmptyArrays,d.strictNullHandling,d.skipNulls,d.encodeDotInKeys,d.encode?d.encoder:null,d.filter,d.sort,d.allowDots,d.serializeDate,d.format,d.formatter,d.encodeValuesOnly,d.charset,g,d.depth,0))}}}var T=f.join(d.delimiter),k=!0===d.addQueryPrefix?"?":"";return d.charsetSentinel&&("iso-8859-1"===d.charset?k+="utf8=%26%2310003%3B"+d.delimiter:k+="utf8=%E2%9C%93"+d.delimiter),T.length>0?k+T:""},stringify_1}function requireParse(){if(hasRequiredParse)return parse;hasRequiredParse=1;var e=requireUtils(),t=Object.prototype.hasOwnProperty,r=Array.isArray,n={allowDots:!1,allowEmptyArrays:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decodeDotInKeys:!1,decoder:e.decode,delimiter:"&",depth:5,duplicates:"combine",ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictDepth:!1,strictMerge:!0,strictNullHandling:!1,throwOnLimitExceeded:!1},i=function(e){return e.replace(/&#(\d+);/g,function(e,t){return String.fromCharCode(parseInt(t,10))})},a=function(e,t,r){if(e&&"string"==typeof e&&t.comma&&e.indexOf(",")>-1){if(t.throwOnLimitExceeded)for(var n=0,i=e.indexOf(",");i>-1;){if((n+=1)>=t.arrayLimit)throw new RangeError("Array limit exceeded. Only "+t.arrayLimit+" element"+(1===t.arrayLimit?"":"s")+" allowed in an array.");i=e.indexOf(",",i+1)}return e.split(",")}if(t.throwOnLimitExceeded&&r>=t.arrayLimit)throw new RangeError("Array limit exceeded. Only "+t.arrayLimit+" element"+(1===t.arrayLimit?"":"s")+" allowed in an array.");return e},s=function(r,n,i,s){if(r){var o=function(e,r){var n=r.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e;if(r.depth<=0){if(!r.plainObjects&&t.call(Object.prototype,n)&&!r.allowPrototypes)return;return[n]}var i=[],a=n.indexOf("["),s=a>=0?n.slice(0,a):n;if(s){if(!r.plainObjects&&t.call(Object.prototype,s)&&!r.allowPrototypes)return;i[i.length]=s}for(var o=n.length,l=a,u=0;l>=0&&u<r.depth;){for(var c=1,d=l+1,h=-1;d<o&&h<0;){var f=n.charCodeAt(d);91===f?c+=1:93===f&&0==(c-=1)&&(h=d),d+=1}if(h<0)return i[i.length]="["+n.slice(l)+"]",i;var v=n.slice(l,h+1),p=v.slice(1,-1);if(!r.plainObjects&&t.call(Object.prototype,p)&&!r.allowPrototypes)return;i[i.length]=v,u+=1,l=n.indexOf("[",h+1)}if(l>=0){if(!0===r.strictDepth)throw new RangeError("Input depth exceeded depth option of "+r.depth+" and strictDepth is true");i[i.length]="["+n.slice(l)+"]"}return i}(r,i);if(o)return function(t,r,n,i){var s=0;if(t.length>0&&"[]"===t[t.length-1]){var o=t.slice(0,-1).join("");s=Array.isArray(r)&&r[o]?r[o].length:0}for(var l=i?r:a(r,n,s),u=t.length-1;u>=0;--u){var c,d=t[u];if("[]"===d&&n.parseArrays)c=e.isOverflow(l)?l:n.allowEmptyArrays&&(""===l||n.strictNullHandling&&null===l)?[]:e.combine([],l,n.arrayLimit,n.plainObjects,n.throwOnLimitExceeded);else{c=n.plainObjects?{__proto__:null}:{};var h="["===d.charAt(0)&&"]"===d.charAt(d.length-1)?d.slice(1,-1):d,f=n.decodeDotInKeys?h.replace(/%2E/g,"."):h,v=parseInt(f,10),p=!isNaN(v)&&d!==f&&String(v)===f&&v>=0&&n.parseArrays;if(n.parseArrays||""!==f)if(p&&v<n.arrayLimit)(c=[])[v]=l;else{if(p&&n.throwOnLimitExceeded)throw new RangeError("Array limit exceeded. Only "+n.arrayLimit+" element"+(1===n.arrayLimit?"":"s")+" allowed in an array.");p?(c[v]=l,e.markOverflow(c,v)):"__proto__"!==f&&(c[f]=l)}else c={0:l}}l=c}return l}(o,n,i,s)}};return parse=function(o,l){var u=function(t){if(!t)return n;if(void 0!==t.allowEmptyArrays&&"boolean"!=typeof t.allowEmptyArrays)throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(void 0!==t.decodeDotInKeys&&"boolean"!=typeof t.decodeDotInKeys)throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided");if(null!==t.decoder&&void 0!==t.decoder&&"function"!=typeof t.decoder)throw new TypeError("Decoder has to be a function.");if(void 0!==t.charset&&"utf-8"!==t.charset&&"iso-8859-1"!==t.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");if(void 0!==t.throwOnLimitExceeded&&"boolean"!=typeof t.throwOnLimitExceeded)throw new TypeError("`throwOnLimitExceeded` option must be a boolean");var r=void 0===t.charset?n.charset:t.charset,i=void 0===t.duplicates?n.duplicates:t.duplicates;if("combine"!==i&&"first"!==i&&"last"!==i)throw new TypeError("The duplicates option must be either combine, first, or last");return{allowDots:void 0===t.allowDots?!0===t.decodeDotInKeys||n.allowDots:!!t.allowDots,allowEmptyArrays:"boolean"==typeof t.allowEmptyArrays?!!t.allowEmptyArrays:n.allowEmptyArrays,allowPrototypes:"boolean"==typeof t.allowPrototypes?t.allowPrototypes:n.allowPrototypes,allowSparse:"boolean"==typeof t.allowSparse?t.allowSparse:n.allowSparse,arrayLimit:"number"==typeof t.arrayLimit?t.arrayLimit:n.arrayLimit,charset:r,charsetSentinel:"boolean"==typeof t.charsetSentinel?t.charsetSentinel:n.charsetSentinel,comma:"boolean"==typeof t.comma?t.comma:n.comma,decodeDotInKeys:"boolean"==typeof t.decodeDotInKeys?t.decodeDotInKeys:n.decodeDotInKeys,decoder:"function"==typeof t.decoder?t.decoder:n.decoder,delimiter:"string"==typeof t.delimiter||e.isRegExp(t.delimiter)?t.delimiter:n.delimiter,depth:"number"==typeof t.depth||!1===t.depth?+t.depth:n.depth,duplicates:i,ignoreQueryPrefix:!0===t.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof t.interpretNumericEntities?t.interpretNumericEntities:n.interpretNumericEntities,parameterLimit:"number"==typeof t.parameterLimit?t.parameterLimit:n.parameterLimit,parseArrays:!1!==t.parseArrays,plainObjects:"boolean"==typeof t.plainObjects?t.plainObjects:n.plainObjects,strictDepth:"boolean"==typeof t.strictDepth?!!t.strictDepth:n.strictDepth,strictMerge:"boolean"==typeof t.strictMerge?!!t.strictMerge:n.strictMerge,strictNullHandling:"boolean"==typeof t.strictNullHandling?t.strictNullHandling:n.strictNullHandling,throwOnLimitExceeded:"boolean"==typeof t.throwOnLimitExceeded&&t.throwOnLimitExceeded}}(l);if(""===o||null==o)return u.plainObjects?{__proto__:null}:{};for(var c="string"==typeof o?function(s,o){var l={__proto__:null},u=o.ignoreQueryPrefix?s.replace(/^\?/,""):s;u=u.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var c=o.parameterLimit===1/0?void 0:o.parameterLimit,d=u.split(o.delimiter,o.throwOnLimitExceeded&&void 0!==c?c+1:c);if(o.throwOnLimitExceeded&&void 0!==c&&d.length>c)throw new RangeError("Parameter limit exceeded. Only "+c+" parameter"+(1===c?"":"s")+" allowed.");var h,f=-1,v=o.charset;if(o.charsetSentinel)for(h=0;h<d.length;++h)0===d[h].indexOf("utf8=")&&("utf8=%E2%9C%93"===d[h]?v="utf-8":"utf8=%26%2310003%3B"===d[h]&&(v="iso-8859-1"),f=h,h=d.length);for(h=0;h<d.length;++h)if(h!==f){var p,g,y=d[h],m=y.indexOf("]="),E=-1===m?y.indexOf("="):m+1;if(-1===E?(p=o.decoder(y,n.decoder,v,"key"),g=o.strictNullHandling?null:""):null!==(p=o.decoder(y.slice(0,E),n.decoder,v,"key"))&&(g=e.maybeMap(a(y.slice(E+1),o,r(l[p])?l[p].length:0),function(e){return o.decoder(e,n.decoder,v,"value")})),g&&o.interpretNumericEntities&&"iso-8859-1"===v&&(g=i(String(g))),y.indexOf("[]=")>-1&&(g=r(g)?[g]:g),o.comma&&r(g)&&g.length>o.arrayLimit&&(g=e.combine([],g,o.arrayLimit,o.plainObjects,o.throwOnLimitExceeded)),null!==p){var S=t.call(l,p);S&&("combine"===o.duplicates||y.indexOf("[]=")>-1)?l[p]=e.combine(l[p],g,o.arrayLimit,o.plainObjects,o.throwOnLimitExceeded):S&&"last"!==o.duplicates||(l[p]=g)}}return l}(o,u):o,d=u.plainObjects?{__proto__:null}:{},h=Object.keys(c),f=0;f<h.length;++f){var v=h[f],p=s(v,c[v],u,"string"==typeof o);d=e.merge(d,p,u)}return!0===u.allowSparse?d:e.compact(d)}}function requireLib(){if(hasRequiredLib)return lib;hasRequiredLib=1;var e=requireStringify(),t=requireParse();return lib={formats:requireFormats(),parse:t,stringify:e}}var libExports=requireLib(),qs=getDefaultExportFromCjs(libExports);function bind(e,t){return function(){return e.apply(t,arguments)}}var toString=Object.prototype.toString,getPrototypeOf=Object.getPrototypeOf,iterator=Symbol.iterator,toStringTag=Symbol.toStringTag,hasOwnProperty=function(){var e=Object.prototype.hasOwnProperty;return function(t,r){return e.call(t,r)}}(),isUnsafeObjectKey=function(e){return"string"==typeof e&&("__proto__"===e||"constructor"===e||"prototype"===e)},isPrototypeBoundary=function(e,t,r){return e===Object.prototype||!r&&null===t},isSafeAndFullyMutable=function(e){if(!Object.isExtensible(e))return!1;var t=Object.getOwnPropertyNames(e);return Object.getOwnPropertySymbols&&t.push.apply(t,_toConsumableArray(Object.getOwnPropertySymbols(e))),t.every(function(t){if(isUnsafeObjectKey(t))return!1;var r=Object.getOwnPropertyDescriptor(e,t);return!!r&&r.configurable&&!0===r.writable})},hasOwnInPrototypeChain=function(e,t){for(var r=e,n=[];null!=r;){if(-1!==n.indexOf(r))return!1;n.push(r);var i=getPrototypeOf(r);if(isPrototypeBoundary(r,i,r===e))return!1;if(hasOwnProperty(r,t))return!0;r=i}return!1},getSafeProp=function(e,t){return null!=e&&hasOwnInPrototypeChain(e,t)?e[t]:void 0},toSafeFlatObject=function(e){if(null==e||"object"!==_typeof(e)&&"function"!=typeof e)return e;var t=getPrototypeOf(e);if(null===t&&isSafeAndFullyMutable(e))return e;for(var r=Object.create(null),n=Object.create(null),i=[],a=e;null!=a&&-1===i.indexOf(a);){i.push(a);var s=a===e?t:getPrototypeOf(a);if(isPrototypeBoundary(a,s,a===e))break;var o=Object.getOwnPropertyNames(a);Object.getOwnPropertySymbols&&o.push.apply(o,_toConsumableArray(Object.getOwnPropertySymbols(a)));var l,u=_createForOfIteratorHelper(o);try{for(u.s();!(l=u.n()).done;){var c=l.value;isUnsafeObjectKey(c)||(hasOwnProperty(n,c)||(r[c]=e[c],n[c]=!0))}}catch(err){u.e(err)}finally{u.f()}a=s}return r},kindOf=function(e){return function(t){var r=toString.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())}}(Object.create(null)),kindOfTest=function(e){return e=e.toLowerCase(),function(t){return kindOf(t)===e}},typeOfTest=function(e){return function(t){return _typeof(t)===e}},isArray=Array.isArray,isUndefined=typeOfTest("undefined");function isBuffer(e){return null!==e&&!isUndefined(e)&&null!==e.constructor&&!isUndefined(e.constructor)&&isFunction$1(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var isArrayBuffer=kindOfTest("ArrayBuffer");function isArrayBufferView(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&isArrayBuffer(e.buffer)}var isString=typeOfTest("string"),isFunction$1=typeOfTest("function"),isNumber=typeOfTest("number"),isObject=function(e){return null!==e&&"object"===_typeof(e)},isBoolean=function(e){return!0===e||!1===e},isPlainObject$1=function(e){if(!isObject(e))return!1;var t=getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==getPrototypeOf(t)||hasOwnInPrototypeChain(e,toStringTag)||hasOwnInPrototypeChain(e,iterator))},isEmptyObject=function(e){if(!isObject(e)||isBuffer(e))return!1;try{return 0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype}catch(t){return!1}},isDate=kindOfTest("Date"),isFile=kindOfTest("File"),isReactNativeBlob=function(e){return!(!e||void 0===e.uri)},isReactNative=function(e){return e&&void 0!==e.getParts},isBlob=kindOfTest("Blob"),isFileList=kindOfTest("FileList"),isSet=kindOfTest("Set"),isStream=function(e){return isObject(e)&&isFunction$1(e.pipe)};function getGlobal(){return"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{}}var G=getGlobal(),FormDataCtor=void 0!==G.FormData?G.FormData:void 0,isFormData=function(e){if(!e)return!1;if(FormDataCtor&&e instanceof FormDataCtor)return!0;var t=getPrototypeOf(e);if(!t||t===Object.prototype)return!1;if(!isFunction$1(e.append))return!1;var r=kindOf(e);return"formdata"===r||"object"===r&&isFunction$1(e.toString)&&"[object FormData]"===e.toString()},isURLSearchParams=kindOfTest("URLSearchParams"),_map=["ReadableStream","Request","Response","Headers"].map(kindOfTest),_map2=_slicedToArray(_map,4),isReadableStream=_map2[0],isRequest=_map2[1],isResponse=_map2[2],isHeaders=_map2[3],trim=function(e){return e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")};function forEach(e,t){var r,n,i=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).allOwnKeys,a=void 0!==i&&i;if(null!=e)if("object"!==_typeof(e)&&(e=[e]),isArray(e))for(r=0,n=e.length;r<n;r++)t.call(null,e[r],r,e);else{if(isBuffer(e))return;var s,o=a?Object.getOwnPropertyNames(e):Object.keys(e),l=o.length;for(r=0;r<l;r++)s=o[r],t.call(null,e[s],s,e)}}function findKey(e,t){if(isBuffer(e))return null;t=t.toLowerCase();for(var r,n=Object.keys(e),i=n.length;i-- >0;)if(t===(r=n[i]).toLowerCase())return r;return null}var _global="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,isContextDefined=function(e){return!isUndefined(e)&&e!==_global};function merge(){for(var e=isContextDefined(this)&&this||{},t=e.caseless,r=e.skipUndefined,n={},i=function(e,i){if("__proto__"!==i&&"constructor"!==i&&"prototype"!==i){var a=t&&"string"==typeof i&&findKey(n,i)||i,s=hasOwnProperty(n,a)?n[a]:void 0;isPlainObject$1(s)&&isPlainObject$1(e)?n[a]=merge(s,e):isPlainObject$1(e)?n[a]=merge({},e):isArray(e)?n[a]=e.slice():r&&isUndefined(e)||(n[a]=e)}},a=0,s=arguments.length;a<s;a++){var o=a<0||arguments.length<=a?void 0:arguments[a];if(o&&!isBuffer(o)&&(forEach(o,i),"object"===_typeof(o)&&!isArray(o)))for(var l=Object.getOwnPropertySymbols(o),u=0;u<l.length;u++){var c=l[u];propertyIsEnumerable.call(o,c)&&i(o[c],c)}}return n}var extend=function(e,t,r){return forEach(t,function(t,n){r&&isFunction$1(t)?Object.defineProperty(e,n,{__proto__:null,value:bind(t,r),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(e,n,{__proto__:null,value:t,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:(arguments.length>3&&void 0!==arguments[3]?arguments[3]:{}).allOwnKeys}),e},stripBOM=function(e){return 65279===e.charCodeAt(0)&&(e=e.slice(1)),e},inherits=function(e,t,r,n){e.prototype=Object.create(t.prototype,n),Object.defineProperty(e.prototype,"constructor",{__proto__:null,value:e,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(e,"super",{__proto__:null,value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject=function(e,t,r,n){var i,a,s,o={};if(t=t||{},null==e)return t;do{for(a=(i=Object.getOwnPropertyNames(e)).length;a-- >0;)s=i[a],n&&!n(s,e,t)||o[s]||(t[s]=e[s],o[s]=!0);e=!1!==r&&getPrototypeOf(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},endsWith=function(e,t,r){e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;var n=e.indexOf(t,r);return-1!==n&&n===r},toArray=function(e){if(!e)return null;if(isArray(e))return e;var t=e.length;if(!isNumber(t))return null;for(var r=new Array(t);t-- >0;)r[t]=e[t];return r},isTypedArray=function(e){return function(t){return e&&t instanceof e}}("undefined"!=typeof Uint8Array&&getPrototypeOf(Uint8Array)),forEachEntry=function(e,t){for(var r,n=(e&&e[iterator]).call(e);(r=n.next())&&!r.done;){var i=r.value;t.call(e,i[0],i[1])}},matchAll=function(e,t){for(var r,n=[];null!==(r=e.exec(t));)n.push(r);return n},isHTMLForm=kindOfTest("HTMLFormElement"),toCamelCase=function(e){return e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(e,t,r){return t.toUpperCase()+r})},propertyIsEnumerable=Object.prototype.propertyIsEnumerable,isRegExp=kindOfTest("RegExp"),reduceDescriptors=function(e,t){var r=Object.getOwnPropertyDescriptors(e),n={};forEach(r,function(r,i){var a;!1!==(a=t(r,i,e))&&(n[i]=a||r)}),Object.defineProperties(e,n)},freezeMethods=function(e){reduceDescriptors(e,function(t,r){if(isFunction$1(e)&&["arguments","caller","callee"].includes(r))return!1;var n=e[r];isFunction$1(n)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=function(){throw Error("Can not rewrite read-only method '"+r+"'")}))})},toObjectSet=function(e,t){var r={},n=function(e){e.forEach(function(e){r[e]=!0})};return isArray(e)?n(e):n(String(e).split(t)),r},noop=function(){},toFiniteNumber=function(e,t){return null!=e&&Number.isFinite(e=+e)?e:t};function isSpecCompliantForm(e){return!!(e&&isFunction$1(e.append)&&"FormData"===e[toStringTag]&&e[iterator])}var toJSONObject=function(e){var t=new WeakSet,r=function(e){if(isObject(e)){if(t.has(e))return;if(isBuffer(e))return e;if(!("toJSON"in e)){var n;if(t.add(e),isSet(e)){n=[];var i,a=_createForOfIteratorHelper(e);try{for(a.s();!(i=a.n()).done;){var s=i.value,o=r(s);!isUndefined(o)&&n.push(o)}}catch(err){a.e(err)}finally{a.f()}}else n=isArray(e)?[]:{},forEach(e,function(e,t){var i=r(e);!isUndefined(i)&&(n[t]=i)});return t.delete(e),n}}return e};return r(e)},isAsyncFn=kindOfTest("AsyncFunction"),isThenable=function(e){return e&&(isObject(e)||isFunction$1(e))&&isFunction$1(e.then)&&isFunction$1(e.catch)},_setImmediate=function(e,t){return e?setImmediate:t?(r="axios@".concat(Math.random()),n=[],_global.addEventListener("message",function(e){var t=e.source,i=e.data;t===_global&&i===r&&n.length&&n.shift()()},!1),function(e){n.push(e),_global.postMessage(r,"*")}):function(e){return setTimeout(e)};var r,n}("function"==typeof setImmediate,isFunction$1(_global.postMessage)),asap="undefined"!=typeof queueMicrotask?queueMicrotask.bind(_global):"undefined"!=typeof process&&process.nextTick||_setImmediate,isIterable=function(e){return null!=e&&isFunction$1(e[iterator])},isSafeIterable=function(e){return null!=e&&hasOwnInPrototypeChain(e,iterator)&&isIterable(e)},utils$1={isArray:isArray,isArrayBuffer:isArrayBuffer,isBuffer:isBuffer,isFormData:isFormData,isArrayBufferView:isArrayBufferView,isString:isString,isNumber:isNumber,isBoolean:isBoolean,isObject:isObject,isPlainObject:isPlainObject$1,isEmptyObject:isEmptyObject,isReadableStream:isReadableStream,isRequest:isRequest,isResponse:isResponse,isHeaders:isHeaders,isUndefined:isUndefined,isDate:isDate,isFile:isFile,isReactNativeBlob:isReactNativeBlob,isReactNative:isReactNative,isBlob:isBlob,isRegExp:isRegExp,isFunction:isFunction$1,isStream:isStream,isURLSearchParams:isURLSearchParams,isTypedArray:isTypedArray,isFileList:isFileList,forEach:forEach,merge:merge,extend:extend,trim:trim,stripBOM:stripBOM,inherits:inherits,toFlatObject:toFlatObject,kindOf:kindOf,kindOfTest:kindOfTest,endsWith:endsWith,toArray:toArray,forEachEntry:forEachEntry,matchAll:matchAll,isHTMLForm:isHTMLForm,hasOwnProperty:hasOwnProperty,hasOwnProp:hasOwnProperty,hasOwnInPrototypeChain:hasOwnInPrototypeChain,getSafeProp:getSafeProp,toSafeFlatObject:toSafeFlatObject,reduceDescriptors:reduceDescriptors,freezeMethods:freezeMethods,toObjectSet:toObjectSet,toCamelCase:toCamelCase,noop:noop,toFiniteNumber:toFiniteNumber,findKey:findKey,global:_global,isContextDefined:isContextDefined,isSpecCompliantForm:isSpecCompliantForm,toJSONObject:toJSONObject,isAsyncFn:isAsyncFn,isThenable:isThenable,setImmediate:_setImmediate,asap:asap,isIterable:isIterable,isSafeIterable:isSafeIterable},ignoreDuplicateOf=utils$1.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),parseHeaders=function(e){var t,r,n,i={};return e&&e.split("\n").forEach(function(e){n=e.indexOf(":"),t=e.substring(0,n).trim().toLowerCase(),r=e.substring(n+1).trim();var a=utils$1.hasOwnProp(i,t);!t||a&&utils$1.hasOwnProp(ignoreDuplicateOf,t)||("set-cookie"===t?a?i[t].push(r):i[t]=[r]:i[t]=a?i[t]+", "+r:r)}),i};function trimSPorHTAB(e){for(var t=0,r=e.length;t<r;){var n=e.charCodeAt(t);if(9!==n&&32!==n)break;t+=1}for(;r>t;){var i=e.charCodeAt(r-1);if(9!==i&&32!==i)break;r-=1}return 0===t&&r===e.length?e:e.slice(t,r)}var INVALID_UNICODE_HEADER_VALUE_CHARS=new RegExp("[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+","g"),INVALID_BYTE_STRING_HEADER_VALUE_CHARS=new RegExp("[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+","g");function sanitizeValue(e,t){return utils$1.isArray(e)?e.map(function(e){return sanitizeValue(e,t)}):trimSPorHTAB(String(e).replace(t,""))}var sanitizeHeaderValue=function(e){return sanitizeValue(e,INVALID_UNICODE_HEADER_VALUE_CHARS)},sanitizeByteStringHeaderValue=function(e){return sanitizeValue(e,INVALID_BYTE_STRING_HEADER_VALUE_CHARS)};function toByteStringHeaderObject(e){var t=Object.create(null);return utils$1.forEach(e.toJSON(),function(e,r){t[r]=sanitizeByteStringHeaderValue(e)}),t}var $internals$1=Symbol("internals");function normalizeHeader(e){return e&&String(e).trim().toLowerCase()}function normalizeValue(e){return!1===e||null==e?e:utils$1.isArray(e)?e.map(normalizeValue):sanitizeHeaderValue(String(e))}function parseTokens(e){for(var t,r=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;t=n.exec(e);)r[t[1]]=t[2];return r}var parameterNameRE=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function trimOWS(e){for(var t=0,r=e.length;t<r;){var n=e.charCodeAt(t);if(9!==n&&32!==n)break;t+=1}for(;r>t;){var i=e.charCodeAt(r-1);if(9!==i&&32!==i)break;r-=1}return 0===t&&r===e.length?e:e.slice(t,r)}function decodeQuotedString(e){var t=e.length-1;if(t<1||34!==e.charCodeAt(0)||34!==e.charCodeAt(t))return e;for(var r="",n=1;n<t;n++){var i=e.charCodeAt(n);if(34===i)return e;if(92===i&&(n+=1)>=t)return e;r+=e[n]}return r}function _parseParameters(e){var t=Object.create(null),r=String(e),n=0,i=!1,a=!1;function s(e){var i=trimOWS(r.slice(n,e)),a=i.indexOf("=");if(!(a<1)){var s=trimOWS(i.slice(0,a));if(parameterNameRE.test(s)){var o=s.toLowerCase();if("__proto__"!==o&&"constructor"!==o&&"prototype"!==o){var l=trimOWS(i.slice(a+1));t[o]=decodeQuotedString(l)}}}}for(var o=0;o<r.length;o++){var l=r.charCodeAt(o);i?a?a=!1:92===l?a=!0:34===l&&(i=!1):34===l?i=!0:44!==l&&59!==l||(s(o),n=o+1)}return s(r.length),t}var isValidHeaderName=function(e){return/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim())};function matchHeaderValue(e,t,r,n,i){return utils$1.isFunction(n)?n.call(this,t,r):(i&&(t=r),utils$1.isString(t)?utils$1.isString(n)?-1!==t.indexOf(n):utils$1.isRegExp(n)?n.test(t):void 0:void 0)}function formatHeader(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,function(e,t,r){return t.toUpperCase()+r})}function buildAccessors(e,t){var r=utils$1.toCamelCase(" "+t);["get","set","has"].forEach(function(n){Object.defineProperty(e,n+r,{__proto__:null,value:function(e,r,i){return this[n].call(this,t,e,r,i)},configurable:!0})})}var AxiosHeaders=function(){return _createClass(function e(t){_classCallCheck(this,e),t&&this.set(t)},[{key:"set",value:function(e,t,r){var n=this;function i(e,t,r){var i=normalizeHeader(t);if(i){var a=utils$1.findKey(n,i);(!a||void 0===n[a]||!0===r||void 0===r&&!1!==n[a])&&(n[a||t]=normalizeValue(e))}}var a=function(e,t){return utils$1.forEach(e,function(e,r){return i(e,r,t)})};if(utils$1.isPlainObject(e)||e instanceof this.constructor)a(e,t);else if(utils$1.isString(e)&&(e=e.trim())&&!isValidHeaderName(e))a(parseHeaders(e),t);else if(utils$1.isObject(e)&&utils$1.isSafeIterable(e)){var s,o,l,u=Object.create(null),c=_createForOfIteratorHelper(e);try{for(c.s();!(l=c.n()).done;){var d=l.value;if(!utils$1.isArray(d))throw new TypeError("Object iterator must return a key-value pair");o=d[0],utils$1.hasOwnProp(u,o)?(s=u[o],u[o]=utils$1.isArray(s)?[].concat(_toConsumableArray(s),[d[1]]):[s,d[1]]):u[o]=d[1]}}catch(err){c.e(err)}finally{c.f()}a(u,t)}else null!=e&&i(t,e,r);return this}},{key:"get",value:function(e,t){if(e=normalizeHeader(e)){var r=utils$1.findKey(this,e);if(r){var n=this[r];if(!t)return n;if(!0===t)return parseTokens(n);if(utils$1.isFunction(t))return t.call(this,n,r);if(utils$1.isRegExp(t))return t.exec(n);throw new TypeError("parser must be boolean|regexp|function")}}}},{key:"has",value:function(e,t){if(e=normalizeHeader(e)){var r=utils$1.findKey(this,e);return!(!r||void 0===this[r]||t&&!matchHeaderValue(this,this[r],r,t))}return!1}},{key:"delete",value:function(e,t){var r=this,n=!1;function i(e){if(e=normalizeHeader(e)){var i=utils$1.findKey(r,e);!i||t&&!matchHeaderValue(r,r[i],i,t)||(delete r[i],n=!0)}}return utils$1.isArray(e)?e.forEach(i):i(e),n}},{key:"clear",value:function(e){for(var t=Object.keys(this),r=t.length,n=!1;r--;){var i=t[r];e&&!matchHeaderValue(this,this[i],i,e,!0)||(delete this[i],n=!0)}return n}},{key:"normalize",value:function(e){var t=this,r={};return utils$1.forEach(this,function(n,i){var a=utils$1.findKey(r,i);if(a)return t[a]=normalizeValue(n),void delete t[i];var s=e?formatHeader(i):String(i).trim();s!==i&&delete t[i],t[s]=normalizeValue(n),r[s]=!0}),this}},{key:"concat",value:function(){for(var e,t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];return(e=this.constructor).concat.apply(e,[this].concat(r))}},{key:"toJSON",value:function(e){var t=Object.create(null);return utils$1.forEach(this,function(r,n){null!=r&&!1!==r&&(t[n]=e&&utils$1.isArray(r)?r.join(", "):r)}),t}},{key:Symbol.iterator,value:function(){return Object.entries(this.toJSON())[Symbol.iterator]()}},{key:"toString",value:function(){return Object.entries(this.toJSON()).map(function(e){var t=_slicedToArray(e,2);return t[0]+": "+t[1]}).join("\n")}},{key:"getSetCookie",value:function(){var e=this.get("set-cookie");return utils$1.isArray(e)?e:null==e||!1===e?[]:[e]}},{key:Symbol.toStringTag,get:function(){return"AxiosHeaders"}}],[{key:"from",value:function(e){return e instanceof this?e:new this(e)}},{key:"parseParameters",value:function(e){return _parseParameters(e)}},{key:"concat",value:function(e){for(var t=new this(e),r=arguments.length,n=new Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];return n.forEach(function(e){return t.set(e)}),t}},{key:"accessor",value:function(e){var t=(this[$internals$1]=this[$internals$1]={accessors:{}}).accessors,r=this.prototype;function n(e){var n=normalizeHeader(e);t[n]||(buildAccessors(r,e),t[n]=!0)}return utils$1.isArray(e)?e.forEach(n):n(e),this}}])}();AxiosHeaders.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),utils$1.reduceDescriptors(AxiosHeaders.prototype,function(e,t){var r=e.value,n=t[0].toUpperCase()+t.slice(1);return{get:function(){return r},set:function(e){this[n]=e}}}),utils$1.freezeMethods(AxiosHeaders);var REDACTED="[REDACTED ****]";function hasOwnOrPrototypeToJSON(e){if(utils$1.hasOwnProp(e,"toJSON"))return!0;for(var t=Object.getPrototypeOf(e);t&&t!==Object.prototype;){if(utils$1.hasOwnProp(t,"toJSON"))return!0;t=Object.getPrototypeOf(t)}return!1}function redactConfig(e,t){var r=new Set(t.map(function(e){return String(e).toLowerCase()})),n=[],i=function(e){if(null===e||"object"!==_typeof(e))return e;if(utils$1.isBuffer(e))return e;if(-1===n.indexOf(e)){var t;if(e instanceof AxiosHeaders&&(e=e.toJSON()),n.push(e),utils$1.isArray(e))t=[],e.forEach(function(e,r){var n=i(e);utils$1.isUndefined(n)||(t[r]=n)});else{if(!utils$1.isPlainObject(e)&&hasOwnOrPrototypeToJSON(e))return n.pop(),e;t=Object.create(null);for(var a=0,s=Object.entries(e);a<s.length;a++){var o=_slicedToArray(s[a],2),l=o[0],u=o[1],c=r.has(l.toLowerCase())?REDACTED:i(u);utils$1.isUndefined(c)||(t[l]=c)}}return n.pop(),t}};return i(e)}function stringifySafely$1(e){try{return String(e)}catch(err){return""}}function aggregateErrorMessage(e){return e.errors.map(function(e){try{return e&&e.message?stringifySafely$1(e.message):stringifySafely$1(e)}catch(err){return""}}).filter(Boolean).join("; ")||e.name||"AggregateError"}var AxiosError=function(){function e(t,r,n,i,a){var s;return _classCallCheck(this,e),s=_callSuper(this,e,[t]),Object.defineProperty(s,"message",{__proto__:null,value:t,enumerable:!0,writable:!0,configurable:!0}),s.name="AxiosError",s.isAxiosError=!0,r&&(s.code=r),n&&(s.config=n),i&&(s.request=i),a&&(s.response=a,s.status=a.status),s}return _inherits(e,_wrapNativeSuper(Error)),_createClass(e,[{key:"toJSON",value:function(){var e=this.config,t=e&&utils$1.hasOwnProp(e,"redact")?e.redact:void 0,r=utils$1.isArray(t)&&t.length>0?redactConfig(e,t):utils$1.toJSONObject(e);return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:r,code:this.code,status:this.status}}}],[{key:"from",value:function(t,r,n,i,a,s){var o=t.message;!o&&utils$1.isArray(t.errors)&&t.errors.length&&(o=aggregateErrorMessage(t));var l=new e(o,r||t.code,n,i,a);return Object.defineProperty(l,"cause",{__proto__:null,value:t,writable:!0,enumerable:!1,configurable:!0}),l.name=t.name,null!=t.status&&null==l.status&&(l.status=t.status),s&&Object.assign(l,s),l}}])}();AxiosError.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE",AxiosError.ERR_BAD_OPTION="ERR_BAD_OPTION",AxiosError.ECONNABORTED="ECONNABORTED",AxiosError.ETIMEDOUT="ETIMEDOUT",AxiosError.ECONNREFUSED="ECONNREFUSED",AxiosError.ERR_NETWORK="ERR_NETWORK",AxiosError.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS",AxiosError.ERR_DEPRECATED="ERR_DEPRECATED",AxiosError.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE",AxiosError.ERR_BAD_REQUEST="ERR_BAD_REQUEST",AxiosError.ERR_CANCELED="ERR_CANCELED",AxiosError.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT",AxiosError.ERR_INVALID_URL="ERR_INVALID_URL",AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED="ERR_FORM_DATA_DEPTH_EXCEEDED";var httpAdapter=null,DEFAULT_FORM_DATA_MAX_DEPTH=100;function isVisitable(e){return utils$1.isPlainObject(e)||utils$1.isArray(e)}function removeBrackets(e){return utils$1.endsWith(e,"[]")?e.slice(0,-2):e}function renderKey(e,t,r){return e?e.concat(t).map(function(e,t){return e=removeBrackets(e),!r&&t?"["+e+"]":e}).join(r?".":""):t}function isFlatArray(e){return utils$1.isArray(e)&&!e.some(isVisitable)}var predicates=utils$1.toFlatObject(utils$1,{},null,function(e){return/^is[A-Z]/.test(e)});function toFormData(e,t,r){if(!utils$1.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;var n=function(e,t){var n=utils$1.getSafeProp(r,e);return utils$1.isUndefined(n)?t:n},i=n("metaTokens",!0),a=n("visitor")||v,s=n("dots",!1),o=n("indexes",!1),l=n("Blob")||"undefined"!=typeof Blob&&Blob,u=n("maxDepth",DEFAULT_FORM_DATA_MAX_DEPTH),c=l&&utils$1.isSpecCompliantForm(t),d=[];if(!utils$1.isFunction(a))throw new TypeError("visitor must be a function");function h(e){if(null===e)return"";if(utils$1.isDate(e))return e.toISOString();if(utils$1.isBoolean(e))return e.toString();if(!c&&utils$1.isBlob(e))throw new AxiosError("Blob is not supported. Use a Buffer instead.");if(utils$1.isArrayBuffer(e)||utils$1.isTypedArray(e)){if(c&&"function"==typeof l)return new l([e]);throw new AxiosError("Blob is not supported. Use a Buffer instead.",AxiosError.ERR_NOT_SUPPORT)}return e}function f(e){if(e>u)throw new AxiosError("Object is too deeply nested ("+e+" levels). Max depth: "+u,AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED)}function v(e,r,n){var a=e;if(utils$1.isReactNative(t)&&utils$1.isReactNativeBlob(e))return t.append(renderKey(n,r,s),h(e)),!1;if(e&&!n&&"object"===_typeof(e))if(utils$1.endsWith(r,"{}"))r=i?r:r.slice(0,-2),e=function(e,t){if(u===1/0)return JSON.stringify(e);var r=[];return JSON.stringify(e,function(e,n){if(!utils$1.isObject(n))return n;for(;r.length&&r[r.length-1]!==this;)r.pop();return r.push(n),f(t+r.length-1),n})}(e,1);else if(utils$1.isArray(e)&&isFlatArray(e)||(utils$1.isFileList(e)||utils$1.endsWith(r,"[]"))&&(a=utils$1.toArray(e)))return r=removeBrackets(r),a.forEach(function(e,n){!utils$1.isUndefined(e)&&null!==e&&t.append(!0===o?renderKey([r],n,s):null===o?r:r+"[]",h(e))}),!1;return!!isVisitable(e)||(t.append(renderKey(n,r,s),h(e)),!1)}var p=Object.assign(predicates,{defaultVisitor:v,convertValue:h,isVisitable:isVisitable});if(!utils$1.isObject(e))throw new TypeError("data must be an object");return function e(r,n){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;if(!utils$1.isUndefined(r)){if(f(i),-1!==d.indexOf(r))throw new Error("Circular reference detected in "+n.join("."));d.push(r),utils$1.forEach(r,function(r,s){!0===(!(utils$1.isUndefined(r)||null===r)&&a.call(t,r,utils$1.isString(s)?s.trim():s,n,p))&&e(r,n?n.concat(s):[s],i+1)}),d.pop()}}(e),t}function encode$1(e){var t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"};return encodeURIComponent(e).replace(/[!'()~]|%20/g,function(e){return t[e]})}function AxiosURLSearchParams(e,t){this._pairs=[],e&&toFormData(e,this,t)}var prototype=AxiosURLSearchParams.prototype;function encode(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function buildURL(e,t,r){if(!t)return e;e=e||"";var n,i=utils$1.isFunction(r)?{serialize:r}:r,a=utils$1.getSafeProp(i,"encode")||encode,s=utils$1.getSafeProp(i,"serialize");if(n=s?s(t,i):utils$1.isURLSearchParams(t)?t.toString():new AxiosURLSearchParams(t,i).toString(a)){var o=e.indexOf("#");-1!==o&&(e=e.slice(0,o)),e+=(-1===e.indexOf("?")?"?":"&")+n}return e}prototype.append=function(e,t){this._pairs.push([e,t])},prototype.toString=function(e){var t=this,r=e?function(r){return e.call(t,r,encode$1)}:encode$1;return this._pairs.map(function(e){return r(e[0])+"="+r(e[1])},"").join("&")};var $internals=Symbol("internals");function countHandlers(e){return e?e.length:0}function trimHandlers(e){if(e)for(;e.length&&null===e[e.length-1];)e.pop()}function syncHandlerEntries(e,t){var r=e.handlers,n=countHandlers(r);r!==t.handlersRef?(t.handlersRef=r,t.handlerEntries.clear()):n!==t.handlersLength&&(n?t.handlerEntries.forEach(function(e,n){r[e.index]!==e.handler&&t.handlerEntries.delete(n)}):t.handlerEntries.clear()),t.handlersLength=n}var InterceptorManager=function(){return _createClass(function e(){_classCallCheck(this,e),this.handlers=[],this[$internals]={handlersRef:this.handlers,handlersLength:this.handlers.length,handlerEntries:new Map,iterationDepth:0,nextId:0}},[{key:"use",value:function(e,t,r){var n={fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null},i=this[$internals];null==this.handlers&&(this.handlers=[]),syncHandlerEntries(this,i);var a=i.nextId++;return this.handlers.push(n),i.handlerEntries.set(a,{handler:n,index:this.handlers.length-1}),i.handlersLength=this.handlers.length,a}},{key:"eject",value:function(e){var t=this[$internals];syncHandlerEntries(this,t);var r=t.handlerEntries.get(e);if(r){if(t.handlerEntries.delete(e),this.handlers[r.index]!==r.handler)return;this.handlers[r.index]=null,t.iterationDepth||(trimHandlers(this.handlers),t.handlersLength=this.handlers.length)}}},{key:"clear",value:function(){this.handlers&&(this.handlers=[],syncHandlerEntries(this,this[$internals]))}},{key:"forEach",value:function(e){var t=this[$internals];syncHandlerEntries(this,t),t.iterationDepth++;try{utils$1.forEach(this.handlers,function(t){null!==t&&e(t)})}finally{--t.iterationDepth||(syncHandlerEntries(this,t),trimHandlers(this.handlers),t.handlersLength=countHandlers(this.handlers))}}}])}(),transitionalDefaults={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0,advertiseZstdAcceptEncoding:!1,validateStatusUndefinedResolves:!0},URLSearchParams$1="undefined"!=typeof URLSearchParams?URLSearchParams:AxiosURLSearchParams,FormData$1="undefined"!=typeof FormData?FormData:null,Blob$1="undefined"!=typeof Blob?Blob:null,platform$1={isBrowser:!0,classes:{URLSearchParams:URLSearchParams$1,FormData:FormData$1,Blob:Blob$1},protocols:["http","https","file","blob","url","data"]},hasBrowserEnv="undefined"!=typeof window&&"undefined"!=typeof document,_navigator="object"===("undefined"==typeof navigator?"undefined":_typeof(navigator))&&navigator||void 0,hasStandardBrowserEnv=hasBrowserEnv&&(!_navigator||["ReactNative","NativeScript","NS"].indexOf(_navigator.product)<0),hasStandardBrowserWebWorkerEnv="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,origin=hasBrowserEnv&&window.location.href||"http://localhost",utils=Object.freeze({__proto__:null,hasBrowserEnv:hasBrowserEnv,hasStandardBrowserEnv:hasStandardBrowserEnv,hasStandardBrowserWebWorkerEnv:hasStandardBrowserWebWorkerEnv,navigator:_navigator,origin:origin}),platform=_objectSpread2$1(_objectSpread2$1({},utils),platform$1);function toURLEncodedForm(e,t){return toFormData(e,new platform.classes.URLSearchParams,_objectSpread2$1({visitor:function(e,t,r,n){return platform.isNode&&utils$1.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)}},t))}var MAX_DEPTH=DEFAULT_FORM_DATA_MAX_DEPTH;function throwIfDepthExceeded(e){if(e>MAX_DEPTH)throw new AxiosError("FormData field is too deeply nested ("+e+" levels). Max depth: "+MAX_DEPTH,AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED)}function parsePropPath(e){for(var t,r=[],n=/[^.[\]]+|\[([^.[\]]*)]/g;null!==(t=n.exec(e));)throwIfDepthExceeded(r.length),r.push("[]"===t[0]?"":t[1]||t[0]);return r}function arrayToObject(e){var t,r,n={},i=Object.keys(e),a=i.length;for(t=0;t<a;t++)n[r=i[t]]=e[r];return n}function formDataToJSON(e){function t(e,r,n,i){throwIfDepthExceeded(i);var a=e[i++];if("__proto__"===a)return!0;var s=Number.isFinite(+a),o=i>=e.length;return a=!a&&utils$1.isArray(n)?n.length:a,o?(utils$1.hasOwnProp(n,a)?n[a]=utils$1.isArray(n[a])?n[a].concat(r):[n[a],r]:n[a]=r,!s):(utils$1.hasOwnProp(n,a)&&utils$1.isObject(n[a])||(n[a]=[]),t(e,r,n[a],i)&&utils$1.isArray(n[a])&&(n[a]=arrayToObject(n[a])),!s)}if(utils$1.isFormData(e)&&utils$1.isFunction(e.entries)){var r={};return utils$1.forEachEntry(e,function(e,n){t(parsePropPath(e),n,r,0)}),r}return null}var methodList=Object.freeze(["get","delete","head","options","post","put","patch","purge","link","unlink","query"]),own=function(e,t){return null!=e&&utils$1.hasOwnProp(e,t)?e[t]:void 0};function stringifySafely(e,t,r){if(utils$1.isString(e))try{return(t||JSON.parse)(e),utils$1.trim(e)}catch(n){if("SyntaxError"!==n.name)throw n}return(r||JSON.stringify)(e)}var defaults={transitional:transitionalDefaults,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){var r,n=t.getContentType()||"",i=n.indexOf("application/json")>-1,a=utils$1.isObject(e);if(a&&utils$1.isHTMLForm(e)&&(e=new FormData(e)),utils$1.isFormData(e))return i?JSON.stringify(formDataToJSON(e)):e;if(utils$1.isArrayBuffer(e)||utils$1.isBuffer(e)||utils$1.isStream(e)||utils$1.isFile(e)||utils$1.isBlob(e)||utils$1.isReadableStream(e))return e;if(utils$1.isArrayBufferView(e))return e.buffer;if(utils$1.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();if(a){var s=own(this,"formSerializer");if(n.indexOf("application/x-www-form-urlencoded")>-1)return toURLEncodedForm(e,s).toString();if((r=utils$1.isFileList(e))||n.indexOf("multipart/form-data")>-1){var o=own(this,"env"),l=o&&o.FormData;return toFormData(r?{"files[]":e}:e,l&&new l,s)}}return a||i?(t.setContentType("application/json",!1),stringifySafely(e)):e}],transformResponse:[function(e){var t=own(this,"transitional")||defaults.transitional,r=t&&t.forcedJSONParsing,n=own(this,"responseType"),i="json"===n;if(utils$1.isResponse(e)||utils$1.isReadableStream(e))return e;if(e&&utils$1.isString(e)&&(r&&!n||i)){var a=!(t&&t.silentJSONParsing)&&i;try{return JSON.parse(e,own(this,"parseReviver"))}catch(s){if(a){if("SyntaxError"===s.name)throw AxiosError.from(s,AxiosError.ERR_BAD_RESPONSE,this,null,own(this,"response"));throw s}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:platform.classes.FormData,Blob:platform.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};function transformData(e,t){var r=this||defaults,n=t||r,i=AxiosHeaders.from(n.headers),a=n.data;return utils$1.forEach(e,function(e){a=e.call(r,a,i.normalize(),t?t.status:void 0)}),i.normalize(),a}function isCancel(e){return!(!e||!e.__CANCEL__)}utils$1.forEach(methodList,function(e){defaults.headers[e]={}});var CanceledError=function(){function e(t,r,n){var i;return _classCallCheck(this,e),(i=_callSuper(this,e,[null==t?"canceled":t,AxiosError.ERR_CANCELED,r,n])).name="CanceledError",i.__CANCEL__=!0,i}return _inherits(e,AxiosError),_createClass(e)}();function settle(e,t,r){var n=r.config.validateStatus;r.status&&n&&!n(r.status)?t(new AxiosError("Request failed with status code "+r.status,r.status>=400&&r.status<500?AxiosError.ERR_BAD_REQUEST:AxiosError.ERR_BAD_RESPONSE,r.config,r.request,r)):e(r)}var urlParserControlCharacters=/[\t\n\r]/g;function normalizeURLForProtocolCheck(e){if("string"!=typeof e)return e;for(var t=0;t<e.length&&e.charCodeAt(t)<=32;)t++;return e.slice(t).replace(urlParserControlCharacters,"")}function parseProtocol(e){var t=/^([-+\w]{1,25}):(?:\/\/)?/.exec(e);return t&&t[1]||""}function speedometer(e,t){e=e||10;var r,n=new Array(e),i=new Array(e),a=0,s=0;return t=void 0!==t?t:1e3,function(o){var l=Date.now(),u=i[s];r||(r=l),n[a]=o,i[a]=l;for(var c=s,d=0;c!==a;)d+=n[c++],c%=e;if((a=(a+1)%e)===s&&(s=(s+1)%e),!(l-r<t)){var h=u&&l-u;return h?Math.round(1e3*d/h):void 0}}}function throttle(e,t){var r,n,i=0,a=1e3/t,s=function(t){var a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Date.now();i=a,r=null,n&&(clearTimeout(n),n=null),e.apply(void 0,_toConsumableArray(t))};return[function(){for(var e=Date.now(),t=e-i,o=arguments.length,l=new Array(o),u=0;u<o;u++)l[u]=arguments[u];t>=a?s(l,e):(r=l,n||(n=setTimeout(function(){n=null,s(r)},a-t)))},function(){return r&&s(r)},function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return s(t)}]}var progressEventReducer=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:3,n=0,i=speedometer(50,250);return throttle(function(r){if(r&&utils$1.isNumber(r.loaded)){var a=r.loaded,s=r.lengthComputable?r.total:void 0,o=Math.max(0,null!=s?Math.min(a,s):a),l=Math.max(0,o-n),u=i(l);n=Math.max(n,o);var c=_defineProperty$1({loaded:o,total:s,progress:s?o/s:void 0,bytes:l,rate:u||void 0,estimated:u&&s?(s-o)/u:void 0,event:r,lengthComputable:null!=s},t?"download":"upload",!0);e(c)}},r)},progressEventDecorator=function(e,t){var r=null!=e;return[function(n){return t[0]({lengthComputable:r,total:e,loaded:n})},t[1]]},asyncDecorator=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:utils$1.asap;return function(){for(var r=arguments.length,n=new Array(r),i=0;i<r;i++)n[i]=arguments[i];return t(function(){return e.apply(void 0,n)})}},isURLSameOrigin=platform.hasStandardBrowserEnv?function(e,t){return function(r){return r=new URL(r,platform.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)}}(new URL(platform.origin),platform.navigator&&/(msie|trident)/i.test(platform.navigator.userAgent)):function(){return!0},cookies=platform.hasStandardBrowserEnv?{write:function(e,t,r,n,i,a,s){if("undefined"!=typeof document){var o=["".concat(e,"=").concat(encodeURIComponent(t))];utils$1.isNumber(r)&&o.push("expires=".concat(new Date(r).toUTCString())),utils$1.isString(n)&&o.push("path=".concat(n)),utils$1.isString(i)&&o.push("domain=".concat(i)),!0===a&&o.push("secure"),utils$1.isString(s)&&o.push("SameSite=".concat(s)),document.cookie=o.join("; ")}},read:function(e){if("undefined"==typeof document)return null;for(var t=document.cookie.split(";"),r=0;r<t.length;r++){var n=t[r].replace(/^\s+/,""),i=n.indexOf("=");if(-1!==i&&n.slice(0,i)===e)try{return decodeURIComponent(n.slice(i+1))}catch(a){return n.slice(i+1)}}return null},remove:function(e){this.write(e,"",Date.now()-864e5,"/")}}:{write:function(){},read:function(){return null},remove:function(){}};function isAbsoluteURL(e){return"string"==typeof e&&/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function combineURLs(e,t){if(!t)return e;for(var r=e.length;r>0&&47===e.charCodeAt(r-1);)r--;return e.slice(0,r)+"/"+t.replace(/^\/+/,"")}var malformedHttpProtocol=/^https?:(?!\/\/)/i;function redactFragment(e){return e?e.replace(/(^|&)([^=&]*=)?[^&]+/g,function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";return"".concat(t).concat(r).concat(REDACTED)}):e}function redactSensitiveURLParts(e){var t=e.replace(/^(https?:\/{0,2})[^/?#]*@/i,"$1".concat(REDACTED,"@")),r=t.indexOf("#"),n=(-1===r?t:t.slice(0,r)).replace(/([?&][^=&#]*=)[^&#]*/g,"$1".concat(REDACTED));return-1===r?n:"".concat(n,"#").concat(redactFragment(t.slice(r+1)))}function assertValidHttpProtocolURL(e,t){if("string"==typeof e){var r=normalizeURLForProtocolCheck(e);if(malformedHttpProtocol.test(r))throw new AxiosError("Invalid URL ".concat(JSON.stringify(redactSensitiveURLParts(r)),': missing "//" after protocol'),AxiosError.ERR_INVALID_URL,t)}}function buildFullPath(e,t,r,n){assertValidHttpProtocolURL(t,n);var i=!isAbsoluteURL(t);return e&&(i||!1===r)?(assertValidHttpProtocolURL(e,n),combineURLs(e,t)):t}var headersToObject=function(e){return e instanceof AxiosHeaders?_objectSpread2$1({},e):e},ownEnumerableKeys=function(e){return Object.getOwnPropertySymbols&&Object.getOwnPropertyDescriptor?Object.keys(e).concat(Object.getOwnPropertySymbols(e).filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})):Object.keys(e)};function mergeConfig(e,t){e=e||{},t=t||{};var r=Object.create(null);function n(e,t,r,n){return utils$1.isPlainObject(e)&&utils$1.isPlainObject(t)?utils$1.merge.call({caseless:n},e,t):utils$1.isPlainObject(t)?utils$1.merge({},t):utils$1.isArray(t)?t.slice():t}function i(e,t,r,i){return utils$1.isUndefined(t)?utils$1.isUndefined(e)?void 0:n(void 0,e,0,i):n(e,t,0,i)}function a(e,t){if(!utils$1.isUndefined(t))return n(void 0,t)}function s(e,t){return utils$1.isUndefined(t)?utils$1.isUndefined(e)?void 0:n(void 0,e):n(void 0,t)}function o(r,i,a){return utils$1.hasOwnProp(t,a)?n(r,i):utils$1.hasOwnProp(e,a)?n(void 0,r):void 0}Object.defineProperty(r,"hasOwnProperty",{__proto__:null,value:Object.prototype.hasOwnProperty,enumerable:!1,writable:!0,configurable:!0});var l={url:a,method:a,data:a,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutErrorMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,allowedSocketPaths:s,responseEncoding:s,validateStatus:o,headers:function(e,t,r){return i(headersToObject(e),headersToObject(t),0,!0)}};return utils$1.forEach(ownEnumerableKeys(_objectSpread2$1(_objectSpread2$1({},e),t)),function(n){if("__proto__"!==n&&"constructor"!==n&&"prototype"!==n){var a=utils$1.hasOwnProp(l,n)?l[n]:i,s=a(utils$1.hasOwnProp(e,n)?e[n]:void 0,utils$1.hasOwnProp(t,n)?t[n]:void 0,n);utils$1.isUndefined(s)&&a!==o||(r[n]=s)}}),utils$1.hasOwnProp(t,"validateStatus")&&utils$1.isUndefined(t.validateStatus)&&!1===function(r){var n=utils$1.hasOwnProp(t,"transitional")?t.transitional:void 0;if(!utils$1.isUndefined(n)){if(!utils$1.isPlainObject(n))return;if(utils$1.hasOwnProp(n,r))return n[r]}var i=utils$1.hasOwnProp(e,"transitional")?e.transitional:void 0;if(utils$1.isPlainObject(i)&&utils$1.hasOwnProp(i,r))return i[r]}("validateStatusUndefinedResolves")&&(utils$1.hasOwnProp(e,"validateStatus")?r.validateStatus=n(void 0,e.validateStatus):delete r.validateStatus),r}var FORM_DATA_CONTENT_HEADERS=["content-type","content-length"];function setFormDataHeaders(e,t,r){"content-only"===r?Object.entries(t||{}).forEach(function(t){var r=_slicedToArray(t,2),n=r[0],i=r[1];FORM_DATA_CONTENT_HEADERS.includes(n.toLowerCase())&&e.set(n,i)}):e.set(t)}var encodeUTF8$1=function(e){return encodeURIComponent(e).replace(/%([0-9A-F]{2})/gi,function(e,t){return String.fromCharCode(parseInt(t,16))})};function resolveConfig(e){var t=mergeConfig({},e),r=function(e){return utils$1.hasOwnProp(t,e)?t[e]:void 0},n=r("data"),i=r("withXSRFToken"),a=r("xsrfHeaderName"),s=r("xsrfCookieName"),o=r("headers"),l=r("auth"),u=r("baseURL"),c=r("allowAbsoluteUrls"),d=r("url");if(t.headers=o=AxiosHeaders.from(o),t.url=buildURL(buildFullPath(u,d,c,t),r("params"),r("paramsSerializer")),l){var h=utils$1.getSafeProp(l,"username")||"",f=utils$1.getSafeProp(l,"password")||"";try{o.set("Authorization","Basic "+btoa(h+":"+(f?encodeUTF8$1(f):"")))}catch(g){throw AxiosError.from(g,AxiosError.ERR_BAD_OPTION_VALUE,e)}}if(utils$1.isFormData(n)){var v=utils$1.getSafeProp(n,"getHeaders");platform.hasStandardBrowserEnv||platform.hasStandardBrowserWebWorkerEnv||utils$1.isReactNative(n)?o.setContentType(void 0):utils$1.isFunction(v)&&setFormDataHeaders(o,v.call(n),r("formDataHeaderPolicy"))}if(platform.hasStandardBrowserEnv&&(utils$1.isFunction(i)&&(i=i(t)),!0===i||null==i&&isURLSameOrigin(t.url))){var p=a&&s&&cookies.read(s);p&&o.set(a,p)}return t}var isXHRAdapterSupported="undefined"!=typeof XMLHttpRequest,xhrAdapter=isXHRAdapterSupported&&function(e){return new Promise(function(t,r){var n,i,a,s,o,l,u=resolveConfig(e),c=u.data,d=AxiosHeaders.from(u.headers).normalize(),h=u.responseType,f=u.onUploadProgress,v=u.onDownloadProgress;function p(){s&&s(),o&&o(),u.cancelToken&&u.cancelToken.unsubscribe(n),u.signal&&u.signal.removeEventListener("abort",n)}var g=new XMLHttpRequest;function y(n){if(g){if(!(0!==g.status||"file"===(parseProtocol(normalizeURLForProtocolCheck(u.url))||parseProtocol(platform.origin))||g.responseURL&&g.responseURL.startsWith("file:")))return r(new AxiosError("Request aborted",AxiosError.ECONNABORTED,e,g)),p(),void(g=null);try{n?l&&l(n):o&&o()}catch(err){setTimeout(function(){throw err})}if(g){var i=AxiosHeaders.from("getAllResponseHeaders"in g&&g.getAllResponseHeaders());settle(function(e){t(e),p()},function(e){r(e),p()},{data:h&&"text"!==h&&"json"!==h?g.response:g.responseText,status:g.status,statusText:g.statusText,headers:i,config:e,request:g}),g=null}}}if(g.open(u.method.toUpperCase(),u.url,!0),g.timeout=u.timeout,"onloadend"in g?g.onloadend=y:g.onreadystatechange=function(){g&&4===g.readyState&&(0!==g.status||g.responseURL&&g.responseURL.startsWith("file:"))&&setTimeout(y)},g.onabort=function(){g&&(r(new AxiosError("Request aborted",AxiosError.ECONNABORTED,e,g)),p(),g=null)},g.onerror=function(t){var n=t&&t.message?t.message:"Network Error",i=new AxiosError(n,AxiosError.ERR_NETWORK,e,g);i.event=t||null,r(i),p(),g=null},g.ontimeout=function(){var t=u.timeout?"timeout of "+u.timeout+"ms exceeded":"timeout exceeded",n=u.transitional||transitionalDefaults;u.timeoutErrorMessage&&(t=u.timeoutErrorMessage),r(new AxiosError(t,n.clarifyTimeoutError?AxiosError.ETIMEDOUT:AxiosError.ECONNABORTED,e,g)),p(),g=null},void 0===c&&d.setContentType(null),"setRequestHeader"in g&&utils$1.forEach(toByteStringHeaderObject(d),function(e,t){g.setRequestHeader(t,e)}),utils$1.isUndefined(u.withCredentials)||(g.withCredentials=!!u.withCredentials),h&&"json"!==h&&(g.responseType=u.responseType),v){var m=_slicedToArray(progressEventReducer(v,!0),3);a=m[0],o=m[1],l=m[2],g.addEventListener("progress",a)}if(f&&g.upload){var E=_slicedToArray(progressEventReducer(f),2);i=E[0],s=E[1],g.upload.addEventListener("progress",i),g.upload.addEventListener("loadend",s)}(u.cancelToken||u.signal)&&(n=function(t){g&&(r(!t||t.type?new CanceledError(null,e,g):t),g.abort(),p(),g=null)},u.cancelToken&&u.cancelToken.subscribe(n),u.signal&&(u.signal.aborted?n():u.signal.addEventListener("abort",n)));var S=parseProtocol(u.url);if(S&&!platform.protocols.includes(S))return r(new AxiosError("Unsupported protocol "+S+":",AxiosError.ERR_BAD_REQUEST,e)),void p();g.send(c||null)})},composeSignals=function(e,t){if(e=e?e.filter(Boolean):[],t||e.length){var r=new AbortController,n=!1,i=function(e){if(!n){n=!0,s();var t=e instanceof Error?e:this.reason;r.abort(t instanceof AxiosError?t:new CanceledError(t instanceof Error?t.message:t))}},a=t&&setTimeout(function(){a=null,i(new AxiosError("timeout of ".concat(t,"ms exceeded"),AxiosError.ETIMEDOUT))},t),s=function(){e&&(a&&clearTimeout(a),a=null,e.forEach(function(e){e.unsubscribe?e.unsubscribe(i):e.removeEventListener("abort",i)}),e=null)};e.forEach(function(e){n||(e.aborted?i.call(e):e.addEventListener("abort",i,{once:!0}))});var o=r.signal;return o.unsubscribe=function(){return utils$1.asap(s)},o}},streamChunk=_regenerator().m(function e(t,r){var n,i,a;return _regenerator().w(function(e){for(;;)switch(e.n){case 0:if(n=t.byteLength,r&&!(n<r)){e.n=2;break}return e.n=1,t;case 1:return e.a(2);case 2:i=0;case 3:if(!(i<n)){e.n=5;break}return a=i+r,e.n=4,t.slice(i,a);case 4:i=a,e.n=3;break;case 5:return e.a(2)}},e)}),readBytes=function(){var e=_wrapAsyncGenerator(_regenerator().m(function e(t,r){var n,i,a,s,o,l,u;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:n=!1,i=!1,e.p=1,s=_asyncIterator(readStream(t));case 2:return e.n=3,_awaitAsyncGenerator(s.next());case 3:if(!(n=!(o=e.v).done)){e.n=5;break}return l=o.value,e.d(_regeneratorValues(_asyncGeneratorDelegate(_asyncIterator(streamChunk(l,r)))),4);case 4:n=!1,e.n=2;break;case 5:e.n=7;break;case 6:e.p=6,u=e.v,i=!0,a=u;case 7:if(e.p=7,e.p=8,!n||null==s.return){e.n=9;break}return e.n=9,_awaitAsyncGenerator(s.return());case 9:if(e.p=9,!i){e.n=10;break}throw a;case 10:return e.f(9);case 11:return e.f(7);case 12:return e.a(2)}},e,null,[[8,,9,11],[1,6,7,12]])}));return function(t,r){return e.apply(this,arguments)}}(),readStream=function(){var e=_wrapAsyncGenerator(_regenerator().m(function e(t){var r,n,i,a;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(!t[Symbol.asyncIterator]){e.n=2;break}return e.d(_regeneratorValues(_asyncGeneratorDelegate(_asyncIterator(t))),1);case 1:return e.a(2);case 2:r=t.getReader(),e.p=3;case 4:return e.n=5,_awaitAsyncGenerator(r.read());case 5:if(n=e.v,i=n.done,a=n.value,!i){e.n=6;break}return e.a(3,8);case 6:return e.n=7,a;case 7:e.n=4;break;case 8:return e.p=8,e.n=9,_awaitAsyncGenerator(r.cancel());case 9:return e.f(8);case 10:return e.a(2)}},e,null,[[3,,8,10]])}));return function(t){return e.apply(this,arguments)}}(),trackStream=function(e,t,r,n){var i,a=readBytes(e,t),s=0,o=function(e){i||(i=!0,n&&n(e))};return new ReadableStream({pull:function(e){return _asyncToGenerator(_regenerator().m(function t(){var n,i,l,u,c,d;return _regenerator().w(function(t){for(;;)switch(t.p=t.n){case 0:return t.p=0,t.n=1,a.next();case 1:if(n=t.v,i=n.done,l=n.value,!i){t.n=2;break}return o(),e.close(),t.a(2);case 2:u=l.byteLength,r&&(c=s+=u,r(c)),e.enqueue(new Uint8Array(l)),t.n=4;break;case 3:throw t.p=3,d=t.v,o(d),d;case 4:return t.a(2)}},t,null,[[0,3]])}))()},cancel:function(e){return o(e),a.return()}},{highWaterMark:2})},isHexDigit=function(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102},isPercentEncodedByte=function(e,t,r){return t+2<r&&isHexDigit(e.charCodeAt(t+1))&&isHexDigit(e.charCodeAt(t+2))},hexValue=function(e){return e<=57?e-48:(223&e)-55},isBase64Char=function(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||43===e||47===e||45===e||95===e},isBase64Whitespace=function(e){return 9===e||10===e||12===e||13===e||32===e},base64Bytes=function(e){var t=e%4;return 3*Math.floor(e/4)+(2===t?1:3===t?2:0)},estimateBase64BufferAllocation=function(e){var t=e.length,r=0;return t>0&&61===e.charCodeAt(t-1)&&(r++,t>1&&61===e.charCodeAt(t-2)&&r++),Math.floor(3*(t-r)/4)},estimatePercentDecodedBase64Bytes=function(e){for(var t=e.length,r=0,n=0,i=!1,a=0;a<t;a++){var s=e.charCodeAt(a);37===s&&isPercentEncodedByte(e,a,t)&&(s=16*hexValue(e.charCodeAt(a+1))+hexValue(e.charCodeAt(a+2)),a+=2),isBase64Whitespace(s)||(61!==s?!isBase64Char(s)||n>0?i=!0:r++:n++)}return i||n>2||n>0&&(r+n)%4!=0||r%4==1?estimateBase64BufferAllocation(e):base64Bytes(r)},estimateDataURLBytes=function(e,t){if(!e||"string"!=typeof e)return 0;if(!e.startsWith("data:"))return 0;var r=e.indexOf(",");if(r<0)return 0;var n=e.slice(5,r),i=e.slice(r+1);if(/;base64/i.test(n))return t(i);for(var a=0,s=0,o=i.length;s<o;s++){var l=i.charCodeAt(s);if(37===l&&isPercentEncodedByte(i,s,o))a+=1,s+=2;else if(l<128)a+=1;else if(l<2048)a+=2;else if(l>=55296&&l<=56319&&s+1<o){var u=i.charCodeAt(s+1);u>=56320&&u<=57343?(a+=4,s++):a+=3}else a+=3}return a};function estimateDataURLDecodedBytes(e){var t="string"==typeof e?e.indexOf("#"):-1;return estimateDataURLBytes(-1===t?e:e.slice(0,t),estimatePercentDecodedBase64Bytes)}var VERSION="1.20.0",DEFAULT_CHUNK_SIZE=65536,DEFAULT_REQUEST_OPTIONS={cache:"default",redirect:"follow",referrer:"about:client",referrerPolicy:"",mode:"cors",integrity:"",keepalive:!1,priority:"auto",window:null},isFunction=utils$1.isFunction,encodeUTF8=function(e){return encodeURIComponent(e).replace(/%([0-9A-F]{2})/gi,function(e,t){return String.fromCharCode(parseInt(t,16))})},decodeURIComponentSafe=function(e){if(!utils$1.isString(e))return e;try{return decodeURIComponent(e)}catch(t){return e}},test=function(e){try{for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];return!!e.apply(void 0,r)}catch(i){return!1}},maybeWithAuthCredentials=function(e){var t=e.indexOf("://"),r=e;return-1!==t&&(r=r.slice(t+3)),r.includes("@")||r.includes(":")},factory=function(e){var t=void 0!==utils$1.global&&null!==utils$1.global?utils$1.global:globalThis,r=t.ReadableStream,n=t.TextEncoder,i=e=utils$1.merge.call({skipUndefined:!0},{Request:t.Request,Response:t.Response},e),a=i.fetch,s=i.Request,o=i.Response,l=a?isFunction(a):"function"==typeof fetch,u=isFunction(s),c=isFunction(o);if(!l)return!1;var d,h=l&&isFunction(r),f=l&&("function"==typeof n?(d=new n,function(e){return d.encode(e)}):function(){var e=_asyncToGenerator(_regenerator().m(function e(t){var r,n;return _regenerator().w(function(e){for(;;)switch(e.n){case 0:return r=Uint8Array,e.n=1,new s(t).arrayBuffer();case 1:return n=e.v,e.a(2,new r(n))}},e)}));return function(t){return e.apply(this,arguments)}}()),v=u&&h&&test(function(){var e=!1,t=new s(platform.origin,{body:new r,method:"POST",get duplex(){return e=!0,"half"}}),n=t.headers.has("Content-Type");return null!=t.body&&t.body.cancel(),e&&!n}),p=c&&h&&test(function(){return utils$1.isReadableStream(new o("").body)}),g={stream:p&&function(e){return e.body}};l&&["text","arrayBuffer","blob","formData","stream"].forEach(function(e){!g[e]&&(g[e]=function(t,r){var n=t&&t[e];if(n)return n.call(t);throw new AxiosError("Response type '".concat(e,"' is not supported"),AxiosError.ERR_NOT_SUPPORT,r)})});var y=function(){var e=_asyncToGenerator(_regenerator().m(function e(t){var r;return _regenerator().w(function(e){for(;;)switch(e.n){case 0:if(null!=t){e.n=1;break}return e.a(2,0);case 1:if(!utils$1.isBlob(t)){e.n=2;break}return e.a(2,t.size);case 2:if(!utils$1.isSpecCompliantForm(t)){e.n=4;break}return r=new s(platform.origin,{method:"POST",body:t}),e.n=3,r.arrayBuffer();case 3:case 6:return e.a(2,e.v.byteLength);case 4:if(!utils$1.isArrayBufferView(t)&&!utils$1.isArrayBuffer(t)){e.n=5;break}return e.a(2,t.byteLength);case 5:if(utils$1.isURLSearchParams(t)&&(t+=""),!utils$1.isString(t)){e.n=7;break}return e.n=6,f(t);case 7:return e.a(2)}},e)}));return function(t){return e.apply(this,arguments)}}(),m=function(){var e=_asyncToGenerator(_regenerator().m(function e(t,r){var n;return _regenerator().w(function(e){for(;;)if(0===e.n)return n=utils$1.toFiniteNumber(t.getContentLength()),e.a(2,null==n?y(r):n)},e)}));return function(t,r){return e.apply(this,arguments)}}();return function(){var e=_asyncToGenerator(_regenerator().m(function e(t){var r,i,l,c,d,f,E,S,T,k,_,A,b,L,R,C,I,P,D,w,O,x,M,F,N,U,B,G,H,$,K,V,j,q,W,Y,z,X,Q,J,Z,ee,te,re,ne,ie,ae,se,oe,le,ue,ce,de,he,fe,ve,pe,ge,ye,me,Ee,Se,Te,ke;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(r=resolveConfig(t),i=r.url,l=r.method,c=r.data,d=r.signal,f=r.cancelToken,E=r.timeout,S=r.onDownloadProgress,T=r.onUploadProgress,k=r.responseType,_=r.headers,A=r.withCredentials,b=void 0===A?"same-origin":A,L=r.fetchOptions,R=r.maxContentLength,C=r.maxBodyLength,I=r.maxRedirects,P=utils$1.isNumber(R)&&R>-1,D=utils$1.isNumber(C)&&C>-1,w=function(e){return utils$1.hasOwnProp(t,e)?t[e]:void 0},O=a||fetch,k=k?(k+"").toLowerCase():"text",x=composeSignals([d,f&&f.toAbortSignal()],E),M=null,F=x&&x.unsubscribe&&function(){x.unsubscribe()},U=null,B=function(){return new AxiosError("Request body larger than maxBodyLength limit",AxiosError.ERR_BAD_REQUEST,t,M)},e.p=1,G=void 0,(H=w("auth"))&&($=utils$1.getSafeProp(H,"username")||"",K=utils$1.getSafeProp(H,"password")||"",G={username:$,password:K}),maybeWithAuthCredentials(i)&&(V=new URL(i,platform.origin),G||!V.username&&!V.password||(j=decodeURIComponentSafe(V.username),q=decodeURIComponentSafe(V.password),G={username:j,password:q}),(V.username||V.password)&&(V.username="",V.password="",i=V.href)),G&&(_.delete("authorization"),_.set("Authorization","Basic "+btoa(encodeUTF8((G.username||"")+":"+(G.password||""))))),!P||"string"!=typeof i||!i.startsWith("data:")){e.n=2;break}if(!(estimateDataURLDecodedBytes(i)>R)){e.n=2;break}throw new AxiosError("maxContentLength size of "+R+" exceeded",AxiosError.ERR_BAD_RESPONSE,t,M);case 2:if(!D||"get"===l||"head"===l){e.n=4;break}return e.n=3,y(c);case 3:if("number"!=typeof(W=e.v)||!isFinite(W)){e.n=4;break}if(N=W,!(W>C)){e.n=4;break}throw B();case 4:if(Y=D&&(utils$1.isReadableStream(c)||utils$1.isStream(c)),z=function(e,t,r){return trackStream(e,DEFAULT_CHUNK_SIZE,function(e){if(D&&e>C)throw U=B();t&&t(e)},r)},!v||"get"===l||"head"===l||!T&&!Y){e.n=8;break}if(null!=N){e.n=6;break}return e.n=5,m(_,c);case 5:Te=e.v,e.n=7;break;case 6:Te=N;case 7:(0!==(N=Te)||Y)&&(X=new s(i,{method:"POST",body:c,duplex:"half"}),utils$1.isFormData(c)&&(Q=X.headers.get("content-type"))&&_.setContentType(Q),X.body&&(J=T&&progressEventDecorator(N,progressEventReducer(asyncDecorator(T)))||[],Z=_slicedToArray(J,2),ee=Z[0],te=Z[1],c=z(X.body,ee,te))),e.n=10;break;case 8:if(!Y||u||!h||"get"===l||"head"===l){e.n=9;break}c=z(c),e.n=10;break;case 9:if(!Y||!u||v||"get"===l||"head"===l){e.n=10;break}throw new AxiosError("Stream request bodies are not supported by the current fetch implementation",AxiosError.ERR_NOT_SUPPORT,t,M);case 10:return utils$1.isString(b)||(b=b?"include":"omit"),re=u&&"credentials"in s.prototype,utils$1.isFormData(c)&&(ne=_.getContentType())&&/^multipart\/form-data/i.test(ne)&&!/boundary=/i.test(ne)&&_.delete("content-type"),_.set("User-Agent","axios/"+VERSION,!1),(ie=null==L?L:Object.assign(Object.create(null),L))&&(delete ie.body,delete ie.headers,delete ie.method,delete ie.signal,delete ie.duplex,delete ie.credentials),ae=Object.assign(Object.create(null),ie,{signal:x,method:l.toUpperCase(),headers:toByteStringHeaderObject(_.normalize()),body:c,duplex:"half",credentials:re?b:void 0}),u&&(utils$1.forEach(DEFAULT_REQUEST_OPTIONS,function(e,t){void 0===ae[t]&&(ae[t]=e)}),void 0===ae.signal&&(ae.signal=null),void 0===ae.body&&(ae.body=null)),0===I&&(ae.redirect="manual",ie&&(ie.redirect="manual")),M=u&&new s(i,ae),e.n=11,u?O(M,ie):O(i,ae);case 11:if(se=e.v,oe=AxiosHeaders.from(se.headers),!P){e.n=12;break}if(!(null!=(le=utils$1.toFiniteNumber(oe.getContentLength()))&&le>R)){e.n=12;break}throw new AxiosError("maxContentLength size of "+R+" exceeded",AxiosError.ERR_BAD_RESPONSE,t,M);case 12:return ue=p&&("stream"===k||"response"===k),p&&se.body&&(S||P||ue&&F)&&(ce={},["status","statusText","headers"].forEach(function(e){ce[e]=se[e]}),de=utils$1.toFiniteNumber(oe.getContentLength()),he=S&&progressEventDecorator(de,progressEventReducer(asyncDecorator(S),!0))||[],fe=_slicedToArray(he,2),ve=fe[0],pe=fe[1],ge=function(e){if(P&&e>R)throw new AxiosError("maxContentLength size of "+R+" exceeded",AxiosError.ERR_BAD_RESPONSE,t,M);ve&&ve(e)},se=new o(trackStream(se.body,DEFAULT_CHUNK_SIZE,ge,function(){pe&&pe(),F&&F()}),ce)),k=k||"text",e.n=13,g[utils$1.findKey(g,k)||"text"](se,t);case 13:if(ye=e.v,!P||p||ue){e.n=14;break}if(null!=ye&&("number"==typeof ye.byteLength?me=ye.byteLength:"number"==typeof ye.size?me=ye.size:"string"==typeof ye&&(me="function"==typeof n?(new n).encode(ye).byteLength:ye.length)),!("number"==typeof me&&me>R)){e.n=14;break}throw new AxiosError("maxContentLength size of "+R+" exceeded",AxiosError.ERR_BAD_RESPONSE,t,M);case 14:return!ue&&F&&F(),e.n=15,new Promise(function(e,r){settle(e,r,{data:ye,headers:AxiosHeaders.from(se.headers),status:se.status,statusText:se.statusText,config:t,request:M})});case 15:return e.a(2,e.v);case 16:if(e.p=16,ke=e.v,F&&F(),!(x&&x.aborted&&x.reason instanceof AxiosError)){e.n=17;break}throw(Ee=x.reason).config=t,M&&(Ee.request=M),ke!==Ee&&Object.defineProperty(Ee,"cause",{__proto__:null,value:ke,writable:!0,enumerable:!1,configurable:!0}),Ee;case 17:if(!U){e.n=18;break}throw M&&!U.request&&(U.request=M),U;case 18:if(!(ke instanceof AxiosError)){e.n=19;break}throw M&&!ke.request&&(ke.request=M),ke;case 19:if(!ke||"TypeError"!==ke.name||!/Load failed|fetch/i.test(ke.message)){e.n=20;break}throw Se=new AxiosError("Network Error",AxiosError.ERR_NETWORK,t,M,ke&&ke.response),Object.defineProperty(Se,"cause",{__proto__:null,value:ke.cause||ke,writable:!0,enumerable:!1,configurable:!0}),Se;case 20:throw AxiosError.from(ke,ke&&ke.code,t,M,ke&&ke.response);case 21:return e.a(2)}},e,null,[[1,16]])}));return function(t){return e.apply(this,arguments)}}()},seedCache=new Map,getFetch=function(e){for(var t,r,n=e&&e.env||{},i=n.fetch,a=[n.Request,n.Response,i],s=a.length,o=seedCache;s--;)t=a[s],void 0===(r=o.get(t))&&o.set(t,r=s?new Map:factory(n)),o=r;return r};getFetch();var knownAdapters={http:httpAdapter,xhr:xhrAdapter,fetch:{get:getFetch}};utils$1.forEach(knownAdapters,function(e,t){if(e){try{Object.defineProperty(e,"name",{__proto__:null,value:t})}catch(r){}Object.defineProperty(e,"adapterName",{__proto__:null,value:t})}});var renderReason=function(e){return"- ".concat(e)},isResolvedHandle=function(e){return utils$1.isFunction(e)||null===e||!1===e};function getAdapter(e,t){for(var r,n,i=(e=utils$1.isArray(e)?e:[e]).length,a={},s=0;s<i;s++){var o=void 0;if(n=r=e[s],!isResolvedHandle(r)&&void 0===(n=knownAdapters[(o=String(r)).toLowerCase()]))throw new AxiosError("Unknown adapter '".concat(o,"'"));if(n&&(utils$1.isFunction(n)||(n=n.get(t))))break;a[o||"#"+s]=n}if(!n){var l=Object.entries(a).map(function(e){var t=_slicedToArray(e,2),r=t[0],n=t[1];return"adapter ".concat(r," ")+(!1===n?"is not supported by the environment":"is not available in the build")}),u=i?l.length>1?"since :\n"+l.map(renderReason).join("\n"):" "+renderReason(l[0]):"as no adapter specified";throw new AxiosError("There is no suitable adapter to dispatch the request "+u,AxiosError.ERR_NOT_SUPPORT)}return n}var adapters={getAdapter:getAdapter,adapters:knownAdapters};function throwIfCancellationRequested(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new CanceledError(null,e)}function dispatchRequest(e){var t=utils$1.toSafeFlatObject(e);return throwIfCancellationRequested(t),t.headers=AxiosHeaders.from(utils$1.getSafeProp(t,"headers")),t.data=transformData.call(t,t.transformRequest),-1!==["post","put","patch"].indexOf(t.method)&&t.headers.setContentType("application/x-www-form-urlencoded",!1),adapters.getAdapter(t.adapter||defaults.adapter,t)(t).then(function(e){throwIfCancellationRequested(t),t.response=e;try{e.data=transformData.call(t,t.transformResponse,e)}finally{delete t.response}return e.headers=AxiosHeaders.from(e.headers),e},function(e){if(!isCancel(e)&&(throwIfCancellationRequested(t),e&&e.response)){t.response=e.response;try{e.response.data=transformData.call(t,t.transformResponse,e.response)}finally{delete t.response}e.response.headers=AxiosHeaders.from(e.response.headers)}return Promise.reject(e)})}var validators$1={};["object","boolean","number","function","string","symbol"].forEach(function(e,t){validators$1[e]=function(r){return _typeof(r)===e||"a"+(t<1?"n ":" ")+e}});var deprecatedWarnings={};function assertOptions(e,t,r){if("object"!==_typeof(e)||null===e)throw new AxiosError("options must be an object",AxiosError.ERR_BAD_OPTION_VALUE);for(var n=Object.keys(e),i=n.length;i-- >0;){var a=n[i],s=Object.prototype.hasOwnProperty.call(t,a)?t[a]:void 0;if(s){var o=e[a],l=void 0===o||s(o,a,e);if(!0!==l)throw new AxiosError("option "+a+" must be "+l,AxiosError.ERR_BAD_OPTION_VALUE)}else if(!0!==r)throw new AxiosError("Unknown option "+a,AxiosError.ERR_BAD_OPTION)}}validators$1.transitional=function(e,t,r){function n(e,t){return"[Axios v"+VERSION+"] Transitional option '"+e+"'"+t+(r?". "+r:"")}return function(r,i,a){if(!1===e)throw new AxiosError(n(i," has been removed"+(t?" in "+t:"")),AxiosError.ERR_DEPRECATED);return t&&!deprecatedWarnings[i]&&(deprecatedWarnings[i]=!0,console.warn(n(i," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,i,a)}},validators$1.spelling=function(e){return function(t,r){return console.warn("".concat(r," is likely a misspelling of ").concat(e)),!0}};var validator={assertOptions:assertOptions,validators:validators$1},validators=validator.validators,Axios=function(){return _createClass(function e(t){_classCallCheck(this,e),this.defaults=t||{},this.interceptors={request:new InterceptorManager,response:new InterceptorManager}},[{key:"request",value:(e=_asyncToGenerator(_regenerator().m(function e(t,r){var n,i,a,s,o,l,u,c;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:return e.p=0,e.n=1,this._request(t,r);case 1:return e.a(2,e.v);case 2:if(e.p=2,(c=e.v)instanceof Error)try{n={},Error.captureStackTrace?Error.captureStackTrace(n):n=new Error,i=n.stack,a="","string"==typeof i&&(s=i.indexOf("\n"),a=-1===s?"":i.slice(s+1)),c.stack?a&&(o=a.indexOf("\n"),l=-1===o?-1:a.indexOf("\n",o+1),u=-1===l?"":a.slice(l+1),String(c.stack).endsWith(u)||(c.stack+="\n"+a)):c.stack=a}catch(d){}throw c;case 3:return e.a(2)}},e,this,[[0,2]])})),function(t,r){return e.apply(this,arguments)})},{key:"_request",value:function(e,t){var r=this;"string"==typeof e?(t=t||{}).url=e:t=e||{};var n=t=mergeConfig(this.defaults,t),i=n.transitional,a=n.paramsSerializer,s=n.headers;void 0!==i&&validator.assertOptions(i,{silentJSONParsing:validators.transitional(validators.boolean),forcedJSONParsing:validators.transitional(validators.boolean),clarifyTimeoutError:validators.transitional(validators.boolean),legacyInterceptorReqResOrdering:validators.transitional(validators.boolean),advertiseZstdAcceptEncoding:validators.transitional(validators.boolean),validateStatusUndefinedResolves:validators.transitional(validators.boolean)},!1),null!=a&&(utils$1.isFunction(a)?t.paramsSerializer={serialize:a}:validator.assertOptions(a,{encode:validators.function,serialize:validators.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),validator.assertOptions(t,{baseUrl:validators.spelling("baseURL"),withXsrfToken:validators.spelling("withXSRFToken")},!0),t.method=(utils$1.getSafeProp(t,"method")||utils$1.getSafeProp(this.defaults,"method")||"get").toLowerCase();var o=s&&utils$1.merge(s.common,s[t.method]);s&&utils$1.forEach(methodList.concat("common"),function(e){delete s[e]}),t.headers=AxiosHeaders.concat(o,s);var l=[],u=!0;this.interceptors.request.forEach(function(e){if("function"!=typeof e.runWhen||!1!==e.runWhen(t)){u=u&&e.synchronous;var r=t.transitional||transitionalDefaults;r&&r.legacyInterceptorReqResOrdering?l.unshift(e.fulfilled,e.rejected):l.push(e.fulfilled,e.rejected)}});var c,d=[];this.interceptors.response.forEach(function(e){d.push(e.fulfilled,e.rejected)});var h,f=0;if(!u){var v=[dispatchRequest.bind(this),void 0];for(v.unshift.apply(v,l),v.push.apply(v,d),h=v.length,c=Promise.resolve(t);f<h;)c=c.then(v[f++],v[f++]);return c}h=l.length;for(var p=t;f<h;){var g=l[f++],y=l[f++];try{p=g?g(p):p}catch(E){if(!y){c=Promise.reject(E);break}try{var m=y.call(this,E);utils$1.isThenable(m)&&(c=Promise.resolve(m).then(function(){return dispatchRequest.call(r,p)}))}catch(S){c=Promise.reject(S)}break}}if(!c)try{c=dispatchRequest.call(this,p)}catch(E){c=Promise.reject(E)}for(f=0,h=d.length;f<h;)c=c.then(d[f++],d[f++]);return c}},{key:"getUri",value:function(e){return buildURL(buildFullPath((e=mergeConfig(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls,e),e.params,e.paramsSerializer)}}]);var e}();utils$1.forEach(["delete","get","head","options"],function(e){Axios.prototype[e]=function(t,r){return this.request(mergeConfig(r||{},{method:e,url:t,data:r&&utils$1.hasOwnProp(r,"data")?r.data:void 0}))}}),utils$1.forEach(["post","put","patch","query"],function(e){function t(t){return function(r,n,i){return this.request(mergeConfig(i||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:n}))}}Axios.prototype[e]=t(),"query"!==e&&(Axios.prototype[e+"Form"]=t(!0))});var CancelToken=function(){function e(t){if(_classCallCheck(this,e),"function"!=typeof t)throw new TypeError("executor must be a function.");var r;this.promise=new Promise(function(e){r=e});var n=this;this.promise.then(function(e){if(n._listeners){for(var t=n._listeners.length;t-- >0;)n._listeners[t](e);n._listeners=null}}),this.promise.then=function(e){var t,r=new Promise(function(e){n.subscribe(e),t=e}).then(e);return r.cancel=function(){n.unsubscribe(t)},r},t(function(e,t,i){n.reason||(n.reason=new CanceledError(e,t,i),r(n.reason))})}return _createClass(e,[{key:"throwIfRequested",value:function(){if(this.reason)throw this.reason}},{key:"subscribe",value:function(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}},{key:"unsubscribe",value:function(e){if(this._listeners){var t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}}},{key:"toAbortSignal",value:function(){var e=this,t=new AbortController,r=function(e){t.abort(e)};return this.subscribe(r),t.signal.unsubscribe=function(){return e.unsubscribe(r)},t.signal}}],[{key:"source",value:function(){var t;return{token:new e(function(e){t=e}),cancel:t}}}])}();function spread(e){return function(t){return e.apply(null,t)}}function isAxiosError(e){return utils$1.isObject(e)&&!0===e.isAxiosError}var HttpStatusCode={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,ContentTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,UnprocessableContent:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerReturnsAnUnknownError:520,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};function createInstance(e){var t=new Axios(e),r=bind(Axios.prototype.request,t);return utils$1.extend(r,Axios.prototype,t,{allOwnKeys:!0}),utils$1.extend(r,t,null,{allOwnKeys:!0}),r.create=function(t){return createInstance(mergeConfig(e,t))},r}Object.entries(HttpStatusCode).forEach(function(e){var t=_slicedToArray(e,2),r=t[0],n=t[1];void 0===HttpStatusCode[n]&&(HttpStatusCode[n]=r)});var axios=createInstance(defaults);axios.Axios=Axios,axios.CanceledError=CanceledError,axios.CancelToken=CancelToken,axios.isCancel=isCancel,axios.VERSION=VERSION,axios.toFormData=toFormData,axios.AxiosError=AxiosError,axios.Cancel=axios.CanceledError,axios.all=function(e){return Promise.all(e)},axios.spread=spread,axios.isAxiosError=isAxiosError,axios.mergeConfig=mergeConfig,axios.AxiosHeaders=AxiosHeaders,axios.formToJSON=function(e){return formDataToJSON(utils$1.isHTMLForm(e)?new FormData(e):e)},axios.getAdapter=adapters.getAdapter,axios.HttpStatusCode=HttpStatusCode,axios.default=axios,axios.Axios,axios.AxiosError,axios.CanceledError,axios.isCancel,axios.CancelToken,axios.VERSION,axios.all,axios.Cancel,axios.isAxiosError,axios.spread,axios.toFormData,axios.AxiosHeaders,axios.HttpStatusCode,axios.formToJSON,axios.getAdapter,axios.mergeConfig,axios.create;var HttpUtil=_createClass(function e(t){var r=this;_classCallCheck(this,e),_defineProperty$1(this,"get",function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return new Promise(function(i,a){r.instance(_objectSpread2$1({url:e,method:"GET",params:t},n)).then(function(e){i(e)}).catch(function(e){a(e)})})}),_defineProperty$1(this,"post",function(e,t,n){return new Promise(function(i,a){var s={};n?s["Content-Type"]="json"===n?"application/json":"multipart/form-data":(t=qs.stringify(t),s["Content-Type"]="application/x-www-form-urlencoded"),r.instance({url:e,method:"POST",data:t,headers:s}).then(function(e){i(e)}).catch(function(e){a(e)})})}),this.instance=axios.create({baseURL:t||"",timeout:1e4}),this.instance.interceptors.request.use(function(e){return e}),this.instance.interceptors.response.use(function(e){var t=e.data,r=t.code,n=t.message;return r&&200===r?Promise.resolve(e.data):Promise.reject(n)},function(e){return console.log(e),Promise.reject(e)})}),PlayUrlAble=function(){return _createClass(function e(){_classCallCheck(this,e)},null,[{key:"fetchUrls",value:function(e,t){return(new HttpUtil).get("".concat(e,"?appid=").concat(t,"&all_play_url=true"))}},{key:"sortUrls",value:function(e){return e.sort(function(e,t){return e.file_size-t.file_size})}},{key:"markSources",value:function(e){return e.map(function(e){var t,r,n=Number(null!==(t=e.source_type)&&void 0!==t?t:e.sourceType),i=Number(null!==(r=e.source_storage_id)&&void 0!==r?r:e.sourceStorageId);return _objectSpread2$1(_objectSpread2$1({},e),{},{source_type:n,source_storage_id:i,isLine2:8===n&&4===i})})}},{key:"findLine2Source",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];if(!e||!e.length)return null;var t=e.find(function(e){return e.isLine2&&e.url});return t||(e.find(function(e){var t,r;return 8===Number(null!==(t=e.source_type)&&void 0!==t?t:e.sourceType)&&4===Number(null!==(r=e.source_storage_id)&&void 0!==r?r:e.sourceStorageId)&&e.url})||null)}},{key:"probeSource",value:function(e){var t=performance.now();return fetch(e.url,{method:"GET",headers:{Accept:"application/vnd.apple.mpegurl, */*"}}).then(function(){var r=_asyncToGenerator(_regenerator().m(function r(n){var i,a;return _regenerator().w(function(r){for(;;)switch(r.n){case 0:return r.n=1,n.text();case 1:return i=r.v,a=n.ok&&/#EXTM3U/i.test(i),r.a(2,{ok:a,durationMs:Math.round(performance.now()-t),url:e.url,content:a?i:null,isLine2:!!e.isLine2,source:e})}},r)}));return function(e){return r.apply(this,arguments)}}()).catch(function(){return{ok:!1,durationMs:Math.round(performance.now()-t),url:e.url,content:null,isLine2:!!e.isLine2,source:e}})}},{key:"raceFastestSource",value:function(){var e=this,t=arguments.length>1?arguments[1]:void 0,r=arguments.length>2?arguments[2]:void 0,n=((arguments.length>0&&void 0!==arguments[0]?arguments[0]:[])||[]).filter(function(e){return e&&e.url});if(!n.length)return Promise.resolve({winner:null,results:[]});if(1===n.length){var i=n[0],a={ok:!0,durationMs:0,url:i.url,skipped:!0,isLine2:!!i.isLine2,source:i};return"function"==typeof t&&t(i,a),Promise.resolve({winner:i,results:[a]})}var s=!1,o=n.map(function(n){return e.probeSource(n).then(function(e){return e.ok&&e.content&&r&&(r[e.url]=e.content),e.ok&&!s&&(s=!0,"function"==typeof t&&t(n,e)),e})});return Promise.all(o).then(function(e){var t=e.filter(function(e){return e.ok&&e.content}).sort(function(e,t){return e.durationMs-t.durationMs});return{winner:t.length?t[0].source:null,results:e}})}},{key:"putWinnerFirst",value:function(e,t){if(!t||!e||!e.length)return e||[];var r=e.filter(function(e){return e&&e.url!==t.url});return[t].concat(_toConsumableArray(r))}},{key:"ableUrls",value:(e=_asyncToGenerator(_regenerator().m(function e(t){var r;return _regenerator().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,this.fetchUrls(t.sourceURL,t.appId);case 1:return r=e.v,e.a(2,this.markSources(this.sortUrls(r.data.play_urls||[])))}},e,this)})),function(t){return e.apply(this,arguments)})}]);var e}(),CanvasMirror=function(){return _createClass(function e(t,r){var n=this;_classCallCheck(this,e),this.video=t,this.container=r,this.canvas=document.createElement("canvas"),this.canvas.className="ylc-video-canvas-mirror",this.canvas.setAttribute("data-ylc","canvas-mirror"),this.ctx=this.canvas.getContext("2d",{alpha:!1}),this.running=!1,this.destroyed=!1,this.failed=!1,this.raf=0,this.vfc=0,this._onPlay=function(){return n.start()},this._onPause=function(){n.draw(),n.stop()},this._onFrame=function(){return n.draw()},this._onResize=function(){return n.resize()},this._onFs=function(){return n.exitNativeFullscreen()},this.hideVideo(),this.resize(),this.bind()},[{key:"hideVideo",value:function(){var e=this.video;e.setAttribute("t7-video-player-type","inline"),e.setAttribute("x5-video-player-type","h5"),e.setAttribute("x5-video-player-fullscreen","false"),e.controls=!1,e.removeAttribute("controls"),e.style.cssText=["position:fixed","left:-9999px","top:0","width:16px","height:16px","opacity:0.01","pointer-events:none","z-index:-1","object-fit:contain"].join(";")}},{key:"restoreVideo",value:function(){this.video.style.cssText=["position:relative","z-index:0","width:100%","height:100%","background:#000","overflow:hidden","object-fit:contain","pointer-events:none"].join(";"),this.canvas&&this.canvas.parentNode&&(this.canvas.style.display="none")}},{key:"bind",value:function(){this.video.addEventListener("play",this._onPlay),this.video.addEventListener("playing",this._onPlay),this.video.addEventListener("pause",this._onPause),this.video.addEventListener("ended",this._onPause),this.video.addEventListener("seeked",this._onFrame),this.video.addEventListener("loadeddata",this._onFrame),window.addEventListener("resize",this._onResize),document.addEventListener("fullscreenchange",this._onFs),document.addEventListener("webkitfullscreenchange",this._onFs),this.video.addEventListener("webkitbeginfullscreen",this._onFs),"undefined"!=typeof ResizeObserver&&(this.ro=new ResizeObserver(this._onResize),this.ro.observe(this.container))}},{key:"unbind",value:function(){this.video.removeEventListener("play",this._onPlay),this.video.removeEventListener("playing",this._onPlay),this.video.removeEventListener("pause",this._onPause),this.video.removeEventListener("ended",this._onPause),this.video.removeEventListener("seeked",this._onFrame),this.video.removeEventListener("loadeddata",this._onFrame),window.removeEventListener("resize",this._onResize),document.removeEventListener("fullscreenchange",this._onFs),document.removeEventListener("webkitfullscreenchange",this._onFs),this.video.removeEventListener("webkitbeginfullscreen",this._onFs),this.ro&&(this.ro.disconnect(),this.ro=null)}},{key:"exitNativeFullscreen",value:function(e){e&&"function"==typeof e.preventDefault&&e.preventDefault();try{this.video.webkitExitFullScreen&&this.video.webkitExitFullScreen()}catch(err){}try{document.fullscreenElement&&document.exitFullscreen(),document.webkitFullscreenElement&&document.webkitExitFullscreen&&document.webkitExitFullscreen()}catch(err){}}},{key:"resize",value:function(){if(!this.destroyed&&this.container){var e=this.container.getBoundingClientRect(),t=Math.min(window.devicePixelRatio||1,2),r=Math.max(1,Math.floor(e.width*t)),n=Math.max(1,Math.floor(e.height*t));this.canvas.width===r&&this.canvas.height===n||(this.canvas.width=r,this.canvas.height=n,this.draw())}}},{key:"draw",value:function(){if(!this.destroyed&&!this.failed&&this.ctx){var e=this.canvas.width,t=this.canvas.height,r=this.video.videoWidth,n=this.video.videoHeight;if(this.ctx.fillStyle="#000",this.ctx.fillRect(0,0,e,t),r&&n){var i=Math.min(e/r,t/n),a=r*i,s=n*i,o=(e-a)/2,l=(t-s)/2;try{this.ctx.drawImage(this.video,o,l,a,s)}catch(err){this.failed=!0,this.stop(),this.restoreVideo()}}}}},{key:"start",value:function(){this.running||this.destroyed||this.failed||(this.running=!0,this.loop())}},{key:"loop",value:function(){var e=this;!this.running||this.destroyed||this.failed||(this.draw(),"function"==typeof this.video.requestVideoFrameCallback?this.vfc=this.video.requestVideoFrameCallback(function(){return e.loop()}):this.raf=requestAnimationFrame(function(){return e.loop()}))}},{key:"stop",value:function(){if(this.running=!1,this.vfc&&"function"==typeof this.video.cancelVideoFrameCallback)try{this.video.cancelVideoFrameCallback(this.vfc)}catch(e){}this.vfc=0,this.raf&&cancelAnimationFrame(this.raf),this.raf=0}},{key:"destroy",value:function(){this.destroyed=!0,this.stop(),this.unbind(),this.ctx=null,this.video=null,this.container=null,this.canvas=null}}])}(),VideoPlayer=function(){return _createClass(function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(_classCallCheck(this,e),this.containerId=t,this.options=_objectSpread2$1({sourceURL:"",poster:"",autoplay:!1,controls:!0,muted:!1,loop:!1,preload:"metadata",width:"100%",height:"100%"},r),this.hlsInstance=null,this.playUrls=null,this.currentLine=1,this._destroyed=!1,this.controlBar=null,this._handleFullscreenChange=null,this._isSeeking=!1,this._seekTarget=null,this.containerId){var n=document.querySelector("#"+t);n||Logger.error("VideoPlayer日志-未查询到节点",{containerId:t,elTmp:n}),Logger.info("VideoPlayer日志-开始事件和节点初始化",{containerId:t,options:_objectSpread2$1(_objectSpread2$1({},this.options),{},{fullscreenElement:""})}),this.el=n,this.events=new Events$1(this),this.clearPlayer(),this.init(),Logger.info("VideoPlayer日志-canVideoPlayHevcHls",{canVideoPlayHevcHls:canVideoPlayHevcHls(),browser:navigator.userAgent,options:this.options})}else Logger.error("VideoPlayer日志-未传节点id",{containerId:t})},[{key:"init",value:function(){this.createPlayerContainer(),this.setVideoSource(),this.bindEvents()}},{key:"createPlayerContainer",value:function(){if(this.el.innerHTML="",Ui.mount(this),isMiBrowser()||isUcLikeBrowser()){this.canvasMirror=new CanvasMirror(this.videoElm,this.container);var e=this.touchMask;e?this.container.insertBefore(this.canvasMirror.canvas,e):this.container.appendChild(this.canvasMirror.canvas),Logger.info("VideoPlayer日志-启用canvas镜像防浏览器接管",{ua:navigator.userAgent})}if(this._bindTouchMask(),this.controlBar=ControlBar.mount(this),"function"==typeof this.options.customControlsMount)try{var t=this.options.customControlsMount({player:this,container:this.container,video:this.videoElm});t instanceof HTMLElement&&this.container.appendChild(t)}catch(r){Logger.error("VideoPlayer日志-挂载自定义控件失败",{e:r})}this.el.appendChild(this.container),Logger.info("VideoPlayer日志-节点初始化完成并加载")}},{key:"_bindTouchMask",value:function(){var e=this;if(this.touchMask){var t=function(e){e.stopPropagation()};this.touchMask.addEventListener("pointerdown",t),this.touchMask.addEventListener("touchstart",t,{passive:!0}),this.touchMask.addEventListener("click",function(t){t.preventDefault(),t.stopPropagation(),e.videoElm&&(e.videoElm.paused?e.play():e.pause())})}}},{key:"setVideoSource",value:(n=_asyncToGenerator(_regenerator().m(function e(){var t;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(!this.useHls()){e.n=6;break}return e.p=1,e.n=2,PlayUrlAble.ableUrls(this.options);case 2:t=e.v,e.n=4;break;case 3:e.p=3,e.v,t=null;case 4:if(!this._destroyed){e.n=5;break}return e.a(2);case 5:this._startHlsWithFastestSource(t),e.n=8;break;case 6:if(!this._destroyed){e.n=7;break}return e.a(2);case 7:this.videoElm.src=this.options.sourceURL;case 8:return e.a(2)}},e,this,[[1,3]])})),function(){return n.apply(this,arguments)})},{key:"bindEvents",value:function(){var e=this;this.videoElm.addEventListener("play",function(){e._applyPlayUi(),e.events.emit("play")}),this.videoElm.addEventListener("playing",function(){e._clearSeekHold(),e._hideLoading(),e.events.emit("playing")}),this.videoElm.addEventListener("pause",function(){e._applyPauseUi(),e.events.emit("pause")}),this.videoElm.addEventListener("ended",function(){e.events.emit("ended")}),this.videoElm.addEventListener("loadedmetadata",function(){ControlTime.updateDurationTime(e),e.events.emit("loadedmetadata")}),this.videoElm.addEventListener("loadeddata",function(){e.events.emit("loadeddata")}),this.videoElm.addEventListener("loadstart",function(){e.events.emit("loadstart")}),this.videoElm.addEventListener("canplay",function(){e.events.emit("autoPlay"),e.events.emit("canplay"),!e._shouldHoldSeekUi()&&e.videoElm.readyState>=3&&e._hideLoading()}),this.videoElm.addEventListener("seeking",function(t){e._isSeeking=!0,null==e._seekTarget&&(e._seekTarget=t.target.currentTime,e._syncSeekUi(e._seekTarget));var r=null!=e._seekTarget?e._seekTarget:t.target.currentTime;e._isTimeBuffered(r)||e._showLoading(),e.events.emit("seeking",t.target.currentTime)}),this.videoElm.addEventListener("seeked",function(t){var r=t.target.currentTime,n=e._seekTarget,i=null==n||Math.abs(r-n)<=.5;e.videoElm.readyState<2||!i?e._syncSeekUi(null!=n?n:r):(e._clearSeekHold(),e._syncSeekUi(r)),(e.videoElm.readyState>=3||e.videoElm.paused&&e.videoElm.readyState>=2)&&e._hideLoading(),e.events.emit("seeked",r)}),this.videoElm.addEventListener("waiting",function(){e._showLoading(),e.events.emit("waiting")}),this.videoElm.addEventListener("durationchange",function(){e.events.emit("durationchange")}),this.videoElm.addEventListener("timeupdate",function(t){e._shouldHoldSeekUi()||(e._clearSeekHold(),ControlTime.updateCurrentTime(e),ControlProgress.updateLine(e)),e.events.emit("timeupdate",t.target.currentTime)}),this.videoElm.addEventListener("error",function(){var t=e.videoElm.error,r={code:t?t.code:null,message:t?t.message:"未知错误",src:e.videoElm.src,networkState:e.videoElm.networkState,readyState:e.videoElm.readyState};t&&t.code&&(r.message={1:"MEDIA_ERR_ABORTED - 用户中止",2:"MEDIA_ERR_NETWORK - 网络错误",3:"MEDIA_ERR_DECODE - 解码错误",4:"MEDIA_ERR_SRC_NOT_SUPPORTED - 格式不支持"}[t.code]||r.message),e.videoElm.src&&e.videoElm.src.startsWith("blob:")?(r.blobUrlError=!0,r.message="Blob URL加载失败: ".concat(e.videoElm.src),Logger.error("VideoPlayer日志-视频Blob URL错误",r),e.hlsInstance&&console.error("HLS实例状态:",{media:e.hlsInstance.media,url:e.hlsInstance.url,levels:e.hlsInstance.levels,currentLevel:e.hlsInstance.currentLevel})):Logger.error("VideoPlayer日志-视频加载错误",r),e.events.emit("error",r)}),this._handleFullscreenChange=function(){var t=!!(document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement);e.events.emit("fullscreenchange",t),e.options.controls&&ControlFullScreen.changeFullScreen(e,t)},document.addEventListener("fullscreenchange",this._handleFullscreenChange),document.addEventListener("webkitfullscreenchange",this._handleFullscreenChange),document.addEventListener("mozfullscreenchange",this._handleFullscreenChange),document.addEventListener("MSFullscreenChange",this._handleFullscreenChange),this.events.on("fullscreenchange",function(t){e.options.controls&&ControlFullScreen.changeFullScreen(e,t)}),this.events.on("volumechange",function(t){ControlVolume.sync(e,t)}),this.events.on("changeProgress",function(t){ControlProgress.updateLineDot(e,t)}),this.options.autoPlay&&this.events.once("autoPlay",function(){e.play()});var t=new MutationObserver(function(){e.videoElm&&e.videoElm.hasAttribute("controls")&&(e.videoElm.removeAttribute("controls"),e.videoElm.controls=!1)});this.videoElm&&(t.observe(this.videoElm,{attributes:!0,attributeFilter:["controls"]}),this._controlsObserver=t,this.videoElm.hasAttribute("controls")&&(this.videoElm.removeAttribute("controls"),this.videoElm.controls=!1)),Logger.info("VideoPlayer日志-事件绑定完成")}},{key:"clearPlayer",value:function(){if(this.el){var e=this.el.querySelector("video");if(e&&(e.pause(),e.src="","function"==typeof e.remove))try{e.remove()}catch(t){}this.el.innerHTML="",Logger.info("VideoPlayer日志-清除播放器")}}},{key:"_applyPlayUi",value:function(){this.status="playing",ControlBtn.changeBtnStatus(this)}},{key:"_applyPauseUi",value:function(){this.status="pause",ControlBtn.changeBtnStatus(this)}},{key:"play",value:function(){if(this._applyPlayUi(),this.videoElm&&(this.videoElm.controls=!1,this.videoElm.removeAttribute("controls"),this.videoElm.paused)){var e=this.videoElm.play();e&&"function"==typeof e.catch&&e.catch(function(){})}Logger.info("VideoPlayer日志-播放",{status:this.status})}},{key:"pause",value:function(){this._applyPauseUi(),this.videoElm&&!this.videoElm.paused&&this.videoElm.pause(),Logger.info("VideoPlayer日志-暂停",{status:this.status})}},{key:"on",value:function(e,t){this.events.on(e,t)}},{key:"off",value:function(e,t){this.events.off(e,t)}},{key:"currentTimeSec",value:function(e){return void 0!==e&&this.seek(e),this.videoElm.currentTime}},{key:"duration",value:function(){return this.videoElm.duration}},{key:"_isProgressDragging",value:function(){return!(!this.progressSlider||!this.progressSlider.isDragging)}},{key:"_isTimeBuffered",value:function(e){var t=this.videoElm&&this.videoElm.buffered;if(!t||!Number.isFinite(e))return!1;for(var r=0;r<t.length;r++)if(e>=t.start(r)&&e<t.end(r)-.15)return!0;return!1}},{key:"_shouldHoldSeekUi",value:function(){return!!this._isProgressDragging()||this._isSeeking}},{key:"_syncSeekUi",value:function(e){if(Number.isFinite(e)&&this.videoElm){var t=this.videoElm.duration;ControlTime.updateCurrentTime(this,e),t&&Number.isFinite(t)&&t>0&&ControlProgress.updateLine(this,e/t)}}},{key:"_clearSeekHold",value:function(){this._isSeeking=!1,this._seekTarget=null}},{key:"_showLoading",value:function(){this.loadingElm&&this.loadingElm.classList.add("is-show")}},{key:"_hideLoading",value:function(){this.loadingElm&&this.loadingElm.classList.remove("is-show")}},{key:"seek",value:function(e){if(this.videoElm&&Number.isFinite(e)){var t=this.videoElm.duration,r=t&&Number.isFinite(t)?Math.max(0,Math.min(t,e)):Math.max(0,e);this._isSeeking=!0,this._seekTarget=r,this._syncSeekUi(r),this._isTimeBuffered(r)||this._showLoading(),this.videoElm.currentTime=r}}},{key:"changeSrc",value:function(e){var t=this;this.hlsInstance&&(HlsPlayer.destroyHlsInstance(this.hlsInstance),this.hlsInstance=null),e&&e.includes(".m3u8")&&Hls.isSupported()?(this.options.isSupportHls=!0,this.options.sourceURL=e,this.setVideoSource()):(this.options.isSupportHls=!1,this.options.sourceURL=e,this.videoElm.src=e,this.events.once("autoPlay",function(){t.play()}))}},{key:"muted",value:function(e){ControlVolume.changeVolume(this,!e),this.events.emit("volumechange",!e)}},{key:"requestFullscreen",value:function(){ControlFullScreen.fullScreen(this)}},{key:"exitFullscreen",value:function(){ControlFullScreen.exitFullScreen(this)}},{key:"changeSpeed",value:function(e){var t=e.value;this.videoElm.playbackRate=t||1}},{key:"uploadPlayerLogs",value:(r=_asyncToGenerator(_regenerator().m(function e(){return _regenerator().w(function(e){for(;;)switch(e.n){case 0:Logger.info("VideoPlayer日志-日志已通过WebSocket实时上报");case 1:return e.a(2)}},e)})),function(){return r.apply(this,arguments)})},{key:"destroy",value:function(){this._destroyed=!0,this._hideLoading(),this._clearSeekHold(),this.hlsInstance&&(HlsPlayer.destroyHlsInstance(this.hlsInstance),this.hlsInstance=null),this._controlsObserver&&(this._controlsObserver.disconnect(),this._controlsObserver=null),this._handleFullscreenChange&&(document.removeEventListener("fullscreenchange",this._handleFullscreenChange),document.removeEventListener("webkitfullscreenchange",this._handleFullscreenChange),document.removeEventListener("mozfullscreenchange",this._handleFullscreenChange),document.removeEventListener("MSFullscreenChange",this._handleFullscreenChange),this._handleFullscreenChange=null),this.canvasMirror&&(this.canvasMirror.destroy(),this.canvasMirror=null),this.events&&"function"==typeof this.events.removeAll&&this.events.removeAll(),this.clearPlayer()}},{key:"useHls",value:function(){return this.options.isSupportHls&&this.options.sourceURL.includes(".m3u8")}},{key:"_findLine2Source",value:function(e){return PlayUrlAble.findLine2Source(e)}},{key:"switchLine",value:(t=_asyncToGenerator(_regenerator().m(function e(t){var r,n,i,a;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(r=2===Number(t)?2:1,!this._destroyed){e.n=1;break}return e.a(2,!1);case 1:if(this.useHls()){e.n=2;break}return e.a(2,!1);case 2:if(this.currentLine!==r||!this.hlsInstance){e.n=3;break}return ControlLine.changeLineUI(this,r),e.a(2,!0);case 3:return e.p=3,e.n=4,PlayUrlAble.ableUrls(this.options);case 4:this.playUrls=e.v,e.n=6;break;case 5:if(e.p=5,e.v,this.playUrls&&this.playUrls.length){e.n=6;break}return e.a(2,!1);case 6:if(!this._destroyed){e.n=7;break}return e.a(2,!1);case 7:if(2!==r){e.n=10;break}if((n=this._findLine2Source(this.playUrls))&&n.url){e.n=8;break}return e.a(2,!1);case 8:return e.n=9,this._reloadHlsByLine({line:2,url:n.url,cdnList:[n],switchCdn:!1});case 9:return e.a(2,!0);case 10:return this.currentLine=1,ControlLine.changeLineUI(this,1),i=this.videoElm?this.videoElm.currentTime:0,a="playing"===this.status||this.videoElm&&!this.videoElm.paused,this._startHlsWithFastestSource(this.playUrls,{restoreTime:i,wasPlaying:a}),e.a(2,!0)}},e,this,[[3,5]])})),function(e){return t.apply(this,arguments)})},{key:"_startHlsWithFastestSource",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=e&&e.length?e:null,i=!!(n&&n.length>1),a=n&&n[0]&&n[0].url||this.options.sourceURL;this.playUrls=n,this.currentLine=this.currentLine||1;var s=r.restoreTime,o=r.wasPlaying,l={},u=function(e,r){!t._destroyed&&e&&(t.hlsInstance&&(HlsPlayer.destroyHlsInstance(t.hlsInstance),t.hlsInstance=null),t.hlsInstance=HlsPlayer.createHlsInstance(t.videoElm,!!(r&&r.length>1),r||[],_objectSpread2$1(_objectSpread2$1({},t.options),{},{m3u8Cache:l})),HlsPlayer.startLoad(t.hlsInstance,e),(s>0&&Number.isFinite(s)||o)&&t.hlsInstance.once(Hls.Events.MANIFEST_PARSED,function(){if(!t._destroyed&&t.videoElm){if(s>0&&Number.isFinite(s))try{t.videoElm.currentTime=s}catch(e){}o&&t.play()}}))};if(i){var c=!1;PlayUrlAble.raceFastestSource(n,function(e,r){if(!c&&!t._destroyed){c=!0,r.content&&(l[e.url]=r.content);var i=PlayUrlAble.putWinnerFirst(n,e);t.playUrls=i,u(e.url,i)}},l).then(function(e){var r=e.winner,i=r?PlayUrlAble.putWinnerFirst(n,r):t.playUrls||n;if(t.playUrls=i,i&&i.length>1&&buildTsMapFromContents(i,l),!c&&!t._destroyed){c=!0;var s=i&&i[0]&&i[0].url||a;u(s,i||n)}}).catch(function(){c||t._destroyed||(c=!0,u(a,n))})}else u(a,n||[])}},{key:"_reloadHlsByLine",value:(e=_asyncToGenerator(_regenerator().m(function e(t){var r,n,i,a,s,o,l,u=this;return _regenerator().w(function(e){for(;;)switch(e.n){case 0:if(r=t.line,n=t.url,i=t.cdnList,a=t.switchCdn,!this._destroyed&&n){e.n=1;break}return e.a(2);case 1:s=this.videoElm?this.videoElm.currentTime:0,o="playing"===this.status||this.videoElm&&!this.videoElm.paused,this.hlsInstance&&(HlsPlayer.destroyHlsInstance(this.hlsInstance),this.hlsInstance=null),this.currentLine=r,ControlLine.changeLineUI(this,r),this.hlsInstance=HlsPlayer.createHlsInstance(this.videoElm,a,i||[],this.options),HlsPlayer.startLoad(this.hlsInstance,n),l=function(){if(!u._destroyed&&u.videoElm){if(s>0&&Number.isFinite(s))try{u.videoElm.currentTime=s}catch(e){}o&&u.play()}},this.hlsInstance.once(Hls.Events.MANIFEST_PARSED,l);case 2:return e.a(2)}},e,this)})),function(t){return e.apply(this,arguments)})}]);var e,t,r,n}(),Events=function(){return _createClass(function e(t){_classCallCheck(this,e),this.target=t,this.eventsQueue={}},[{key:"on",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];this.eventsQueue[e]||(this.eventsQueue[e]={methods:[],onceFlags:[]}),this.eventsQueue[e].methods.includes(t)||(this.eventsQueue[e].methods.push(t),this.eventsQueue[e].onceFlags.push(!!r))}},{key:"once",value:function(e,t){this.on(e,t,!0)}},{key:"emit",value:function(e){for(var t=this,r=arguments.length,n=new Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];var a=this.eventsQueue[e];if(a){var s=a.methods,o=a.onceFlags,l=[],u=[];s.forEach(function(r,i){try{r.apply(t.target,n)}catch(a){console.error("[LivePlayer Events]",e,a)}o[i]||(l.push(r),u.push(!1))}),a.methods=l,a.onceFlags=u}}},{key:"off",value:function(e,t){var r=this.eventsQueue[e];if(r)if(t){var n=r.methods.indexOf(t);n>=0&&(r.methods.splice(n,1),r.onceFlags.splice(n,1)),r.methods.length||delete this.eventsQueue[e]}else delete this.eventsQueue[e]}},{key:"removeAll",value:function(){this.eventsQueue={}}}])}(),LiveUi=function(){function e(){_classCallCheck(this,e)}return _createClass(e,null,[{key:"injectStyle",value:function(){injectPlayerStyle()}},{key:"createVideoElement",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=document.createElement("video");return t.className="ylc-live-player-video",t.setAttribute("playsinline","true"),t.setAttribute("webkit-playsinline","true"),t.muted=!!e.muted,t.autoplay=!!e.autoPlay||!!e.autoplay,t.controls=!1,e.poster&&(t.poster=e.poster),t}},{key:"mount",value:function(t){e.injectStyle();var r=t.options||{},n=parseTemplate(getLiveTemplate({showControls:!!r.controls,muted:!!r.muted})),i=e.createVideoElement(r);return n.insertBefore(i,n.firstChild),t.container=n,t.videoElm=i,t.liveBadge=n.querySelector(".ylc-live-player-badge"),t.statusText=n.querySelector(".ylc-live-player-status"),t.controlBar=n.querySelector(".ylc-live-player-controls"),t.playButton=n.querySelector(".ylc-live-play-button"),t.pauseButton=n.querySelector(".ylc-live-pause-button"),t.volumeButton=n.querySelector(".ylc-live-volume-button"),t.muteButton=n.querySelector(".ylc-live-mute-button"),t.fullScreenButton=n.querySelector(".ylc-live-full-screen-button"),t.exitFullScreenButton=n.querySelector(".ylc-live-exit-full-screen-button"),n}}])}(),WhepClient=function(){return _createClass(function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};_classCallCheck(this,e),this.whepUrl=t.whepUrl||"",this.rtcConfig=t.rtcConfig||{iceServers:[{urls:"stun:stun.l.google.com:19302"}]},this.headers=t.headers||{},this.onPeer=t.onPeer,this.onTrack=t.onTrack,this.onError=t.onError,this.onConnectionState=t.onConnectionState,this.pc=null,this.resourceUrl=null,this._closed=!1},[{key:"start",value:(t=_asyncToGenerator(_regenerator().m(function e(){var t,r,n,i,a,s,o=this;return _regenerator().w(function(e){for(;;)switch(e.n){case 0:if(this.whepUrl){e.n=1;break}throw new Error("whepUrl 不能为空");case 1:return this._closed=!1,this.pc=new RTCPeerConnection(this.rtcConfig),"function"==typeof this.onPeer&&this.onPeer(this.pc),this.pc.addTransceiver("video",{direction:"recvonly"}),this.pc.addTransceiver("audio",{direction:"recvonly"}),this.pc.ontrack=function(e){if("function"==typeof o.onTrack){var t=e.streams&&e.streams[0]?e.streams[0]:new MediaStream([e.track]);o.onTrack(t,e)}},this.pc.onconnectionstatechange=function(){"function"==typeof o.onConnectionState&&o.onConnectionState(o.pc.connectionState),"failed"===o.pc.connectionState&&o._emitError(new Error("WebRTC connection failed"))},e.n=2,this.pc.createOffer();case 2:return t=e.v,e.n=3,this.pc.setLocalDescription(t);case 3:return e.n=4,this._waitIceGatheringComplete(this.pc);case 4:return r=this.pc.localDescription&&this.pc.localDescription.sdp,e.n=5,fetch(this.whepUrl,{method:"POST",headers:_objectSpread2$1({"Content-Type":"application/sdp"},this.headers),body:r});case 5:if((n=e.v).ok){e.n=7;break}return e.n=6,n.text().catch(function(){return""});case 6:throw i=e.v,new Error("WHEP 请求失败 HTTP ".concat(n.status," ").concat(i));case 7:if(a=n.headers.get("Location")||n.headers.get("location"))try{this.resourceUrl=new URL(a,this.whepUrl).toString()}catch(l){this.resourceUrl=a}return e.n=8,n.text();case 8:return s=e.v,e.n=9,this.pc.setRemoteDescription({type:"answer",sdp:s});case 9:return e.a(2,this.pc)}},e,this)})),function(){return t.apply(this,arguments)})},{key:"stop",value:(e=_asyncToGenerator(_regenerator().m(function e(){return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(this._closed=!0,!this.resourceUrl){e.n=5;break}return e.p=1,e.n=2,fetch(this.resourceUrl,{method:"DELETE",headers:_objectSpread2$1({},this.headers)});case 2:e.n=4;break;case 3:e.p=3,e.v;case 4:this.resourceUrl=null;case 5:if(this.pc){try{this.pc.getSenders().forEach(function(e){e.track&&e.track.stop()}),this.pc.getReceivers().forEach(function(e){e.track&&e.track.stop()}),this.pc.close()}catch(t){}this.pc=null}case 6:return e.a(2)}},e,this,[[1,3]])})),function(){return e.apply(this,arguments)})},{key:"_waitIceGatheringComplete",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:3e3;return"complete"===e.iceGatheringState?Promise.resolve():new Promise(function(r){var n=setTimeout(function(){e.removeEventListener("icegatheringstatechange",i),r()},t),i=function(){"complete"===e.iceGatheringState&&(clearTimeout(n),e.removeEventListener("icegatheringstatechange",i),r())};e.addEventListener("icegatheringstatechange",i)})}},{key:"_emitError",value:function(e){this._closed||"function"==typeof this.onError&&this.onError(e)}}]);var e,t}(),WebrtcAdapter=function(){return _createClass(function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};_classCallCheck(this,e),this.video=t.video,this.options=t,this.pc=null,this.whep=null,this.stream=null,this._destroyed=!1},[{key:"start",value:(i=_asyncToGenerator(_regenerator().m(function e(){var t;return _regenerator().w(function(e){for(;;)switch(e.n){case 0:if(!this._destroyed){e.n=1;break}return e.a(2);case 1:if(!this.options.mediaStream){e.n=3;break}return e.n=2,this._attachStream(this.options.mediaStream);case 2:case 5:return this._emit("connected"),e.a(2);case 3:if("function"!=typeof this.options.getStream){e.n=6;break}return e.n=4,this.options.getStream();case 4:return t=e.v,e.n=5,this._attachStream(t);case 6:if(!this.options.whepUrl){e.n=8;break}return e.n=7,this._startWhep();case 7:case 9:case 11:return e.a(2);case 8:if("function"!=typeof this.options.signaling){e.n=10;break}return e.n=9,this._startCustomSignaling();case 10:throw new Error("LivePlayer: 请提供 mediaStream / getStream / whepUrl / signaling 之一")}},e,this)})),function(){return i.apply(this,arguments)})},{key:"_startWhep",value:(n=_asyncToGenerator(_regenerator().m(function e(){var t=this;return _regenerator().w(function(e){for(;;)switch(e.n){case 0:return this.whep=new WhepClient({whepUrl:this.options.whepUrl,rtcConfig:this.options.rtcConfig,headers:this.options.headers,onPeer:function(e){t.pc=e},onTrack:function(e){t._attachStream(e)},onConnectionState:function(e){t._emit("connectionstatechange",{state:e}),"connected"===e&&t._emit("connected"),"disconnected"!==e&&"failed"!==e&&"closed"!==e||t._emit("disconnected",{state:e})},onError:function(e){return t._emit("error",{error:e})}}),e.n=1,this.whep.start();case 1:return e.a(2)}},e,this)})),function(){return n.apply(this,arguments)})},{key:"_startCustomSignaling",value:(r=_asyncToGenerator(_regenerator().m(function e(){var t,r=this;return _regenerator().w(function(e){for(;;)switch(e.n){case 0:return t=this.options.rtcConfig||{iceServers:[{urls:"stun:stun.l.google.com:19302"}]},this.pc=new RTCPeerConnection(t),this.pc.addTransceiver("video",{direction:"recvonly"}),this.pc.addTransceiver("audio",{direction:"recvonly"}),this.pc.ontrack=function(e){var t=e.streams&&e.streams[0]?e.streams[0]:new MediaStream([e.track]);r._attachStream(t)},this.pc.onconnectionstatechange=function(){var e=r.pc.connectionState;r._emit("connectionstatechange",{state:e}),"connected"===e&&r._emit("connected"),"disconnected"!==e&&"failed"!==e&&"closed"!==e||r._emit("disconnected",{state:e})},e.n=1,this.options.signaling(this.pc,{attachStream:function(e){return r._attachStream(e)}});case 1:return e.a(2)}},e,this)})),function(){return r.apply(this,arguments)})},{key:"_attachStream",value:(t=_asyncToGenerator(_regenerator().m(function e(t){var r;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(!this._destroyed&&t){e.n=1;break}return e.a(2);case 1:if(this.stream=t,!this.video){e.n=5;break}return this.video.srcObject=t,e.p=2,e.n=3,this.video.play();case 3:e.n=5;break;case 4:e.p=4,r=e.v,this._emit("autoplayblocked",{error:r});case 5:this._emit("track",{stream:t});case 6:return e.a(2)}},e,this,[[2,4]])})),function(e){return t.apply(this,arguments)})},{key:"getPeerConnection",value:function(){return this.pc}},{key:"getStream",value:function(){return this.stream}},{key:"destroy",value:(e=_asyncToGenerator(_regenerator().m(function e(){return _regenerator().w(function(e){for(;;)switch(e.n){case 0:if(this._destroyed=!0,!this.whep){e.n=2;break}return e.n=1,this.whep.stop();case 1:this.whep=null;case 2:if(this.pc&&!this.whep){try{this.pc.getReceivers().forEach(function(e){e.track&&e.track.stop()}),this.pc.close()}catch(t){}this.pc=null}if(this.stream){try{this.stream.getTracks().forEach(function(e){return e.stop()})}catch(t){}this.stream=null}this.video&&(this.video.srcObject=null);case 3:return e.a(2)}},e,this)})),function(){return e.apply(this,arguments)})},{key:"_emit",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"function"==typeof this.options.onEvent&&this.options.onEvent(_objectSpread2$1({type:e},t))}}]);var e,t,r,n,i}(),LivePlayer=function(){return _createClass(function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};_classCallCheck(this,e),this.containerId=t,this.options=_objectSpread2$1({poster:"",autoPlay:!0,autoplay:!0,controls:!0,muted:!0,protocol:"webrtc",whepUrl:"",mediaStream:null,getStream:null,signaling:null,rtcConfig:null,headers:null},r),this._destroyed=!1,this.status="idle",this.adapter=null,this._docFsHandler=null,this.containerId?(this.el=document.querySelector("#"+t),this.el?(this.events=new Events(this),this.clearPlayer(),this.init()):Logger.error("LivePlayer日志-未查询到节点",{containerId:t})):Logger.error("LivePlayer日志-未传节点id",{containerId:t})},[{key:"init",value:function(){var e=this;Logger.info("LivePlayer日志-开始初始化",{containerId:this.containerId,protocol:this.options.protocol,hasWhep:!!this.options.whepUrl,hasStream:!!this.options.mediaStream,hasGetStream:"function"==typeof this.options.getStream,hasSignaling:"function"==typeof this.options.signaling}),this.createPlayerContainer(),this.bindUiEvents(),this.startLive().catch(function(t){e._handleError(t)})}},{key:"createPlayerContainer",value:function(){this.el.innerHTML="",LiveUi.mount(this),this.statusText&&(this.statusText.textContent="连接中..."),this.el.appendChild(this.container)}},{key:"bindUiEvents",value:function(){var e=this;this.playButton&&(this.playButton.onclick=function(){return e.play()}),this.pauseButton&&(this.pauseButton.onclick=function(){return e.pause()}),this.volumeButton&&(this.volumeButton.onclick=function(){return e.muted(!0)}),this.muteButton&&(this.muteButton.onclick=function(){return e.muted(!1)}),this.fullScreenButton&&(this.fullScreenButton.onclick=function(){return e.requestFullscreen()}),this.exitFullScreenButton&&(this.exitFullScreenButton.onclick=function(){return e.exitFullscreen()}),this.videoElm.addEventListener("playing",function(){e.status="playing",e._syncPlayButtons(),e._setStatusText(""),e.events.emit("playing"),e.events.emit("play")}),this.videoElm.addEventListener("pause",function(){e.status="pause",e._syncPlayButtons(),e.events.emit("pause")}),this.videoElm.addEventListener("waiting",function(){e._setStatusText("加载中..."),e.events.emit("waiting")}),this.videoElm.addEventListener("error",function(){e._handleError(new Error("video element error"))}),this._docFsHandler=function(){return e._syncFullscreenButtons()},document.addEventListener("fullscreenchange",this._docFsHandler),document.addEventListener("webkitfullscreenchange",this._docFsHandler)}},{key:"startLive",value:(r=_asyncToGenerator(_regenerator().m(function e(){var t=this;return _regenerator().w(function(e){for(;;)switch(e.n){case 0:if(!this._destroyed){e.n=1;break}return e.a(2);case 1:return this.adapter=new WebrtcAdapter({video:this.videoElm,mediaStream:this.options.mediaStream,getStream:this.options.getStream,whepUrl:this.options.whepUrl||this.options.sourceURL,rtcConfig:this.options.rtcConfig,headers:this.options.headers,signaling:this.options.signaling,onEvent:function(e){return t._onAdapterEvent(e)}}),this.status="connecting",this._setStatusText("连接中..."),this.events.emit("connecting"),e.n=2,this.adapter.start();case 2:return e.a(2)}},e,this)})),function(){return r.apply(this,arguments)})},{key:"_onAdapterEvent",value:function(e){if(!this._destroyed){var t=e.type;"connected"===t?(this.status="connected",this._setStatusText(""),this.events.emit("connected"),Logger.info("LivePlayer日志-已连接")):"disconnected"===t?(this.status="disconnected",this._setStatusText("已断开"),this.events.emit("disconnected",e),Logger.info("LivePlayer日志-已断开",e)):"connectionstatechange"===t?this.events.emit("connectionstatechange",e):"track"===t?this.events.emit("track",e):"autoplayblocked"===t?(this._setStatusText("点击播放"),this.events.emit("autoplayblocked",e),Logger.info("LivePlayer日志-自动播放被拦截")):"error"===t&&this._handleError(e.error||new Error("rtc error"))}}},{key:"_handleError",value:function(e){var t=e&&e.message?e.message:String(e);this.status="error",this._setStatusText(t),Logger.error("LivePlayer日志-错误",{message:t}),this.events.emit("error",{error:e,message:t})}},{key:"_setStatusText",value:function(e){this.statusText&&(this.statusText.textContent=e||"",this.statusText.style.display=e?"block":"none")}},{key:"_syncPlayButtons",value:function(){if(this.playButton&&this.pauseButton){var e="playing"===this.status;this.playButton.style.display=e?"none":"inline-block",this.pauseButton.style.display=e?"inline-block":"none"}}},{key:"_syncFullscreenButtons",value:function(){if(this.fullScreenButton&&this.exitFullScreenButton){var e=!!(document.fullscreenElement||document.webkitFullscreenElement);this.fullScreenButton.style.display=e?"none":"inline-block",this.exitFullScreenButton.style.display=e?"inline-block":"none"}}},{key:"play",value:function(){var e=this;if(this.videoElm){var t=this.videoElm.play();t&&"function"==typeof t.then&&t.then(function(){e.status="playing",e._syncPlayButtons(),e._setStatusText(""),Logger.info("LivePlayer日志-播放")}).catch(function(t){e._handleError(t)})}}},{key:"pause",value:function(){this.videoElm&&(this.videoElm.pause(),this.status="pause",this._syncPlayButtons(),Logger.info("LivePlayer日志-暂停"))}},{key:"muted",value:function(e){this.videoElm&&(this.videoElm.muted=!!e,this.volumeButton&&this.muteButton&&(this.volumeButton.style.display=e?"none":"inline-block",this.muteButton.style.display=e?"inline-block":"none"),this.events.emit("volumechange",{muted:!!e}))}},{key:"on",value:function(e,t){this.events.on(e,t)}},{key:"once",value:function(e,t){this.events.once(e,t)}},{key:"off",value:function(e,t){this.events.off(e,t)}},{key:"changeSrc",value:(t=_asyncToGenerator(_regenerator().m(function e(t){return _regenerator().w(function(e){for(;;)switch(e.n){case 0:if(!this._destroyed){e.n=1;break}return e.a(2);case 1:if("string"==typeof t?(this.options.whepUrl=t,this.options.sourceURL=t,this.options.mediaStream=null,this.options.getStream=null,this.options.signaling=null):t&&"object"===_typeof(t)&&Object.assign(this.options,t),!this.adapter){e.n=3;break}return e.n=2,this.adapter.destroy();case 2:this.adapter=null;case 3:return this._setStatusText("重新连接..."),e.n=4,this.startLive();case 4:return e.a(2)}},e,this)})),function(e){return t.apply(this,arguments)})},{key:"requestFullscreen",value:function(){var e=this.options.fullscreenElement||this.container||this.el;if(e){var t=e.requestFullscreen||e.webkitRequestFullscreen||e.webkitEnterFullscreen;if(t)try{var r=t.call(e);r&&"function"==typeof r.catch&&r.catch(function(){})}catch(n){this.videoElm&&this.videoElm.webkitEnterFullscreen&&this.videoElm.webkitEnterFullscreen()}this.events.emit("fullscreenchange",{fullscreen:!0})}}},{key:"exitFullscreen",value:function(){var e=document.exitFullscreen||document.webkitExitFullscreen;if(e)try{var t=e.call(document);t&&"function"==typeof t.catch&&t.catch(function(){})}catch(r){}this.events.emit("fullscreenchange",{fullscreen:!1})}},{key:"getPeerConnection",value:function(){return this.adapter?this.adapter.getPeerConnection():null}},{key:"getStream",value:function(){return this.adapter?this.adapter.getStream():null}},{key:"clearPlayer",value:function(){if(this.el){var e=this.el.querySelector("video");if(e)try{e.pause(),e.srcObject=null,e.removeAttribute("src")}catch(t){}this.el.innerHTML=""}}},{key:"destroy",value:(e=_asyncToGenerator(_regenerator().m(function e(){return _regenerator().w(function(e){for(;;)switch(e.n){case 0:if(this._destroyed=!0,this._docFsHandler&&(document.removeEventListener("fullscreenchange",this._docFsHandler),document.removeEventListener("webkitfullscreenchange",this._docFsHandler),this._docFsHandler=null),!this.adapter){e.n=2;break}return e.n=1,this.adapter.destroy();case 1:this.adapter=null;case 2:this.events&&this.events.removeAll(),this.clearPlayer(),this.status="destroyed",Logger.info("LivePlayer日志-已销毁",{containerId:this.containerId});case 3:return e.a(2)}},e,this)})),function(){return e.apply(this,arguments)})}]);var e,t,r}(),fetchVideoUrl=function(){return _createClass(function e(){_classCallCheck(this,e)},null,[{key:"getVideoSignByFileId",value:function(e,t,r){return new Promise(function(n,i){var a=new HttpUtil,s={secret_id:t,secret_key:r,file_id:e};a.post("https://console-api.huaxiacloud.net/third_party/generate/sign",s,"json").then(function(e){n(e)}).catch(function(e){i(e)})})}},{key:"getVideoUrlBySign",value:function(e,t,r,n){return new Promise(function(i,a){var s=new HttpUtil,o={secret_id:t,file_id:String(e),timestamp:String(r),sign:n,client_type:"web"};s.post("https://console-api.huaxiacloud.net/third_party/verify/sign",o,"json").then(function(e){i(e)}).catch(function(e){a(e)})})}}])}(),PROXY_METHODS=["play","pause","seek","currentTimeSec","duration","changeSrc","muted","changeSpeed","switchLine","on","off","uploadPlayerLogs","requestFullscreen","exitFullscreen"];function isPlainObject(e){return!!e&&"object"===_typeof(e)&&1!==e.nodeType&&!Array.isArray(e)}function parseContainer(e){if(!e)return{id:"",el:null};if("string"==typeof e){var t=e.replace(/^#/,"");return{id:t,el:"undefined"!=typeof document?document.querySelector("#"+t):null}}return 1===e.nodeType?(e.id||(e.id="hx-player-"+Date.now()),{id:e.id,el:e}):{id:"",el:null}}function normalizeOptions(){var e=_objectSpread2$1({},arguments.length>0&&void 0!==arguments[0]?arguments[0]:{});return e.url&&!e.sourceURL&&(e.sourceURL=e.url),null!=e.autoplay&&null==e.autoPlay&&(e.autoPlay=e.autoplay),e}function isLiveOptions(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return"live"===e.mode||("webrtc"===e.protocol||"rtc"===e.protocol||(!!e.whepUrl||!(!e.mediaStream&&"function"!=typeof e.getStream&&"function"!=typeof e.signaling)))}function detectMediaType(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return(e.sourceURL||"").includes(".m3u8")?isIosEnvironment()&&!e.isEncrypt?{type:"VIDEO"}:{type:"HLS"}:{type:"VIDEO"}}var HxPlayer=function(){function e(t){var r=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};_classCallCheck(this,e),isPlainObject(t)&&(t.id||t.el||t.container||t.url||t.sourceURL||t.fileId||t.whepUrl||t.mode)&&(t=(n=_objectSpread2$1(_objectSpread2$1({},t),n)).id||n.el||n.container);var i=parseContainer(t);this.containerId=i.id,this.el=i.el,this.options=normalizeOptions(n),this._player=null,this._destroyed=!1;var a=e._instances.get(this.containerId);a&&a!==this&&"function"==typeof a.destroy&&a.destroy(),this.containerId&&e._instances.set(this.containerId,this),this._seq=(e._createSeq.get(this.containerId)||0)+1,e._createSeq.set(this.containerId,this._seq),this.ready=this._bootstrap(),PROXY_METHODS.forEach(function(e){r[e]=function(){for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];return r._call.apply(r,[e].concat(n))}})}return _createClass(e,[{key:"player",get:function(){return this._player}},{key:"video",get:function(){return this._player&&this._player.videoElm}},{key:"_bootstrap",value:(t=_asyncToGenerator(_regenerator().m(function t(){var r,n,i,a,s,o,l,u;return _regenerator().w(function(t){for(;;)switch(t.p=t.n){case 0:if(t.p=0,Logger.info("HxPlayer日志-创建播放器实例",{containerId:this.containerId,options:_objectSpread2$1(_objectSpread2$1({},this.options),{},{fullscreenElement:""})}),LogWebSocket.connect({userId:this.options.fansId||this.options.userId||this.options.user_id||"",terminal:this.options.terminal||LogWebSocket.detectTerminal()}).catch(function(e){console.warn("[HxPlayer] LogWebSocket 连接失败",e)}),Logger.setAppContext({appId:this.options.appId,fansId:this.options.fansId}),this.options.sourceURL||!this.options.fileId||!this.options.secret_id){t.n=2;break}return t.n=1,fetchVideoUrl.getVideoUrlBySign(this.options.fileId,this.options.secret_id,this.options.timestamp,this.options.sign);case 1:r=t.v,n=r.code,i=r.data,a=i.play_url,s=i.encrypt_type,o=i.encrypted_data,200===n&&(this.options.sourceURL=a,this.options.url=a,this.options.isEncrypt=1===s,this.options.encryptedData=o);case 2:if(!this._destroyed){t.n=3;break}return t.a(2,this);case 3:if(!this.containerId||e._createSeq.get(this.containerId)===this._seq){t.n=4;break}return Logger.info("HxPlayer日志-检测到更新的实例,放弃本次初始化",{containerId:this.containerId,seq:this._seq}),t.a(2,this);case 4:if(!isLiveOptions(this.options)){t.n=5;break}this._player=new LivePlayer(this.containerId,this.options),t.n=7;break;case 5:if(l=detectMediaType(this.options),!this._destroyed){t.n=6;break}return t.a(2,this);case 6:this._player=new VideoPlayer(this.containerId,_objectSpread2$1(_objectSpread2$1({},this.options),{},{isSupportHls:"HLS"===l.type}));case 7:return t.a(2,this);case 8:throw t.p=8,u=t.v,console.log("HxPlayer日志-播放器初始化失败",u),Logger.error("HxPlayer日志-播放器初始化失败",{error:u&&u.message?u.message:String(u)}),u;case 9:return t.a(2)}},t,this,[[0,8]])})),function(){return t.apply(this,arguments)})},{key:"_call",value:function(e){for(var t=this,r=arguments.length,n=new Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];return"destroy"===e?this.destroy():this.ready.then(function(){if(!t._destroyed&&t._player){var r=t._player[e];return"function"==typeof r?r.apply(t._player,n):void 0}})}},{key:"setPlaybackRate",value:function(e){return this._call("changeSpeed",{value:e})}},{key:"destroy",value:function(){this._destroyed=!0,this._player&&"function"==typeof this._player.destroy&&this._player.destroy(),this._player=null,this.containerId&&e._instances.get(this.containerId)===this&&e._instances.delete(this.containerId)}}]);var t}();_defineProperty$1(HxPlayer,"_instances",new Map),_defineProperty$1(HxPlayer,"_createSeq",new Map),HxPlayer.VideoPlayer=VideoPlayer,HxPlayer.LivePlayer=LivePlayer,HxPlayer.Hls=Hls,HxPlayer.version="1.0.0","undefined"!=typeof window&&(window.HxPlayer=HxPlayer);export{Hls,HxPlayer,LivePlayer,VideoPlayer,HxPlayer as default};"undefined"!=typeof globalThis&&globalThis.HxPlayer&&globalThis.HxPlayer.HxPlayer&&(globalThis.HxPlayer=globalThis.HxPlayer.default||globalThis.HxPlayer.HxPlayer);
2
+ //# sourceMappingURL=hx-player.js.map