hr-design-system-handlebars 1.114.139 → 1.114.141
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +24 -0
- package/dist/assets/index.css +6 -3
- package/dist/assets/js/components/external-service/externalServiceDs.feature.js +25 -1
- package/dist/assets/js/components/mediaplayer/ardPlayerLoader.subfeature.js +2 -2
- package/dist/assets/vendor/ardplayer/{ardplayer-SANDLibrary.6faa2a2b.chunk.js → ardplayer-SANDLibrary.1a644373.chunk.js} +17 -72
- package/dist/assets/vendor/ardplayer/ardplayer-hr-7.2.0.07145e1b.js +1 -0
- package/dist/assets/vendor/ardplayer/ardplayer-hr-7.2.0.bdf782df.css +1 -0
- package/dist/assets/vendor/ardplayer/ardplayer-libimsc.34d59351.chunk.js +12 -0
- package/dist/assets/vendor/ardplayer/ardplayer-pluginchromecast.017a470e.chunk.js +1 -0
- package/dist/assets/vendor/ardplayer/ardplayer-plugindash.6abc107d.chunk.js +10 -0
- package/dist/assets/vendor/ardplayer/ardplayer-pluginhls.e7b33d74.chunk.js +1 -0
- package/dist/assets/vendor/ardplayer/ardplayer-pluginhtmla.7a21b373.chunk.js +1 -0
- package/dist/assets/vendor/ardplayer/ardplayer-pluginhtmlv.8e08609e.chunk.js +1 -0
- package/dist/assets/vendor/ardplayer/assets/47bf64197ce0a282ef55-ardplayer-audio.woff +0 -0
- package/dist/assets/vendor/ardplayer/assets/553e21224d0386ee58f0-ardplayer.woff +0 -0
- package/dist/assets/vendor/ardplayer/assets/img/sr-f5ae5aae.svg +1 -0
- package/package.json +1 -1
- package/src/assets/fixtures/audio/audios.inc.json +8 -8
- package/src/assets/fixtures/content/copytext/copytext_externalservice.json +4 -202
- package/src/assets/fixtures/external-service/external_service.inc.json +28 -0
- package/src/assets/fixtures/page/podcast/podcast_player_episode.json +4 -4
- package/src/assets/fixtures/video/videos.inc.json +8 -8
- package/src/assets/vendor/ardplayer/{ardplayer-SANDLibrary.6faa2a2b.chunk.js → ardplayer-SANDLibrary.1a644373.chunk.js} +17 -72
- package/src/assets/vendor/ardplayer/ardplayer-hr-7.2.0.07145e1b.js +1 -0
- package/src/assets/vendor/ardplayer/ardplayer-hr-7.2.0.bdf782df.css +1 -0
- package/src/assets/vendor/ardplayer/ardplayer-libimsc.34d59351.chunk.js +12 -0
- package/src/assets/vendor/ardplayer/ardplayer-pluginchromecast.017a470e.chunk.js +1 -0
- package/src/assets/vendor/ardplayer/ardplayer-plugindash.6abc107d.chunk.js +10 -0
- package/src/assets/vendor/ardplayer/ardplayer-pluginhls.e7b33d74.chunk.js +1 -0
- package/src/assets/vendor/ardplayer/ardplayer-pluginhtmla.7a21b373.chunk.js +1 -0
- package/src/assets/vendor/ardplayer/ardplayer-pluginhtmlv.8e08609e.chunk.js +1 -0
- package/src/assets/vendor/ardplayer/assets/47bf64197ce0a282ef55-ardplayer-audio.woff +0 -0
- package/src/assets/vendor/ardplayer/assets/553e21224d0386ee58f0-ardplayer.woff +0 -0
- package/src/assets/vendor/ardplayer/assets/img/dolby_atmos_horizontal-469f0a42.png +0 -0
- package/src/assets/vendor/ardplayer/assets/img/sr-f5ae5aae.svg +1 -0
- package/src/assets/vendor/ardplayer/schema/MediaCollection.v1.json +36 -1
- package/src/stories/views/components/content/copytext/fixtures/copytext_audio-livestream.json +8 -8
- package/src/stories/views/components/content/copytext/fixtures/copytext_audio.json +1 -1
- package/src/stories/views/components/content/copytext/fixtures/copytext_audio_livestream.json +1 -1
- package/src/stories/views/components/content/copytext/fixtures/copytext_externalservice.json +1 -1
- package/src/stories/views/components/content/copytext/fixtures/copytext_image.json +1 -1
- package/src/stories/views/components/content/copytext/fixtures/copytext_livestream.json +1 -1
- package/src/stories/views/components/content/copytext/fixtures/copytext_media_components.json +1 -1
- package/src/stories/views/components/content/copytext/fixtures/copytext_non_media_components.json +1 -1
- package/src/stories/views/components/content/copytext/fixtures/copytext_podcastepisode.json +1 -1
- package/src/stories/views/components/content/copytext/fixtures/copytext_video.json +1 -1
- package/src/stories/views/components/content/copytext/fixtures/copytext_video_vertical.json +1 -1
- package/src/stories/views/components/external-service/externalServiceDs.feature.js +25 -1
- package/src/stories/views/components/mediaplayer/ardPlayerLoader.subfeature.js +2 -2
- package/src/stories/views/components/mediaplayer/fixtures/mediaplayer.json +1 -1
- package/src/stories/views/components/mediaplayer/fixtures/mediaplayer_snapshots.json +1 -1
- package/src/stories/views/components/page/fixtures/page.json +1 -1
- package/src/stories/views/components/page/podcast/fixtures/podcast_player_episode.json +1 -1
- package/src/stories/views/components/page/podcast/fixtures/podcast_player_playlist.json +1 -1
- package/src/stories/views/components/page/story/fixtures/story.json +1 -1
- package/src/stories/views/components/page/story/fixtures/story_with_audio.json +1 -1
- package/src/stories/views/components/page/story/fixtures/story_with_label.json +1 -1
- package/src/stories/views/components/page/story/fixtures/story_with_livestream.json +1 -1
- package/src/stories/views/components/page/story/fixtures/story_with_square_image.json +1 -1
- package/src/stories/views/components/page/story/fixtures/story_with_video.json +1 -1
- package/src/stories/views/components/pagination/fixtures/page_pagination.json +1 -1
- package/src/stories/views/components/teaser/fixtures/teaser_alternative_av.json +1 -1
- package/src/stories/views/components/teaser/fixtures/teaser_cluster.json +1 -1
- package/src/stories/views/components/teaser/fixtures/teaser_group_100.json +1 -1
- package/src/stories/views/components/teaser/fixtures/teaser_group_100_highlight.json +1 -1
- package/src/stories/views/components/teaser/fixtures/teaser_group_100_highlight_2.json +1 -1
- package/src/stories/views/components/teaser/fixtures/teaser_group_related_content_100.json +1 -1
- package/src/stories/views/components/teaser/fixtures/teaser_index.json +1 -1
- package/src/stories/views/components/teaser/fixtures/teaser_podcast.json +1 -1
- package/src/stories/views/components/teaser/fixtures/teaser_podcast_50.json +1 -1
- package/src/stories/views/components/teaser/fixtures/teaser_podcast_playlist.json +1 -1
- package/src/stories/views/components/teaser/fixtures/teaser_podcast_playlist_50.json +1 -1
- package/src/stories/views/components/teaser/fixtures/teaser_podcast_playlist_filter.json +1 -1
- package/src/stories/views/components/teaser/fixtures/teaser_standard_av.json +1 -1
- package/src/stories/views/components/teaser/fixtures/teaser_tabbox.json +1 -1
- package/src/stories/views/components/teaser/fixtures/teaser_ticker_alternative.json +1 -1
- package/src/stories/views/components/teaser/fixtures/teaser_ticker_standard.json +1 -1
- package/src/stories/views/components/teaser/fixtures/teaser_vertical_video.json +1 -1
- package/src/stories/views/components/voting/fixtures/voting.json +1 -1
- package/src/stories/views/components/voting/fixtures/voting_media_audio_horizontal.json +1 -1
- package/src/stories/views/components/voting/fixtures/voting_media_audio_vertical.json +1 -1
- package/src/stories/views/components/voting/fixtures/voting_media_video_horizontal.json +1 -1
- package/src/stories/views/components/voting/fixtures/voting_media_video_vertical.json +1 -1
- package/dist/assets/vendor/ardplayer/ardplayer-hr-6.9.2.3be63dd6.css +0 -1
- package/dist/assets/vendor/ardplayer/ardplayer-hr-6.9.2.930e5d37.js +0 -1
- package/dist/assets/vendor/ardplayer/ardplayer-libimsc.94ff92e7.chunk.js +0 -12
- package/dist/assets/vendor/ardplayer/ardplayer-pluginchromecast.064b468f.chunk.js +0 -1
- package/dist/assets/vendor/ardplayer/ardplayer-plugindash.f3029c65.chunk.js +0 -10
- package/dist/assets/vendor/ardplayer/ardplayer-pluginhls.d2363d5c.chunk.js +0 -1
- package/dist/assets/vendor/ardplayer/ardplayer-pluginhtmla.fc2a72c0.chunk.js +0 -1
- package/dist/assets/vendor/ardplayer/ardplayer-pluginhtmlv.90153612.chunk.js +0 -1
- package/dist/assets/vendor/ardplayer/assets/c760ddea7c5679abc52d-ardplayer.woff +0 -0
- package/dist/assets/vendor/ardplayer/assets/d45e654a921039ff64c9-ardplayer-audio.woff +0 -0
- package/dist/assets/vendor/ardplayer/assets/img/sr-63f113c4.svg +0 -1
- package/src/assets/vendor/ardplayer/ardplayer-hr-6.9.2.3be63dd6.css +0 -1
- package/src/assets/vendor/ardplayer/ardplayer-hr-6.9.2.930e5d37.js +0 -1
- package/src/assets/vendor/ardplayer/ardplayer-libimsc.94ff92e7.chunk.js +0 -12
- package/src/assets/vendor/ardplayer/ardplayer-pluginchromecast.064b468f.chunk.js +0 -1
- package/src/assets/vendor/ardplayer/ardplayer-plugindash.f3029c65.chunk.js +0 -10
- package/src/assets/vendor/ardplayer/ardplayer-pluginhls.d2363d5c.chunk.js +0 -1
- package/src/assets/vendor/ardplayer/ardplayer-pluginhtmla.fc2a72c0.chunk.js +0 -1
- package/src/assets/vendor/ardplayer/ardplayer-pluginhtmlv.90153612.chunk.js +0 -1
- package/src/assets/vendor/ardplayer/assets/c760ddea7c5679abc52d-ardplayer.woff +0 -0
- package/src/assets/vendor/ardplayer/assets/d45e654a921039ff64c9-ardplayer-audio.woff +0 -0
- package/src/assets/vendor/ardplayer/assets/img/sr-63f113c4.svg +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
(globalThis.webpackChunkardplayer=globalThis.webpackChunkardplayer||[]).push([[965],{39473:module=>{!function t(e){module.exports=function(){"use strict";function i(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),i.push.apply(i,r)}return i}function r(t){for(var e=1;e<arguments.length;e++){var r=null!=arguments[e]?arguments[e]:{};e%2?i(Object(r),!0).forEach((function(e){l(t,e,r[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):i(Object(r)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(r,e))}))}return t}function s(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var r=i.call(t,e||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}function n(t){var e=s(t,"string");return"symbol"==typeof e?e:String(e)}function a(t,e){for(var i=0;i<e.length;i++){var r=e[i];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,n(r.key),r)}}function o(t,e,i){return e&&a(t.prototype,e),i&&a(t,i),Object.defineProperty(t,"prototype",{writable:!1}),t}function l(t,e,i){return(e=n(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function h(){return h=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var r in i)Object.prototype.hasOwnProperty.call(i,r)&&(t[r]=i[r])}return t},h.apply(this,arguments)}function d(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,c(t,e)}function u(t){return u=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},u(t)}function c(t,e){return c=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},c(t,e)}function f(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}function g(t,e,i){return g=f()?Reflect.construct.bind():function(t,e,i){var r=[null];r.push.apply(r,e);var s=new(Function.bind.apply(t,r));return i&&c(s,i.prototype),s},g.apply(null,arguments)}function m(t){try{return-1!==Function.toString.call(t).indexOf("[native code]")}catch(e){return"function"==typeof t}}function p(t){var e="function"==typeof Map?new Map:void 0;return p=function(t){if(null===t||!m(t))return t;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,i)}function i(){return g(t,arguments,u(this).constructor)}return i.prototype=Object.create(t.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),c(i,t)},p(t)}function v(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function y(t,e){if(t){if("string"==typeof t)return E(t,e);var i=Object.prototype.toString.call(t).slice(8,-1);return"Object"===i&&t.constructor&&(i=t.constructor.name),"Map"===i||"Set"===i?Array.from(t):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?E(t,e):void 0}}function E(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,r=new Array(e);i<e;i++)r[i]=t[i];return r}function T(t,e){var i="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(i)return(i=i.call(t)).next.bind(i);if(Array.isArray(t)||(i=y(t))||e&&t&&"number"==typeof t.length){i&&(t=i);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function S(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var A={exports:{}};!function(module){var t,e,i,r,s;t=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,e=/^(?=([^\/?#]*))\1([^]*)$/,i=/(?:\/|^)\.(?=\/)/g,r=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,s={buildAbsoluteURL:function(t,i,r){if(r=r||{},t=t.trim(),!(i=i.trim())){if(!r.alwaysNormalize)return t;var n=s.parseURL(t);if(!n)throw new Error("Error trying to parse base URL.");return n.path=s.normalizePath(n.path),s.buildURLFromParts(n)}var a=s.parseURL(i);if(!a)throw new Error("Error trying to parse relative URL.");if(a.scheme)return r.alwaysNormalize?(a.path=s.normalizePath(a.path),s.buildURLFromParts(a)):i;var o=s.parseURL(t);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=e.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var h={scheme:o.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(h.netLoc=o.netLoc,"/"!==a.path[0]))if(a.path){var d=o.path,u=d.substring(0,d.lastIndexOf("/")+1)+a.path;h.path=s.normalizePath(u)}else h.path=o.path,a.params||(h.params=o.params,a.query||(h.query=o.query));return null===h.path&&(h.path=r.alwaysNormalize?s.normalizePath(a.path):a.path),s.buildURLFromParts(h)},parseURL:function(e){var i=t.exec(e);return i?{scheme:i[1]||"",netLoc:i[2]||"",path:i[3]||"",params:i[4]||"",query:i[5]||"",fragment:i[6]||""}:null},normalizePath:function(t){for(t=t.split("").reverse().join("").replace(i,"");t.length!==(t=t.replace(r,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}},module.exports=s}(A);var L=A.exports,R=Number.isFinite||function(t){return"number"==typeof t&&isFinite(t)},b=Number.isSafeInteger||function(t){return"number"==typeof t&&Math.abs(t)<=k},k=Number.MAX_SAFE_INTEGER||9007199254740991,D=function(t){return t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.BUFFER_RESET="hlsBufferReset",t.BUFFER_CODECS="hlsBufferCodecs",t.BUFFER_CREATED="hlsBufferCreated",t.BUFFER_APPENDING="hlsBufferAppending",t.BUFFER_APPENDED="hlsBufferAppended",t.BUFFER_EOS="hlsBufferEos",t.BUFFER_FLUSHING="hlsBufferFlushing",t.BUFFER_FLUSHED="hlsBufferFlushed",t.MANIFEST_LOADING="hlsManifestLoading",t.MANIFEST_LOADED="hlsManifestLoaded",t.MANIFEST_PARSED="hlsManifestParsed",t.LEVEL_SWITCHING="hlsLevelSwitching",t.LEVEL_SWITCHED="hlsLevelSwitched",t.LEVEL_LOADING="hlsLevelLoading",t.LEVEL_LOADED="hlsLevelLoaded",t.LEVEL_UPDATED="hlsLevelUpdated",t.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",t.LEVELS_UPDATED="hlsLevelsUpdated",t.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",t.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",t.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",t.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",t.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",t.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",t.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",t.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",t.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",t.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",t.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",t.CUES_PARSED="hlsCuesParsed",t.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",t.INIT_PTS_FOUND="hlsInitPtsFound",t.FRAG_LOADING="hlsFragLoading",t.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",t.FRAG_LOADED="hlsFragLoaded",t.FRAG_DECRYPTED="hlsFragDecrypted",t.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",t.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",t.FRAG_PARSING_METADATA="hlsFragParsingMetadata",t.FRAG_PARSED="hlsFragParsed",t.FRAG_BUFFERED="hlsFragBuffered",t.FRAG_CHANGED="hlsFragChanged",t.FPS_DROP="hlsFpsDrop",t.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",t.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",t.ERROR="hlsError",t.DESTROYING="hlsDestroying",t.KEY_LOADING="hlsKeyLoading",t.KEY_LOADED="hlsKeyLoaded",t.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",t.BACK_BUFFER_REACHED="hlsBackBufferReached",t.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",t}({}),I=function(t){return t.NETWORK_ERROR="networkError",t.MEDIA_ERROR="mediaError",t.KEY_SYSTEM_ERROR="keySystemError",t.MUX_ERROR="muxError",t.OTHER_ERROR="otherError",t}({}),w=function(t){return t.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",t.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",t.KEY_SYSTEM_NO_SESSION="keySystemNoSession",t.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",t.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",t.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",t.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",t.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",t.MANIFEST_LOAD_ERROR="manifestLoadError",t.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",t.MANIFEST_PARSING_ERROR="manifestParsingError",t.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",t.LEVEL_EMPTY_ERROR="levelEmptyError",t.LEVEL_LOAD_ERROR="levelLoadError",t.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",t.LEVEL_PARSING_ERROR="levelParsingError",t.LEVEL_SWITCH_ERROR="levelSwitchError",t.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",t.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",t.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",t.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",t.FRAG_LOAD_ERROR="fragLoadError",t.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",t.FRAG_DECRYPT_ERROR="fragDecryptError",t.FRAG_PARSING_ERROR="fragParsingError",t.FRAG_GAP="fragGap",t.REMUX_ALLOC_ERROR="remuxAllocError",t.KEY_LOAD_ERROR="keyLoadError",t.KEY_LOAD_TIMEOUT="keyLoadTimeOut",t.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",t.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",t.BUFFER_APPEND_ERROR="bufferAppendError",t.BUFFER_APPENDING_ERROR="bufferAppendingError",t.BUFFER_STALLED_ERROR="bufferStalledError",t.BUFFER_FULL_ERROR="bufferFullError",t.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",t.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",t.INTERNAL_EXCEPTION="internalException",t.INTERNAL_ABORTED="aborted",t.UNKNOWN="unknown",t}({}),C=function(){},_={trace:C,debug:C,log:C,warn:C,info:C,error:C},P=_;function x(t){var e=self.console[t];return e?e.bind(self.console,"["+t+"] >"):C}function M(t){for(var e=arguments.length,i=new Array(e>1?e-1:0),r=1;r<e;r++)i[r-1]=arguments[r];i.forEach((function(e){P[e]=t[e]?t[e].bind(t):x(e)}))}function O(t,e){if("object"==typeof console&&!0===t||"object"==typeof t){M(t,"debug","log","info","warn","error");try{P.log('Debug logs enabled for "'+e+'" in hls.js version 1.5.14')}catch(t){P=_}}else P=_}var F=P,N=/^(\d+)x(\d+)$/,U=/(.+?)=(".*?"|.*?)(?:,|$)/g,B=function(){function t(e){"string"==typeof e&&(e=t.parseAttrList(e)),h(this,e)}var e=t.prototype;return e.decimalInteger=function(t){var e=parseInt(this[t],10);return e>Number.MAX_SAFE_INTEGER?1/0:e},e.hexadecimalInteger=function(t){if(this[t]){var e=(this[t]||"0x").slice(2);e=(1&e.length?"0":"")+e;for(var i=new Uint8Array(e.length/2),r=0;r<e.length/2;r++)i[r]=parseInt(e.slice(2*r,2*r+2),16);return i}return null},e.hexadecimalIntegerAsNumber=function(t){var e=parseInt(this[t],16);return e>Number.MAX_SAFE_INTEGER?1/0:e},e.decimalFloatingPoint=function(t){return parseFloat(this[t])},e.optionalFloat=function(t,e){var i=this[t];return i?parseFloat(i):e},e.enumeratedString=function(t){return this[t]},e.bool=function(t){return"YES"===this[t]},e.decimalResolution=function(t){var e=N.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}},t.parseAttrList=function(t){var e,i={},r='"';for(U.lastIndex=0;null!==(e=U.exec(t));){var s=e[2];0===s.indexOf(r)&&s.lastIndexOf(r)===s.length-1&&(s=s.slice(1,-1)),i[e[1].trim()]=s}return i},o(t,[{key:"clientAttrs",get:function(){return Object.keys(this).filter((function(t){return"X-"===t.substring(0,2)}))}}]),t}();function G(t){return"ID"!==t&&"CLASS"!==t&&"START-DATE"!==t&&"DURATION"!==t&&"END-DATE"!==t&&"END-ON-NEXT"!==t}function K(t){return"SCTE35-OUT"===t||"SCTE35-IN"===t}var H=function(){function t(t,e){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,e){var i=e.attr;for(var r in i)if(Object.prototype.hasOwnProperty.call(t,r)&&t[r]!==i[r]){F.warn('DATERANGE tag attribute: "'+r+'" does not match for tags with ID: "'+t.ID+'"'),this._badValueForSameId=r;break}t=h(new B({}),i,t)}if(this.attr=t,this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){var s=new Date(this.attr["END-DATE"]);R(s.getTime())&&(this._endDate=s)}}return o(t,[{key:"id",get:function(){return this.attr.ID}},{key:"class",get:function(){return this.attr.CLASS}},{key:"startDate",get:function(){return this._startDate}},{key:"endDate",get:function(){if(this._endDate)return this._endDate;var t=this.duration;return null!==t?new Date(this._startDate.getTime()+1e3*t):null}},{key:"duration",get:function(){if("DURATION"in this.attr){var t=this.attr.decimalFloatingPoint("DURATION");if(R(t))return t}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:"isValid",get:function(){return!!this.id&&!this._badValueForSameId&&R(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)}}]),t}(),$=function(){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}},V={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"},Y=function(){function t(t){var e;this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams=((e={})[V.AUDIO]=null,e[V.VIDEO]=null,e[V.AUDIOVIDEO]=null,e),this.baseurl=t}return t.prototype.setByteRange=function(t,e){var i,r=t.split("@",2);i=1===r.length?(null==e?void 0:e.byteRangeEndOffset)||0:parseInt(r[1]),this._byteRange=[i,parseInt(r[0])+i]},o(t,[{key:"byteRange",get:function(){return this._byteRange?this._byteRange:[]}},{key:"byteRangeStartOffset",get:function(){return this.byteRange[0]}},{key:"byteRangeEndOffset",get:function(){return this.byteRange[1]}},{key:"url",get:function(){return!this._url&&this.baseurl&&this.relurl&&(this._url=L.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""},set:function(t){this._url=t}}]),t}(),W=function(t){function e(e,i){var r;return(r=t.call(this,i)||this)._decryptdata=null,r.rawProgramDateTime=null,r.programDateTime=null,r.tagList=[],r.duration=0,r.sn=0,r.levelkeys=void 0,r.type=void 0,r.loader=null,r.keyLoader=null,r.level=-1,r.cc=0,r.startPTS=void 0,r.endPTS=void 0,r.startDTS=void 0,r.endDTS=void 0,r.start=0,r.deltaPTS=void 0,r.maxStartPTS=void 0,r.minEndPTS=void 0,r.stats=new $,r.data=void 0,r.bitrateTest=!1,r.title=null,r.initSegment=null,r.endList=void 0,r.gap=void 0,r.urlId=0,r.type=e,r}d(e,t);var i=e.prototype;return i.setKeyFormat=function(t){if(this.levelkeys){var e=this.levelkeys[t];e&&!this._decryptdata&&(this._decryptdata=e.getDecryptData(this.sn))}},i.abortRequests=function(){var t,e;null==(t=this.loader)||t.abort(),null==(e=this.keyLoader)||e.abort()},i.setElementaryStreamInfo=function(t,e,i,r,s,n){void 0===n&&(n=!1);var a=this.elementaryStreams,o=a[t];o?(o.startPTS=Math.min(o.startPTS,e),o.endPTS=Math.max(o.endPTS,i),o.startDTS=Math.min(o.startDTS,r),o.endDTS=Math.max(o.endDTS,s)):a[t]={startPTS:e,endPTS:i,startDTS:r,endDTS:s,partial:n}},i.clearElementaryStreamInfo=function(){var t=this.elementaryStreams;t[V.AUDIO]=null,t[V.VIDEO]=null,t[V.AUDIOVIDEO]=null},o(e,[{key:"decryptdata",get:function(){if(!this.levelkeys&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){var t=this.levelkeys.identity;if(t)this._decryptdata=t.getDecryptData(this.sn);else{var e=Object.keys(this.levelkeys);if(1===e.length)return this._decryptdata=this.levelkeys[e[0]].getDecryptData(this.sn)}}return this._decryptdata}},{key:"end",get:function(){return this.start+this.duration}},{key:"endProgramDateTime",get:function(){if(null===this.programDateTime)return null;if(!R(this.programDateTime))return null;var t=R(this.duration)?this.duration:0;return this.programDateTime+1e3*t}},{key:"encrypted",get:function(){var t;if(null!=(t=this._decryptdata)&&t.encrypted)return!0;if(this.levelkeys){var e=Object.keys(this.levelkeys),i=e.length;if(i>1||1===i&&this.levelkeys[e[0]].encrypted)return!0}return!1}}]),e}(Y),j=function(t){function e(e,i,r,s,n){var a;(a=t.call(this,r)||this).fragOffset=0,a.duration=0,a.gap=!1,a.independent=!1,a.relurl=void 0,a.fragment=void 0,a.index=void 0,a.stats=new $,a.duration=e.decimalFloatingPoint("DURATION"),a.gap=e.bool("GAP"),a.independent=e.bool("INDEPENDENT"),a.relurl=e.enumeratedString("URI"),a.fragment=i,a.index=s;var o=e.enumeratedString("BYTERANGE");return o&&a.setByteRange(o,n),n&&(a.fragOffset=n.fragOffset+n.duration),a}return d(e,t),o(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 t=this.elementaryStreams;return!!(t.audio||t.video||t.audiovideo)}}]),e}(Y),q=10,X=function(){function t(t){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.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 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.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=t}return t.prototype.reloaded=function(t){if(!t)return this.advanced=!0,void(this.updated=!0);var e=this.lastPartSn-t.lastPartSn,i=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!i||!!e||!this.live,this.advanced=this.endSN>t.endSN||e>0||0===e&&i>0,this.updated||this.advanced?this.misses=Math.floor(.6*t.misses):this.misses=t.misses+1,this.availabilityDelay=t.availabilityDelay},o(t,[{key:"hasProgramDateTime",get:function(){return!!this.fragments.length&&R(this.fragments[this.fragments.length-1].programDateTime)}},{key:"levelTargetDuration",get:function(){return this.averagetargetduration||this.targetduration||q}},{key:"drift",get:function(){var t=this.driftEndTime-this.driftStartTime;return t>0?1e3*(this.driftEnd-this.driftStart)/t:1}},{key:"edge",get:function(){return this.partEnd||this.fragmentEnd}},{key:"partEnd",get:function(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}},{key:"fragmentEnd",get:function(){var t;return null!=(t=this.fragments)&&t.length?this.fragments[this.fragments.length-1].end:0}},{key:"age",get:function(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}},{key:"lastPartIndex",get:function(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].index:-1}},{key:"lastPartSn",get:function(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}]),t}();function z(t){return Uint8Array.from(atob(t),(function(t){return t.charCodeAt(0)}))}function Q(t){var e=tt(t).subarray(0,16),i=new Uint8Array(16);return i.set(e,16-e.length),i}function J(t){var e=function(t,e,i){var r=t[e];t[e]=t[i],t[i]=r};e(t,0,3),e(t,1,2),e(t,4,5),e(t,6,7)}function Z(t){var e=t.split(":"),i=null;if("data"===e[0]&&2===e.length){var r=e[1].split(";"),s=r[r.length-1].split(",");if(2===s.length){var n="base64"===s[0],a=s[1];n?(r.splice(-1,1),i=z(a)):i=Q(a)}}return i}function tt(t){return Uint8Array.from(unescape(encodeURIComponent(t)),(function(t){return t.charCodeAt(0)}))}var et="undefined"!=typeof self?self:void 0,it={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},rt={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function st(t){switch(t){case rt.FAIRPLAY:return it.FAIRPLAY;case rt.PLAYREADY:return it.PLAYREADY;case rt.WIDEVINE:return it.WIDEVINE;case rt.CLEARKEY:return it.CLEARKEY}}var nt={WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function at(t){if(t===nt.WIDEVINE)return it.WIDEVINE}function ot(t){switch(t){case it.FAIRPLAY:return rt.FAIRPLAY;case it.PLAYREADY:return rt.PLAYREADY;case it.WIDEVINE:return rt.WIDEVINE;case it.CLEARKEY:return rt.CLEARKEY}}function lt(t){var e=t.drmSystems,i=t.widevineLicenseUrl,r=e?[it.FAIRPLAY,it.WIDEVINE,it.PLAYREADY,it.CLEARKEY].filter((function(t){return!!e[t]})):[];return!r[it.WIDEVINE]&&i&&r.push(it.WIDEVINE),r}var ht,dt=null!=et&&null!=(ht=et.navigator)&&ht.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function ut(t,e,i,r){var s;switch(t){case it.FAIRPLAY:s=["cenc","sinf"];break;case it.WIDEVINE:case it.PLAYREADY:s=["cenc"];break;case it.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error("Unknown key-system: "+t)}return ct(s,e,i,r)}function ct(t,e,i,r){return[{initDataTypes:t,persistentState:r.persistentState||"optional",distinctiveIdentifier:r.distinctiveIdentifier||"optional",sessionTypes:r.sessionTypes||[r.sessionType||"temporary"],audioCapabilities:e.map((function(t){return{contentType:'audio/mp4; codecs="'+t+'"',robustness:r.audioRobustness||"",encryptionScheme:r.audioEncryptionScheme||null}})),videoCapabilities:i.map((function(t){return{contentType:'video/mp4; codecs="'+t+'"',robustness:r.videoRobustness||"",encryptionScheme:r.videoEncryptionScheme||null}}))}]}function ft(t,e,i){return Uint8Array.prototype.slice?t.slice(e,i):new Uint8Array(Array.prototype.slice.call(t,e,i))}var gt,mt=function(t,e){return e+10<=t.length&&73===t[e]&&68===t[e+1]&&51===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128},pt=function(t,e){return e+10<=t.length&&51===t[e]&&68===t[e+1]&&73===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128},vt=function(t,e){for(var i=e,r=0;mt(t,e);)r+=10,r+=yt(t,e+6),pt(t,e+10)&&(r+=10),e+=r;if(r>0)return t.subarray(i,i+r)},yt=function(t,e){var i=0;return i=(127&t[e])<<21,i|=(127&t[e+1])<<14,i|=(127&t[e+2])<<7,i|=127&t[e+3]},Et=function(t,e){return mt(t,e)&&yt(t,e+6)+10<=t.length-e},Tt=function(t){for(var e=Lt(t),i=0;i<e.length;i++){var r=e[i];if(St(r))return It(r)}},St=function(t){return t&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info},At=function(t){var e=String.fromCharCode(t[0],t[1],t[2],t[3]),i=yt(t,4),r=10;return{type:e,size:i,data:t.subarray(r,r+i)}},Lt=function(t){for(var e=0,i=[];mt(t,e);){for(var r=yt(t,e+6),s=(e+=10)+r;e+8<s;){var n=At(t.subarray(e)),a=Rt(n);a&&i.push(a),e+=n.size+10}pt(t,e)&&(e+=10)}return i},Rt=function(t){return"PRIV"===t.type?bt(t):"W"===t.type[0]?Dt(t):kt(t)},bt=function(t){if(!(t.size<2)){var e=wt(t.data,!0),i=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:i.buffer}}},kt=function(t){if(!(t.size<2)){if("TXXX"===t.type){var e=1,i=wt(t.data.subarray(e),!0);e+=i.length+1;var r=wt(t.data.subarray(e));return{key:t.type,info:i,data:r}}var s=wt(t.data.subarray(1));return{key:t.type,data:s}}},Dt=function(t){if("WXXX"===t.type){if(t.size<2)return;var e=1,i=wt(t.data.subarray(e),!0);e+=i.length+1;var r=wt(t.data.subarray(e));return{key:t.type,info:i,data:r}}var s=wt(t.data);return{key:t.type,data:s}},It=function(t){if(8===t.data.byteLength){var e=new Uint8Array(t.data),i=1&e[3],r=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return r/=45,i&&(r+=47721858.84),Math.round(r)}},wt=function(t,e){void 0===e&&(e=!1);var i=Ct();if(i){var r=i.decode(t);if(e){var s=r.indexOf("\0");return-1!==s?r.substring(0,s):r}return r.replace(/\0/g,"")}for(var n,a,o,l=t.length,h="",d=0;d<l;){if(0===(n=t[d++])&&e)return h;if(0!==n&&3!==n)switch(n>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:h+=String.fromCharCode(n);break;case 12:case 13:a=t[d++],h+=String.fromCharCode((31&n)<<6|63&a);break;case 14:a=t[d++],o=t[d++],h+=String.fromCharCode((15&n)<<12|(63&a)<<6|63&o)}}return h};function Ct(){if(!navigator.userAgent.includes("PlayStation 4"))return gt||void 0===self.TextDecoder||(gt=new self.TextDecoder("utf-8")),gt}var _t={hexDump:function(t){for(var e="",i=0;i<t.length;i++){var r=t[i].toString(16);r.length<2&&(r="0"+r),e+=r}return e}},Pt=Math.pow(2,32)-1,xt=[].push,Mt={video:1,audio:2,id3:3,text:4};function Ot(t){return String.fromCharCode.apply(null,t)}function Ft(t,e){var i=t[e]<<8|t[e+1];return i<0?65536+i:i}function Nt(t,e){var i=Bt(t,e);return i<0?4294967296+i:i}function Ut(t,e){var i=Nt(t,e);return i*=Math.pow(2,32),i+=Nt(t,e+4)}function Bt(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function Gt(t,e,i){t[e]=i>>24,t[e+1]=i>>16&255,t[e+2]=i>>8&255,t[e+3]=255&i}function Kt(t){for(var e=t.byteLength,i=0;i<e;){var r=Nt(t,i);if(r>8&&109===t[i+4]&&111===t[i+5]&&111===t[i+6]&&102===t[i+7])return!0;i=r>1?i+r:e}return!1}function Ht(t,e){var i=[];if(!e.length)return i;for(var r=t.byteLength,s=0;s<r;){var n=Nt(t,s),a=n>1?s+n:r;if(Ot(t.subarray(s+4,s+8))===e[0])if(1===e.length)i.push(t.subarray(s+8,a));else{var o=Ht(t.subarray(s+8,a),e.slice(1));o.length&&xt.apply(i,o)}s=a}return i}function $t(t){var e=[],i=t[0],r=8,s=Nt(t,r);r+=4;var n=0,a=0;0===i?(n=Nt(t,r),a=Nt(t,r+4),r+=8):(n=Ut(t,r),a=Ut(t,r+8),r+=16),r+=2;var o=t.length+a,l=Ft(t,r);r+=2;for(var h=0;h<l;h++){var d=r,u=Nt(t,d);d+=4;var c=2147483647&u;if(1==(2147483648&u)>>>31)return F.warn("SIDX has hierarchical references (not supported)"),null;var f=Nt(t,d);d+=4,e.push({referenceSize:c,subsegmentDuration:f,info:{duration:f/s,start:o,end:o+c-1}}),o+=c,r=d+=4}return{earliestPresentationTime:n,timescale:s,version:i,referencesCount:l,references:e}}function Vt(t){for(var e=[],i=Ht(t,["moov","trak"]),s=0;s<i.length;s++){var n=i[s],a=Ht(n,["tkhd"])[0];if(a){var o=a[0],l=Nt(a,0===o?12:20),h=Ht(n,["mdia","mdhd"])[0];if(h){var d=Nt(h,0===(o=h[0])?12:20),u=Ht(n,["mdia","hdlr"])[0];if(u){var c=Ot(u.subarray(8,12)),f={soun:V.AUDIO,vide:V.VIDEO}[c];if(f){var g=Yt(Ht(n,["mdia","minf","stbl","stsd"])[0]);e[l]={timescale:d,type:f},e[f]=r({timescale:d,id:l},g)}}}}}return Ht(t,["moov","mvex","trex"]).forEach((function(t){var i=Nt(t,4),r=e[i];r&&(r.default={duration:Nt(t,12),flags:Nt(t,20)})})),e}function Yt(t){var e=t.subarray(8),i=e.subarray(86),r=Ot(e.subarray(4,8)),s=r,n="enca"===r||"encv"===r;if(n){var a=Ht(e,[r])[0];Ht(a.subarray("enca"===r?28:78),["sinf"]).forEach((function(t){var e=Ht(t,["schm"])[0];if(e){var i=Ot(e.subarray(4,8));if("cbcs"===i||"cenc"===i){var r=Ht(t,["frma"])[0];r&&(s=Ot(r))}}}))}switch(s){case"avc1":case"avc2":case"avc3":case"avc4":var o=Ht(i,["avcC"])[0];s+="."+jt(o[1])+jt(o[2])+jt(o[3]);break;case"mp4a":var l=Ht(e,[r])[0],h=Ht(l.subarray(28),["esds"])[0];if(h&&h.length>12){var d=4;if(3!==h[d++])break;d=Wt(h,d),d+=2;var u=h[d++];if(128&u&&(d+=2),64&u&&(d+=h[d++]),4!==h[d++])break;d=Wt(h,d);var c=h[d++];if(64!==c)break;if(s+="."+jt(c),d+=12,5!==h[d++])break;d=Wt(h,d);var f=h[d++],g=(248&f)>>3;31===g&&(g+=1+((7&f)<<3)+((224&h[d])>>5)),s+="."+g}break;case"hvc1":case"hev1":var m=Ht(i,["hvcC"])[0],p=m[1],v=["","A","B","C"][p>>6],y=31&p,E=Nt(m,2),T=(32&p)>>5?"H":"L",S=m[12],A=m.subarray(6,12);s+="."+v+y,s+="."+E.toString(16).toUpperCase(),s+="."+T+S;for(var L="",R=A.length;R--;){var b=A[R];(b||L)&&(L="."+b.toString(16).toUpperCase()+L)}s+=L;break;case"dvh1":case"dvhe":var k=Ht(i,["dvcC"])[0],D=k[2]>>1&127,I=k[2]<<5&32|k[3]>>3&31;s+="."+qt(D)+"."+qt(I);break;case"vp09":var w=Ht(i,["vpcC"])[0],C=w[4],_=w[5],P=w[6]>>4&15;s+="."+qt(C)+"."+qt(_)+"."+qt(P);break;case"av01":var x=Ht(i,["av1C"])[0],M=x[1]>>>5,O=31&x[1],F=x[2]>>>7?"H":"M",N=(64&x[2])>>6,U=(32&x[2])>>5,B=2===M&&N?U?12:10:N?10:8,G=(16&x[2])>>4,K=(8&x[2])>>3,H=(4&x[2])>>2,$=3&x[2],V=1,Y=1,W=1,j=0;s+="."+M+"."+qt(O)+F+"."+qt(B)+"."+G+"."+K+H+$+"."+qt(V)+"."+qt(Y)+"."+qt(W)+"."+j}return{codec:s,encrypted:n}}function Wt(t,e){for(var i=e+5;128&t[e++]&&e<i;);return e}function jt(t){return("0"+t.toString(16).toUpperCase()).slice(-2)}function qt(t){return(t<10?"0":"")+t}function Xt(t,e){if(!t||!e)return t;var i=e.keyId;return i&&e.isCommonEncryption&&Ht(t,["moov","trak"]).forEach((function(t){var e=Ht(t,["mdia","minf","stbl","stsd"])[0].subarray(8),r=Ht(e,["enca"]),s=r.length>0;s||(r=Ht(e,["encv"])),r.forEach((function(t){Ht(s?t.subarray(28):t.subarray(78),["sinf"]).forEach((function(t){var e=zt(t);if(e){var r=e.subarray(8,24);r.some((function(t){return 0!==t}))||(F.log("[eme] Patching keyId in 'enc"+(s?"a":"v")+">sinf>>tenc' box: "+_t.hexDump(r)+" -> "+_t.hexDump(i)),e.set(i,8))}}))}))})),t}function zt(t){var e=Ht(t,["schm"])[0];if(e){var i=Ot(e.subarray(4,8));if("cbcs"===i||"cenc"===i)return Ht(t,["schi","tenc"])[0]}return F.error("[eme] missing 'schm' box"),null}function Qt(t,e){return Ht(e,["moof","traf"]).reduce((function(e,i){var r=Ht(i,["tfdt"])[0],s=r[0],n=Ht(i,["tfhd"]).reduce((function(e,i){var n=Nt(i,4),a=t[n];if(a){var o=Nt(r,4);if(1===s){if(o===Pt)return F.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),e;o*=Pt+1,o+=Nt(r,8)}var l=o/(a.timescale||9e4);if(R(l)&&(null===e||l<e))return l}return e}),null);return null!==n&&R(n)&&(null===e||n<e)?n:e}),null)}function Jt(t,e){for(var i=0,r=0,s=0,n=Ht(t,["moof","traf"]),a=0;a<n.length;a++){var o=n[a],l=Ht(o,["tfhd"])[0],h=e[Nt(l,4)];if(h){var d=h.default,u=Nt(l,0)|(null==d?void 0:d.flags),c=null==d?void 0:d.duration;8&u&&(c=Nt(l,2&u?12:8));for(var f=h.timescale||9e4,g=Ht(o,["trun"]),m=0;m<g.length;m++)!(i=Zt(g[m]))&&c&&(i=c*Nt(g[m],4)),h.type===V.VIDEO?r+=i/f:h.type===V.AUDIO&&(s+=i/f)}}if(0===r&&0===s){for(var p=1/0,v=0,y=0,E=Ht(t,["sidx"]),T=0;T<E.length;T++){var S=$t(E[T]);if(null!=S&&S.references){p=Math.min(p,S.earliestPresentationTime/S.timescale);var A=S.references.reduce((function(t,e){return t+e.info.duration||0}),0);y=(v=Math.max(v,A+S.earliestPresentationTime/S.timescale))-p}}if(y&&R(y))return y}return r||s}function Zt(t){var e=Nt(t,0),i=8;1&e&&(i+=4),4&e&&(i+=4);for(var r=0,s=Nt(t,4),n=0;n<s;n++)256&e&&(r+=Nt(t,i),i+=4),512&e&&(i+=4),1024&e&&(i+=4),2048&e&&(i+=4);return r}function te(t,e,i){Ht(e,["moof","traf"]).forEach((function(e){Ht(e,["tfhd"]).forEach((function(r){var s=Nt(r,4),n=t[s];if(n){var a=n.timescale||9e4;Ht(e,["tfdt"]).forEach((function(t){var e=t[0],r=i*a;if(r){var s=Nt(t,4);if(0===e)s-=r,Gt(t,4,s=Math.max(s,0));else{s*=Math.pow(2,32),s+=Nt(t,8),s-=r,s=Math.max(s,0);var n=Math.floor(s/(Pt+1)),o=Math.floor(s%(Pt+1));Gt(t,4,n),Gt(t,8,o)}}}))}}))}))}function ee(t){var e={valid:null,remainder:null},i=Ht(t,["moof"]);if(i.length<2)return e.remainder=t,e;var r=i[i.length-1];return e.valid=ft(t,0,r.byteOffset-8),e.remainder=ft(t,r.byteOffset-8),e}function ie(t,e){var i=new Uint8Array(t.length+e.length);return i.set(t),i.set(e,t.length),i}function re(t,e){var i=[],r=e.samples,s=e.timescale,n=e.id,a=!1;return Ht(r,["moof"]).map((function(o){var l=o.byteOffset-8;Ht(o,["traf"]).map((function(o){var h=Ht(o,["tfdt"]).map((function(t){var e=t[0],i=Nt(t,4);return 1===e&&(i*=Math.pow(2,32),i+=Nt(t,8)),i/s}))[0];return void 0!==h&&(t=h),Ht(o,["tfhd"]).map((function(h){var d=Nt(h,4),u=16777215&Nt(h,0),c=0,f=!!(16&u),g=0,m=!!(32&u),p=8;d===n&&(!!(1&u)&&(p+=8),!!(2&u)&&(p+=4),!!(8&u)&&(c=Nt(h,p),p+=4),f&&(g=Nt(h,p),p+=4),m&&(p+=4),"video"===e.type&&(a=se(e.codec)),Ht(o,["trun"]).map((function(n){var o=n[0],h=16777215&Nt(n,0),d=!!(1&h),u=0,f=!!(4&h),m=!!(256&h),p=0,v=!!(512&h),y=0,E=!!(1024&h),T=!!(2048&h),S=0,A=Nt(n,4),L=8;d&&(u=Nt(n,L),L+=4),f&&(L+=4);for(var R=u+l,b=0;b<A;b++){if(m?(p=Nt(n,L),L+=4):p=c,v?(y=Nt(n,L),L+=4):y=g,E&&(L+=4),T&&(S=0===o?Nt(n,L):Bt(n,L),L+=4),e.type===V.VIDEO)for(var k=0;k<y;){var D=Nt(r,R);ne(a,r[R+=4])&&ae(r.subarray(R,R+D),a?2:1,t+S/s,i),R+=D,k+=D+4}t+=p/s}})))}))}))})),i}function se(t){if(!t)return!1;var e=t.indexOf("."),i=e<0?t:t.substring(0,e);return"hvc1"===i||"hev1"===i||"dvh1"===i||"dvhe"===i}function ne(t,e){if(t){var i=e>>1&63;return 39===i||40===i}return 6==(31&e)}function ae(t,e,i,r){var s=oe(t),n=0;n+=e;for(var a=0,o=0,l=0;n<s.length;){a=0;do{if(n>=s.length)break;a+=l=s[n++]}while(255===l);o=0;do{if(n>=s.length)break;o+=l=s[n++]}while(255===l);var h=s.length-n,d=n;if(o<h)n+=o;else if(o>h){F.error("Malformed SEI payload. "+o+" is too small, only "+h+" bytes left to parse.");break}if(4===a){if(181===s[d++]){var u=Ft(s,d);if(d+=2,49===u){var c=Nt(s,d);if(d+=4,1195456820===c){var f=s[d++];if(3===f){var g=s[d++],m=64&g,p=m?2+3*(31&g):0,v=new Uint8Array(p);if(m){v[0]=g;for(var y=1;y<p;y++)v[y]=s[d++]}r.push({type:f,payloadType:a,pts:i,bytes:v})}}}}}else if(5===a&&o>16){for(var E=[],T=0;T<16;T++){var S=s[d++].toString(16);E.push(1==S.length?"0"+S:S),3!==T&&5!==T&&7!==T&&9!==T||E.push("-")}for(var A=o-16,L=new Uint8Array(A),R=0;R<A;R++)L[R]=s[d++];r.push({payloadType:a,pts:i,uuid:E.join(""),userData:wt(L),userDataBytes:L})}}}function oe(t){for(var e=t.byteLength,i=[],r=1;r<e-2;)0===t[r]&&0===t[r+1]&&3===t[r+2]?(i.push(r+2),r+=2):r++;if(0===i.length)return t;var s=e-i.length,n=new Uint8Array(s),a=0;for(r=0;r<s;a++,r++)a===i[0]&&(a++,i.shift()),n[r]=t[a];return n}function le(t){var e=t[0],i="",r="",s=0,n=0,a=0,o=0,l=0,h=0;if(0===e){for(;"\0"!==Ot(t.subarray(h,h+1));)i+=Ot(t.subarray(h,h+1)),h+=1;for(i+=Ot(t.subarray(h,h+1)),h+=1;"\0"!==Ot(t.subarray(h,h+1));)r+=Ot(t.subarray(h,h+1)),h+=1;r+=Ot(t.subarray(h,h+1)),h+=1,s=Nt(t,12),n=Nt(t,16),o=Nt(t,20),l=Nt(t,24),h=28}else if(1===e){s=Nt(t,h+=4);var d=Nt(t,h+=4),u=Nt(t,h+=4);for(h+=4,a=Math.pow(2,32)*d+u,b(a)||(a=Number.MAX_SAFE_INTEGER,F.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=Nt(t,h),l=Nt(t,h+=4),h+=4;"\0"!==Ot(t.subarray(h,h+1));)i+=Ot(t.subarray(h,h+1)),h+=1;for(i+=Ot(t.subarray(h,h+1)),h+=1;"\0"!==Ot(t.subarray(h,h+1));)r+=Ot(t.subarray(h,h+1)),h+=1;r+=Ot(t.subarray(h,h+1)),h+=1}return{schemeIdUri:i,value:r,timeScale:s,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:t.subarray(h,t.byteLength)}}function he(t){for(var e=arguments.length,i=new Array(e>1?e-1:0),r=1;r<e;r++)i[r-1]=arguments[r];for(var s=i.length,n=8,a=s;a--;)n+=i[a].byteLength;var o=new Uint8Array(n);for(o[0]=n>>24&255,o[1]=n>>16&255,o[2]=n>>8&255,o[3]=255&n,o.set(t,4),a=0,n=8;a<s;a++)o.set(i[a],n),n+=i[a].byteLength;return o}function de(t,e,i){if(16!==t.byteLength)throw new RangeError("Invalid system id");var r,s,n;if(e){r=1,s=new Uint8Array(16*e.length);for(var a=0;a<e.length;a++){var o=e[a];if(16!==o.byteLength)throw new RangeError("Invalid key");s.set(o,16*a)}}else r=0,s=new Uint8Array;r>0?(n=new Uint8Array(4),e.length>0&&new DataView(n.buffer).setUint32(0,e.length,!1)):n=new Uint8Array;var l=new Uint8Array(4);return i&&i.byteLength>0&&new DataView(l.buffer).setUint32(0,i.byteLength,!1),he([112,115,115,104],new Uint8Array([r,0,0,0]),t,n,s,l,i||new Uint8Array)}function ue(t){if(!(t instanceof ArrayBuffer)||t.byteLength<32)return null;var e={version:0,systemId:"",kids:null,data:null},i=new DataView(t),r=i.getUint32(0);if(t.byteLength!==r&&r>44)return null;if(1886614376!==i.getUint32(4))return null;if(e.version=i.getUint32(8)>>>24,e.version>1)return null;e.systemId=_t.hexDump(new Uint8Array(t,12,16));var s=i.getUint32(28);if(0===e.version){if(r-32<s)return null;e.data=new Uint8Array(t,32,s)}else if(1===e.version){e.kids=[];for(var n=0;n<s;n++)e.kids.push(new Uint8Array(t,32+16*n,16))}return e}var ce={},fe=function(){function t(t,e,i,r,s){void 0===r&&(r=[1]),void 0===s&&(s=null),this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=t,this.uri=e,this.keyFormat=i,this.keyFormatVersions=r,this.iv=s,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&"AES-128"!==t}t.clearKeyUriToKeyIdMap=function(){ce={}};var e=t.prototype;return e.isSupported=function(){if(this.method){if("AES-128"===this.method||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case rt.FAIRPLAY:case rt.WIDEVINE:case rt.PLAYREADY:case rt.CLEARKEY:return-1!==["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1},e.getDecryptData=function(e){if(!this.encrypted||!this.uri)return null;if("AES-128"===this.method&&this.uri&&!this.iv){"number"!=typeof e&&("AES-128"!==this.method||this.iv||F.warn('missing IV for initialization segment with method="'+this.method+'" - compliance issue'),e=0);var i=ge(e);return new t(this.method,this.uri,"identity",this.keyFormatVersions,i)}var r=Z(this.uri);if(r)switch(this.keyFormat){case rt.WIDEVINE:this.pssh=r,r.length>=22&&(this.keyId=r.subarray(r.length-22,r.length-6));break;case rt.PLAYREADY:var s=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=de(s,null,r);var n=new Uint16Array(r.buffer,r.byteOffset,r.byteLength/2),a=String.fromCharCode.apply(null,Array.from(n)),o=a.substring(a.indexOf("<"),a.length),l=(new DOMParser).parseFromString(o,"text/xml").getElementsByTagName("KID")[0];if(l){var h=l.childNodes[0]?l.childNodes[0].nodeValue:l.getAttribute("VALUE");if(h){var d=z(h).subarray(0,16);J(d),this.keyId=d}}break;default:var u=r.subarray(0,16);if(16!==u.length){var c=new Uint8Array(16);c.set(u,16-u.length),u=c}this.keyId=u}if(!this.keyId||16!==this.keyId.byteLength){var f=ce[this.uri];if(!f){var g=Object.keys(ce).length%Number.MAX_SAFE_INTEGER;f=new Uint8Array(16),new DataView(f.buffer,12,4).setUint32(0,g),ce[this.uri]=f}this.keyId=f}return this},t}();function ge(t){for(var e=new Uint8Array(16),i=12;i<16;i++)e[i]=t>>8*(15-i)&255;return e}var me=/\{\$([a-zA-Z0-9-_]+)\}/g;function pe(t){return me.test(t)}function ve(t,e,i){if(null!==t.variableList||t.hasVariableRefs)for(var r=i.length;r--;){var s=i[r],n=e[s];n&&(e[s]=ye(t,n))}}function ye(t,e){if(null!==t.variableList||t.hasVariableRefs){var i=t.variableList;return e.replace(me,(function(e){var r=e.substring(2,e.length-1),s=null==i?void 0:i[r];return void 0===s?(t.playlistParsingError||(t.playlistParsingError=new Error('Missing preceding EXT-X-DEFINE tag for Variable Reference: "'+r+'"')),e):s}))}return e}function Ee(t,e,i){var r,s,n=t.variableList;if(n||(t.variableList=n={}),"QUERYPARAM"in e){r=e.QUERYPARAM;try{var a=new self.URL(i).searchParams;if(!a.has(r))throw new Error('"'+r+'" does not match any query parameter in URI: "'+i+'"');s=a.get(r)}catch(e){t.playlistParsingError||(t.playlistParsingError=new Error("EXT-X-DEFINE QUERYPARAM: "+e.message))}}else r=e.NAME,s=e.VALUE;r in n?t.playlistParsingError||(t.playlistParsingError=new Error('EXT-X-DEFINE duplicate Variable Name declarations: "'+r+'"')):n[r]=s||""}function Te(t,e,i){var r=e.IMPORT;if(i&&r in i){var s=t.variableList;s||(t.variableList=s={}),s[r]=i[r]}else t.playlistParsingError||(t.playlistParsingError=new Error('EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "'+r+'"'))}function Se(t){if(void 0===t&&(t=!0),"undefined"!=typeof self)return(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Ae(t){return"undefined"!=typeof self&&t===self.ManagedMediaSource}var Le={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,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function Re(t,e){var i=Le[e];return!!i&&!!i[t.slice(0,4)]}function be(t,e,i){return void 0===i&&(i=!0),!t.split(",").some((function(t){return!ke(t,e,i)}))}function ke(t,e,i){var r;void 0===i&&(i=!0);var s=Se(i);return null!=(r=null==s?void 0:s.isTypeSupported(De(t,e)))&&r}function De(t,e){return e+'/mp4;codecs="'+t+'"'}function Ie(t){if(t){var e=t.substring(0,4);return Le.video[e]}return 2}function we(t){return t.split(",").reduce((function(t,e){var i=Le.video[e];return i?(2*i+t)/(t?3:2):(Le.audio[e]+t)/(t?2:1)}),0)}var Ce={};function _e(t,e){if(void 0===e&&(e=!0),Ce[t])return Ce[t];for(var i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"]}[t],r=0;r<i.length;r++)if(ke(i[r],"audio",e))return Ce[t]=i[r],i[r];return t}var Pe=/flac|opus/i;function xe(t,e){return void 0===e&&(e=!0),t.replace(Pe,(function(t){return _e(t.toLowerCase(),e)}))}function Me(t,e){return t&&"mp4a"!==t?t:e?e.split(",")[0]:e}function Oe(t){for(var e=t.split(","),i=0;i<e.length;i++){var r=e[i].split(".");if(r.length>2){var s=r.shift()+".";s+=parseInt(r.shift()).toString(16),s+=("000"+parseInt(r.shift()).toString(16)).slice(-4),e[i]=s}}return e.join(",")}var Fe=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,Ne=/#EXT-X-MEDIA:(.*)/g,Ue=/^#EXT(?:INF|-X-TARGETDURATION):/m,Be=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),Ge=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|")),Ke=function(){function t(){}return t.findGroup=function(t,e){for(var i=0;i<t.length;i++){var r=t[i];if(r.id===e)return r}},t.resolve=function(t,e){return L.buildAbsoluteURL(e,t,{alwaysNormalize:!0})},t.isMediaPlaylist=function(t){return Ue.test(t)},t.parseMasterPlaylist=function(e,i){var r,s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:pe(e)},n=[];for(Fe.lastIndex=0;null!=(r=Fe.exec(e));)if(r[1]){var a,o=new B(r[1]);ve(s,o,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);var l=ye(s,r[2]),h={attrs:o,bitrate:o.decimalInteger("BANDWIDTH")||o.decimalInteger("AVERAGE-BANDWIDTH"),name:o.NAME,url:t.resolve(l,i)},d=o.decimalResolution("RESOLUTION");d&&(h.width=d.width,h.height=d.height),Ve(o.CODECS,h),null!=(a=h.unknownCodecs)&&a.length||n.push(h),s.levels.push(h)}else if(r[3]){var u=r[3],c=r[4];switch(u){case"SESSION-DATA":var f=new B(c);ve(s,f,["DATA-ID","LANGUAGE","VALUE","URI"]);var g=f["DATA-ID"];g&&(null===s.sessionData&&(s.sessionData={}),s.sessionData[g]=f);break;case"SESSION-KEY":var m=He(c,i,s);m.encrypted&&m.isSupported()?(null===s.sessionKeys&&(s.sessionKeys=[]),s.sessionKeys.push(m)):F.warn('[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "'+c+'"');break;case"DEFINE":var p=new B(c);ve(s,p,["NAME","VALUE","QUERYPARAM"]),Ee(s,p,i);break;case"CONTENT-STEERING":var v=new B(c);ve(s,v,["SERVER-URI","PATHWAY-ID"]),s.contentSteering={uri:t.resolve(v["SERVER-URI"],i),pathwayId:v["PATHWAY-ID"]||"."};break;case"START":s.startTimeOffset=$e(c)}}var y=n.length>0&&n.length<s.levels.length;return s.levels=y?n:s.levels,0===s.levels.length&&(s.playlistParsingError=new Error("no levels found in manifest")),s},t.parseMasterPlaylistMedia=function(e,i,r){var s,n={},a=r.levels,o={AUDIO:a.map((function(t){return{id:t.attrs.AUDIO,audioCodec:t.audioCodec}})),SUBTITLES:a.map((function(t){return{id:t.attrs.SUBTITLES,textCodec:t.textCodec}})),"CLOSED-CAPTIONS":[]},l=0;for(Ne.lastIndex=0;null!==(s=Ne.exec(e));){var h=new B(s[1]),d=h.TYPE;if(d){var u=o[d],c=n[d]||[];n[d]=c,ve(r,h,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);var f=h.LANGUAGE,g=h["ASSOC-LANGUAGE"],m=h.CHANNELS,p=h.CHARACTERISTICS,v=h["INSTREAM-ID"],y={attrs:h,bitrate:0,id:l++,groupId:h["GROUP-ID"]||"",name:h.NAME||f||"",type:d,default:h.bool("DEFAULT"),autoselect:h.bool("AUTOSELECT"),forced:h.bool("FORCED"),lang:f,url:h.URI?t.resolve(h.URI,i):""};if(g&&(y.assocLang=g),m&&(y.channels=m),p&&(y.characteristics=p),v&&(y.instreamId=v),null!=u&&u.length){var E=t.findGroup(u,y.groupId)||u[0];Ye(y,E,"audioCodec"),Ye(y,E,"textCodec")}c.push(y)}}return n},t.parseLevelPlaylist=function(t,e,i,r,s,n){var a,o,l,d=new X(e),u=d.fragments,c=null,f=0,g=0,m=0,p=0,v=null,y=new W(r,e),E=-1,T=!1,S=null;for(Be.lastIndex=0,d.m3u8=t,d.hasVariableRefs=pe(t);null!==(a=Be.exec(t));){T&&(T=!1,(y=new W(r,e)).start=m,y.sn=f,y.cc=p,y.level=i,c&&(y.initSegment=c,y.rawProgramDateTime=c.rawProgramDateTime,c.rawProgramDateTime=null,S&&(y.setByteRange(S),S=null)));var A=a[1];if(A){y.duration=parseFloat(A);var L=(" "+a[2]).slice(1);y.title=L||null,y.tagList.push(L?["INF",A,L]:["INF",A])}else if(a[3]){if(R(y.duration)){y.start=m,l&&Xe(y,l,d),y.sn=f,y.level=i,y.cc=p,u.push(y);var b=(" "+a[3]).slice(1);y.relurl=ye(d,b),je(y,v),v=y,m+=y.duration,f++,g=0,T=!0}}else if(a[4]){var k=(" "+a[4]).slice(1);v?y.setByteRange(k,v):y.setByteRange(k)}else if(a[5])y.rawProgramDateTime=(" "+a[5]).slice(1),y.tagList.push(["PROGRAM-DATE-TIME",y.rawProgramDateTime]),-1===E&&(E=u.length);else{if(!(a=a[0].match(Ge))){F.warn("No matches on slow regex match for level playlist!");continue}for(o=1;o<a.length&&void 0===a[o];o++);var D=(" "+a[o]).slice(1),I=(" "+a[o+1]).slice(1),w=a[o+2]?(" "+a[o+2]).slice(1):"";switch(D){case"PLAYLIST-TYPE":d.type=I.toUpperCase();break;case"MEDIA-SEQUENCE":f=d.startSN=parseInt(I);break;case"SKIP":var C=new B(I);ve(d,C,["RECENTLY-REMOVED-DATERANGES"]);var _=C.decimalInteger("SKIPPED-SEGMENTS");if(R(_)){d.skippedSegments=_;for(var P=_;P--;)u.unshift(null);f+=_}var x=C.enumeratedString("RECENTLY-REMOVED-DATERANGES");x&&(d.recentlyRemovedDateranges=x.split("\t"));break;case"TARGETDURATION":d.targetduration=Math.max(parseInt(I),1);break;case"VERSION":d.version=parseInt(I);break;case"INDEPENDENT-SEGMENTS":case"EXTM3U":break;case"ENDLIST":d.live=!1;break;case"#":(I||w)&&y.tagList.push(w?[I,w]:[I]);break;case"DISCONTINUITY":p++,y.tagList.push(["DIS"]);break;case"GAP":y.gap=!0,y.tagList.push([D]);break;case"BITRATE":y.tagList.push([D,I]);break;case"DATERANGE":var M=new B(I);ve(d,M,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),ve(d,M,M.clientAttrs);var O=new H(M,d.dateRanges[M.ID]);O.isValid||d.skippedSegments?d.dateRanges[O.id]=O:F.warn('Ignoring invalid DATERANGE tag: "'+I+'"'),y.tagList.push(["EXT-X-DATERANGE",I]);break;case"DEFINE":var N=new B(I);ve(d,N,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in N?Te(d,N,n):Ee(d,N,e);break;case"DISCONTINUITY-SEQUENCE":p=parseInt(I);break;case"KEY":var U=He(I,e,d);if(U.isSupported()){if("NONE"===U.method){l=void 0;break}l||(l={}),l[U.keyFormat]&&(l=h({},l)),l[U.keyFormat]=U}else F.warn('[Keys] Ignoring invalid EXT-X-KEY tag: "'+I+'"');break;case"START":d.startTimeOffset=$e(I);break;case"MAP":var G=new B(I);if(ve(d,G,["BYTERANGE","URI"]),y.duration){var K=new W(r,e);qe(K,G,i,l),c=K,y.initSegment=c,c.rawProgramDateTime&&!y.rawProgramDateTime&&(y.rawProgramDateTime=c.rawProgramDateTime)}else{var $=y.byteRangeEndOffset;if($){var V=y.byteRangeStartOffset;S=$-V+"@"+V}else S=null;qe(y,G,i,l),c=y,T=!0}break;case"SERVER-CONTROL":var Y=new B(I);d.canBlockReload=Y.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=Y.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&Y.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=Y.optionalFloat("PART-HOLD-BACK",0),d.holdBack=Y.optionalFloat("HOLD-BACK",0);break;case"PART-INF":var q=new B(I);d.partTarget=q.decimalFloatingPoint("PART-TARGET");break;case"PART":var z=d.partList;z||(z=d.partList=[]);var Q=g>0?z[z.length-1]:void 0,J=g++,Z=new B(I);ve(d,Z,["BYTERANGE","URI"]);var tt=new j(Z,y,e,J,Q);z.push(tt),y.duration+=tt.duration;break;case"PRELOAD-HINT":var et=new B(I);ve(d,et,["URI"]),d.preloadHint=et;break;case"RENDITION-REPORT":var it=new B(I);ve(d,it,["URI"]),d.renditionReports=d.renditionReports||[],d.renditionReports.push(it);break;default:F.warn("line parsed but not handled: "+a)}}}v&&!v.relurl?(u.pop(),m-=v.duration,d.partList&&(d.fragmentHint=v)):d.partList&&(je(y,v),y.cc=p,d.fragmentHint=y,l&&Xe(y,l,d));var rt=u.length,st=u[0],nt=u[rt-1];if((m+=d.skippedSegments*d.targetduration)>0&&rt&&nt){d.averagetargetduration=m/rt;var at=nt.sn;d.endSN="initSegment"!==at?at:0,d.live||(nt.endList=!0),st&&(d.startCC=st.cc)}else d.endSN=0,d.startCC=0;return d.fragmentHint&&(m+=d.fragmentHint.duration),d.totalduration=m,d.endCC=p,E>0&&We(u,E),d},t}();function He(t,e,i){var r,s,n=new B(t);ve(i,n,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);var a=null!=(r=n.METHOD)?r:"",o=n.URI,l=n.hexadecimalInteger("IV"),h=n.KEYFORMATVERSIONS,d=null!=(s=n.KEYFORMAT)?s:"identity";o&&n.IV&&!l&&F.error("Invalid IV: "+n.IV);var u=o?Ke.resolve(o,e):"",c=(h||"1").split("/").map(Number).filter(Number.isFinite);return new fe(a,u,d,c,l)}function $e(t){var e=new B(t).decimalFloatingPoint("TIME-OFFSET");return R(e)?e:null}function Ve(t,e){var i=(t||"").split(/[ ,]+/).filter((function(t){return t}));["video","audio","text"].forEach((function(t){var r=i.filter((function(e){return Re(e,t)}));r.length&&(e[t+"Codec"]=r.join(","),i=i.filter((function(t){return-1===r.indexOf(t)})))})),e.unknownCodecs=i}function Ye(t,e,i){var r=e[i];r&&(t[i]=r)}function We(t,e){for(var i=t[e],r=e;r--;){var s=t[r];if(!s)return;s.programDateTime=i.programDateTime-1e3*s.duration,i=s}}function je(t,e){t.rawProgramDateTime?t.programDateTime=Date.parse(t.rawProgramDateTime):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime),R(t.programDateTime)||(t.programDateTime=null,t.rawProgramDateTime=null)}function qe(t,e,i,r){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=i,t.sn="initSegment",r&&(t.levelkeys=r),t.initSegment=null}function Xe(t,e,i){t.levelkeys=e;var r=i.encryptedFragments;r.length&&r[r.length-1].levelkeys===e||!Object.keys(e).some((function(t){return e[t].isCommonEncryption}))||r.push(t)}var ze={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},Qe={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};function Je(t){switch(t.type){case ze.AUDIO_TRACK:return Qe.AUDIO;case ze.SUBTITLE_TRACK:return Qe.SUBTITLE;default:return Qe.MAIN}}function Ze(t,e){var i=t.url;return void 0!==i&&0!==i.indexOf("data:")||(i=e.url),i}var ti=function(){function t(t){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=t,this.registerListeners()}var e=t.prototype;return e.startLoad=function(t){},e.stopLoad=function(){this.destroyInternalLoaders()},e.registerListeners=function(){var t=this.hls;t.on(D.MANIFEST_LOADING,this.onManifestLoading,this),t.on(D.LEVEL_LOADING,this.onLevelLoading,this),t.on(D.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(D.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)},e.unregisterListeners=function(){var t=this.hls;t.off(D.MANIFEST_LOADING,this.onManifestLoading,this),t.off(D.LEVEL_LOADING,this.onLevelLoading,this),t.off(D.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(D.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)},e.createInternalLoader=function(t){var e=this.hls.config,i=e.pLoader,r=e.loader,s=new(i||r)(e);return this.loaders[t.type]=s,s},e.getInternalLoader=function(t){return this.loaders[t.type]},e.resetInternalLoader=function(t){this.loaders[t]&&delete this.loaders[t]},e.destroyInternalLoaders=function(){for(var t in this.loaders){var e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}},e.destroy=function(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()},e.onManifestLoading=function(t,e){var i=e.url;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:ze.MANIFEST,url:i,deliveryDirectives:null})},e.onLevelLoading=function(t,e){var i=e.id,r=e.level,s=e.pathwayId,n=e.url,a=e.deliveryDirectives;this.load({id:i,level:r,pathwayId:s,responseType:"text",type:ze.LEVEL,url:n,deliveryDirectives:a})},e.onAudioTrackLoading=function(t,e){var i=e.id,r=e.groupId,s=e.url,n=e.deliveryDirectives;this.load({id:i,groupId:r,level:null,responseType:"text",type:ze.AUDIO_TRACK,url:s,deliveryDirectives:n})},e.onSubtitleTrackLoading=function(t,e){var i=e.id,r=e.groupId,s=e.url,n=e.deliveryDirectives;this.load({id:i,groupId:r,level:null,responseType:"text",type:ze.SUBTITLE_TRACK,url:s,deliveryDirectives:n})},e.load=function(t){var e,i,r,s=this,n=this.hls.config,a=this.getInternalLoader(t);if(a){var o=a.context;if(o&&o.url===t.url&&o.level===t.level)return void F.trace("[playlist-loader]: playlist request ongoing");F.log("[playlist-loader]: aborting previous loader for type: "+t.type),a.abort()}if(i=t.type===ze.MANIFEST?n.manifestLoadPolicy.default:h({},n.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),a=this.createInternalLoader(t),R(null==(e=t.deliveryDirectives)?void 0:e.part)&&(t.type===ze.LEVEL&&null!==t.level?r=this.hls.levels[t.level].details:t.type===ze.AUDIO_TRACK&&null!==t.id?r=this.hls.audioTracks[t.id].details:t.type===ze.SUBTITLE_TRACK&&null!==t.id&&(r=this.hls.subtitleTracks[t.id].details),r)){var l=r.partTarget,d=r.targetduration;if(l&&d){var u=1e3*Math.max(3*l,.8*d);i=h({},i,{maxTimeToFirstByteMs:Math.min(u,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(u,i.maxTimeToFirstByteMs)})}}var c=i.errorRetry||i.timeoutRetry||{},f={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:c.maxNumRetry||0,retryDelay:c.retryDelayMs||0,maxRetryDelay:c.maxRetryDelayMs||0},g={onSuccess:function(t,e,i,r){var n=s.getInternalLoader(i);s.resetInternalLoader(i.type);var a=t.data;0===a.indexOf("#EXTM3U")?(e.parsing.start=performance.now(),Ke.isMediaPlaylist(a)?s.handleTrackOrLevelPlaylist(t,e,i,r||null,n):s.handleMasterPlaylist(t,e,i,r)):s.handleManifestParsingError(t,i,new Error("no EXTM3U delimiter"),r||null,e)},onError:function(t,e,i,r){s.handleNetworkError(e,i,!1,t,r)},onTimeout:function(t,e,i){s.handleNetworkError(e,i,!0,void 0,t)}};a.load(t,f,g)},e.handleMasterPlaylist=function(t,e,i,r){var s=this.hls,n=t.data,a=Ze(t,i),o=Ke.parseMasterPlaylist(n,a);if(o.playlistParsingError)this.handleManifestParsingError(t,i,o.playlistParsingError,r,e);else{var l=o.contentSteering,h=o.levels,d=o.sessionData,u=o.sessionKeys,c=o.startTimeOffset,f=o.variableList;this.variableList=f;var g=Ke.parseMasterPlaylistMedia(n,a,o),m=g.AUDIO,p=void 0===m?[]:m,v=g.SUBTITLES,y=g["CLOSED-CAPTIONS"];p.length&&(p.some((function(t){return!t.url}))||!h[0].audioCodec||h[0].attrs.AUDIO||(F.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new B({}),bitrate:0,url:""}))),s.trigger(D.MANIFEST_LOADED,{levels:h,audioTracks:p,subtitles:v,captions:y,contentSteering:l,url:a,stats:e,networkDetails:r,sessionData:d,sessionKeys:u,startTimeOffset:c,variableList:f})}},e.handleTrackOrLevelPlaylist=function(t,e,i,r,s){var n=this.hls,a=i.id,o=i.level,l=i.type,h=Ze(t,i),d=0,u=R(o)?o:R(a)?a:0,c=Je(i),f=Ke.parseLevelPlaylist(t.data,h,u,c,d,this.variableList);if(l===ze.MANIFEST){var g={attrs:new B({}),bitrate:0,details:f,name:"",url:h};n.trigger(D.MANIFEST_LOADED,{levels:[g],audioTracks:[],url:h,stats:e,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),i.levelDetails=f,this.handlePlaylistLoaded(f,t,e,i,r,s)},e.handleManifestParsingError=function(t,e,i,r,s){this.hls.trigger(D.ERROR,{type:I.NETWORK_ERROR,details:w.MANIFEST_PARSING_ERROR,fatal:e.type===ze.MANIFEST,url:t.url,err:i,error:i,reason:i.message,response:t,context:e,networkDetails:r,stats:s})},e.handleNetworkError=function(t,e,i,s,n){void 0===i&&(i=!1);var a="A network "+(i?"timeout":"error"+(s?" (status "+s.code+")":""))+" occurred while loading "+t.type;t.type===ze.LEVEL?a+=": "+t.level+" id: "+t.id:t.type!==ze.AUDIO_TRACK&&t.type!==ze.SUBTITLE_TRACK||(a+=" id: "+t.id+' group-id: "'+t.groupId+'"');var o=new Error(a);F.warn("[playlist-loader]: "+a);var l=w.UNKNOWN,h=!1,d=this.getInternalLoader(t);switch(t.type){case ze.MANIFEST:l=i?w.MANIFEST_LOAD_TIMEOUT:w.MANIFEST_LOAD_ERROR,h=!0;break;case ze.LEVEL:l=i?w.LEVEL_LOAD_TIMEOUT:w.LEVEL_LOAD_ERROR,h=!1;break;case ze.AUDIO_TRACK:l=i?w.AUDIO_TRACK_LOAD_TIMEOUT:w.AUDIO_TRACK_LOAD_ERROR,h=!1;break;case ze.SUBTITLE_TRACK:l=i?w.SUBTITLE_TRACK_LOAD_TIMEOUT:w.SUBTITLE_LOAD_ERROR,h=!1}d&&this.resetInternalLoader(t.type);var u={type:I.NETWORK_ERROR,details:l,fatal:h,url:t.url,loader:d,context:t,error:o,networkDetails:e,stats:n};if(s){var c=(null==e?void 0:e.url)||t.url;u.response=r({url:c,data:void 0},s)}this.hls.trigger(D.ERROR,u)},e.handlePlaylistLoaded=function(t,e,i,r,s,n){var a=this.hls,o=r.type,l=r.level,h=r.id,d=r.groupId,u=r.deliveryDirectives,c=Ze(e,r),f=Je(r),g="number"==typeof r.level&&f===Qe.MAIN?l:void 0;if(t.fragments.length){t.targetduration||(t.playlistParsingError=new Error("Missing Target Duration"));var m=t.playlistParsingError;if(m)a.trigger(D.ERROR,{type:I.NETWORK_ERROR,details:w.LEVEL_PARSING_ERROR,fatal:!1,url:c,error:m,reason:m.message,response:e,context:r,level:g,parent:f,networkDetails:s,stats:i});else switch(t.live&&n&&(n.getCacheAge&&(t.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(t.ageHeader)||(t.ageHeader=0)),o){case ze.MANIFEST:case ze.LEVEL:a.trigger(D.LEVEL_LOADED,{details:t,level:g||0,id:h||0,stats:i,networkDetails:s,deliveryDirectives:u});break;case ze.AUDIO_TRACK:a.trigger(D.AUDIO_TRACK_LOADED,{details:t,id:h||0,groupId:d||"",stats:i,networkDetails:s,deliveryDirectives:u});break;case ze.SUBTITLE_TRACK:a.trigger(D.SUBTITLE_TRACK_LOADED,{details:t,id:h||0,groupId:d||"",stats:i,networkDetails:s,deliveryDirectives:u})}}else{var p=new Error("No Segments found in Playlist");a.trigger(D.ERROR,{type:I.NETWORK_ERROR,details:w.LEVEL_EMPTY_ERROR,fatal:!1,url:c,error:p,reason:p.message,response:e,context:r,level:g,parent:f,networkDetails:s,stats:i})}},t}();function ei(t,e){var i;try{i=new Event("addtrack")}catch(t){(i=document.createEvent("Event")).initEvent("addtrack",!1,!1)}i.track=t,e.dispatchEvent(i)}function ii(t,e){var i=t.mode;if("disabled"===i&&(t.mode="hidden"),t.cues&&!t.cues.getCueById(e.id))try{if(t.addCue(e),!t.cues.getCueById(e.id))throw new Error("addCue is failed for: "+e)}catch(i){F.debug("[texttrack-utils]: "+i);try{var r=new self.TextTrackCue(e.startTime,e.endTime,e.text);r.id=e.id,t.addCue(r)}catch(t){F.debug("[texttrack-utils]: Legacy TextTrackCue fallback failed: "+t)}}"disabled"===i&&(t.mode=i)}function ri(t){var e=t.mode;if("disabled"===e&&(t.mode="hidden"),t.cues)for(var i=t.cues.length;i--;)t.removeCue(t.cues[i]);"disabled"===e&&(t.mode=e)}function si(t,e,i,r){var s=t.mode;if("disabled"===s&&(t.mode="hidden"),t.cues&&t.cues.length>0)for(var n=ai(t.cues,e,i),a=0;a<n.length;a++)r&&!r(n[a])||t.removeCue(n[a]);"disabled"===s&&(t.mode=s)}function ni(t,e){if(e<t[0].startTime)return 0;var i=t.length-1;if(e>t[i].endTime)return-1;for(var r=0,s=i;r<=s;){var n=Math.floor((s+r)/2);if(e<t[n].startTime)s=n-1;else{if(!(e>t[n].startTime&&r<i))return n;r=n+1}}return t[r].startTime-e<e-t[s].startTime?r:s}function ai(t,e,i){var r=[],s=ni(t,e);if(s>-1)for(var n=s,a=t.length;n<a;n++){var o=t[n];if(o.startTime>=e&&o.endTime<=i)r.push(o);else if(o.startTime>i)return r}return r}function oi(t){for(var e=[],i=0;i<t.length;i++){var r=t[i];"subtitles"!==r.kind&&"captions"!==r.kind||!r.label||e.push(t[i])}return e}var li={audioId3:"org.id3",dateRange:"com.apple.quicktime.HLS",emsg:"https://aomedia.org/emsg/ID3"},hi=.25;function di(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function ui(t,e,i,s,n){var a=new t(e,i,"");try{a.value=s,n&&(a.type=n)}catch(o){a=new t(e,i,JSON.stringify(n?r({type:n},s):s))}return a}var ci=function(){var t=di();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY}();function fi(t,e){return t.getTime()/1e3-e}function gi(t){return Uint8Array.from(t.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}var mi=function(){function t(t){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=t,this._registerListeners()}var e=t.prototype;return e.destroy=function(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null},e._registerListeners=function(){var t=this.hls;t.on(D.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(D.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(D.MANIFEST_LOADING,this.onManifestLoading,this),t.on(D.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(D.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(D.LEVEL_UPDATED,this.onLevelUpdated,this)},e._unregisterListeners=function(){var t=this.hls;t.off(D.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(D.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(D.MANIFEST_LOADING,this.onManifestLoading,this),t.off(D.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(D.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(D.LEVEL_UPDATED,this.onLevelUpdated,this)},e.onMediaAttached=function(t,e){this.media=e.media},e.onMediaDetaching=function(){this.id3Track&&(ri(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})},e.onManifestLoading=function(){this.dateRangeCuesAppended={}},e.createTrack=function(t){var e=this.getID3Track(t.textTracks);return e.mode="hidden",e},e.getID3Track=function(t){if(this.media){for(var e=0;e<t.length;e++){var i=t[e];if("metadata"===i.kind&&"id3"===i.label)return ei(i,this.media),i}return this.media.addTextTrack("metadata","id3")}},e.onFragParsingMetadata=function(t,e){if(this.media){var i=this.hls.config,r=i.enableEmsgMetadataCues,s=i.enableID3MetadataCues;if(r||s){var n=e.samples;this.id3Track||(this.id3Track=this.createTrack(this.media));var a=di();if(a)for(var o=0;o<n.length;o++){var l=n[o].type;if((l!==li.emsg||r)&&s){var h=Lt(n[o].data);if(h){var d=n[o].pts,u=d+n[o].duration;u>ci&&(u=ci),u-d<=0&&(u=d+hi);for(var c=0;c<h.length;c++){var f=h[c];if(!St(f)){this.updateId3CueEnds(d,l);var g=ui(a,d,u,f,l);g&&this.id3Track.addCue(g)}}}}}}}},e.updateId3CueEnds=function(t,e){var i,r=null==(i=this.id3Track)?void 0:i.cues;if(r)for(var s=r.length;s--;){var n=r[s];n.type===e&&n.startTime<t&&n.endTime===ci&&(n.endTime=t)}},e.onBufferFlushing=function(t,e){var i=e.startOffset,r=e.endOffset,s=e.type,n=this.id3Track,a=this.hls;if(a){var o=a.config,l=o.enableEmsgMetadataCues,h=o.enableID3MetadataCues;n&&(l||h)&&si(n,i,r,"audio"===s?function(t){return t.type===li.audioId3&&h}:"video"===s?function(t){return t.type===li.emsg&&l}:function(t){return t.type===li.audioId3&&h||t.type===li.emsg&&l})}},e.onLevelUpdated=function(t,e){var i=this,r=e.details;if(this.media&&r.hasProgramDateTime&&this.hls.config.enableDateRangeMetadataCues){var s=this.dateRangeCuesAppended,n=this.id3Track,a=r.dateRanges,o=Object.keys(a);if(n)for(var l=Object.keys(s).filter((function(t){return!o.includes(t)})),h=function(){var t=l[d];Object.keys(s[t].cues).forEach((function(e){n.removeCue(s[t].cues[e])})),delete s[t]},d=l.length;d--;)h();var u=r.fragments[r.fragments.length-1];if(0!==o.length&&R(null==u?void 0:u.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(var c=u.programDateTime/1e3-u.start,f=di(),g=function(){var t=o[m],e=a[t],r=fi(e.startDate,c),n=s[t],l=(null==n?void 0:n.cues)||{},h=(null==n?void 0:n.durationKnown)||!1,d=ci,u=e.endDate;if(u)d=fi(u,c),h=!0;else if(e.endOnNext&&!h){var g=o.reduce((function(t,i){if(i!==e.id){var r=a[i];if(r.class===e.class&&r.startDate>e.startDate&&(!t||e.startDate<t.startDate))return r}return t}),null);g&&(d=fi(g.startDate,c),h=!0)}for(var p=Object.keys(e.attr),v=0;v<p.length;v++){var y=p[v];if(G(y)){var E=l[y];if(E)h&&!n.durationKnown&&(E.endTime=d);else if(f){var T=e.attr[y];K(y)&&(T=gi(T));var S=ui(f,r,d,{key:y,data:T},li.dateRange);S&&(S.id=t,i.id3Track.addCue(S),l[y]=S)}}}s[t]={cues:l,dateRange:e,durationKnown:h}},m=0;m<o.length;m++)g()}}},t}(),pi=function(){function t(t){var e=this;this.hls=void 0,this.config=void 0,this.media=null,this.levelDetails=null,this.currentTime=0,this.stallCount=0,this._latency=null,this.timeupdateHandler=function(){return e.timeupdate()},this.hls=t,this.config=t.config,this.registerListeners()}var e=t.prototype;return e.destroy=function(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null},e.registerListeners=function(){this.hls.on(D.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(D.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(D.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(D.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(D.ERROR,this.onError,this)},e.unregisterListeners=function(){this.hls.off(D.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(D.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(D.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(D.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(D.ERROR,this.onError,this)},e.onMediaAttached=function(t,e){this.media=e.media,this.media.addEventListener("timeupdate",this.timeupdateHandler)},e.onMediaDetaching=function(){this.media&&(this.media.removeEventListener("timeupdate",this.timeupdateHandler),this.media=null)},e.onManifestLoading=function(){this.levelDetails=null,this._latency=null,this.stallCount=0},e.onLevelUpdated=function(t,e){var i=e.details;this.levelDetails=i,i.advanced&&this.timeupdate(),!i.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)},e.onError=function(t,e){var i;e.details===w.BUFFER_STALLED_ERROR&&(this.stallCount++,null!=(i=this.levelDetails)&&i.live&&F.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))},e.timeupdate=function(){var t=this.media,e=this.levelDetails;if(t&&e){this.currentTime=t.currentTime;var i=this.computeLatency();if(null!==i){this._latency=i;var r=this.config,s=r.lowLatencyMode,n=r.maxLiveSyncPlaybackRate;if(s&&1!==n&&e.live){var a=this.targetLatency;if(null!==a){var o=i-a;if(o<Math.min(this.maxLatency,a+e.targetduration)&&o>.05&&this.forwardBufferLength>1){var l=Math.min(2,Math.max(1,n)),h=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20;t.playbackRate=Math.min(l,Math.max(1,h))}else 1!==t.playbackRate&&0!==t.playbackRate&&(t.playbackRate=1)}}}}},e.estimateLiveEdge=function(){var t=this.levelDetails;return null===t?null:t.edge+t.age},e.computeLatency=function(){var t=this.estimateLiveEdge();return null===t?null:t-this.currentTime},o(t,[{key:"latency",get:function(){return this._latency||0}},{key:"maxLatency",get:function(){var t=this.config,e=this.levelDetails;return void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:e?t.liveMaxLatencyDurationCount*e.targetduration:0}},{key:"targetLatency",get:function(){var t=this.levelDetails;if(null===t)return null;var e=t.holdBack,i=t.partHoldBack,r=t.targetduration,s=this.config,n=s.liveSyncDuration,a=s.liveSyncDurationCount,o=s.lowLatencyMode,l=this.hls.userConfig,h=o&&i||e;(l.liveSyncDuration||l.liveSyncDurationCount||0===h)&&(h=void 0!==n?n:a*r);var d=r,u=1;return h+Math.min(this.stallCount*u,d)}},{key:"liveSyncPosition",get:function(){var t=this.estimateLiveEdge(),e=this.targetLatency,i=this.levelDetails;if(null===t||null===e||null===i)return null;var r=i.edge,s=t-e-this.edgeStalled,n=r-i.totalduration,a=r-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(n,s),a)}},{key:"drift",get:function(){var t=this.levelDetails;return null===t?1:t.drift}},{key:"edgeStalled",get:function(){var t=this.levelDetails;if(null===t)return 0;var e=3*(this.config.lowLatencyMode&&t.partTarget||t.targetduration);return Math.max(t.age-e,0)}},{key:"forwardBufferLength",get:function(){var t=this.media,e=this.levelDetails;if(!t||!e)return 0;var i=t.buffered.length;return(i?t.buffered.end(i-1):e.edge)-this.currentTime}}]),t}(),vi=["NONE","TYPE-0","TYPE-1",null];function yi(t){return vi.indexOf(t)>-1}var Ei=["SDR","PQ","HLG"];function Ti(t){return!!t&&Ei.indexOf(t)>-1}var Si={No:"",Yes:"YES",v2:"v2"};function Ai(t){var e=t.canSkipUntil,i=t.canSkipDateRanges,r=t.age;return e&&r<e/2?i?Si.v2:Si.Yes:Si.No}var Li=function(){function t(t,e,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=e,this.skip=i}return t.prototype.addDirectives=function(t){var e=new self.URL(t);return void 0!==this.msn&&e.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&e.searchParams.set("_HLS_part",this.part.toString()),this.skip&&e.searchParams.set("_HLS_skip",this.skip),e.href},t}(),Ri=function(){function t(t){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.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[t.url],this._attrs=[t.attrs],this.bitrate=t.bitrate,t.details&&(this.details=t.details),this.id=t.id||0,this.name=t.name,this.width=t.width||0,this.height=t.height||0,this.frameRate=t.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=t.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,this.codecSet=[t.videoCodec,t.audioCodec].filter((function(t){return!!t})).map((function(t){return t.substring(0,4)})).join(","),this.addGroupId("audio",t.attrs.AUDIO),this.addGroupId("text",t.attrs.SUBTITLES)}var e=t.prototype;return e.hasAudioGroup=function(t){return bi(this._audioGroups,t)},e.hasSubtitleGroup=function(t){return bi(this._subtitleGroups,t)},e.addGroupId=function(t,e){if(e)if("audio"===t){var i=this._audioGroups;i||(i=this._audioGroups=[]),-1===i.indexOf(e)&&i.push(e)}else if("text"===t){var r=this._subtitleGroups;r||(r=this._subtitleGroups=[]),-1===r.indexOf(e)&&r.push(e)}},e.addFallback=function(){},o(t,[{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:"audioGroups",get:function(){return this._audioGroups}},{key:"subtitleGroups",get:function(){return this._subtitleGroups}},{key:"urlId",get:function(){return 0},set:function(t){}},{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 t;return null==(t=this.audioGroups)?void 0:t[0]}},{key:"textGroupId",get:function(){var t;return null==(t=this.subtitleGroups)?void 0:t[0]}}]),t}();function bi(t,e){return!(!e||!t)&&-1!==t.indexOf(e)}function ki(t,e){var i=e.startPTS;if(R(i)){var r,s=0;e.sn>t.sn?(s=i-t.start,r=t):(s=t.start-i,r=e),r.duration!==s&&(r.duration=s)}else e.sn>t.sn?t.cc===e.cc&&t.minEndPTS?e.start=t.start+(t.minEndPTS-t.start):e.start=t.start+t.duration:e.start=Math.max(t.start-e.duration,0)}function Di(t,e,i,r,s,n){r-i<=0&&(F.warn("Fragment should have a positive duration",e),r=i+e.duration,n=s+e.duration);var a=i,o=r,l=e.startPTS,h=e.endPTS;if(R(l)){var d=Math.abs(l-i);R(e.deltaPTS)?e.deltaPTS=Math.max(d,e.deltaPTS):e.deltaPTS=d,a=Math.max(i,l),i=Math.min(i,l),s=Math.min(s,e.startDTS),o=Math.min(r,h),r=Math.max(r,h),n=Math.max(n,e.endDTS)}var u=i-e.start;0!==e.start&&(e.start=i),e.duration=r-e.start,e.startPTS=i,e.maxStartPTS=a,e.startDTS=s,e.endPTS=r,e.minEndPTS=o,e.endDTS=n;var c,f=e.sn;if(!t||f<t.startSN||f>t.endSN)return 0;var g=f-t.startSN,m=t.fragments;for(m[g]=e,c=g;c>0;c--)ki(m[c],m[c-1]);for(c=g;c<m.length-1;c++)ki(m[c],m[c+1]);return t.fragmentHint&&ki(m[m.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,u}function Ii(t,e){for(var i=null,r=t.fragments,s=r.length-1;s>=0;s--){var n=r[s].initSegment;if(n){i=n;break}}t.fragmentHint&&delete t.fragmentHint.endPTS;var a,o=0;if(_i(t,e,(function(t,r){t.relurl&&(o=t.cc-r.cc),R(t.startPTS)&&R(t.endPTS)&&(r.start=r.startPTS=t.startPTS,r.startDTS=t.startDTS,r.maxStartPTS=t.maxStartPTS,r.endPTS=t.endPTS,r.endDTS=t.endDTS,r.minEndPTS=t.minEndPTS,r.duration=t.endPTS-t.startPTS,r.duration&&(a=r),e.PTSKnown=e.alignedSliding=!0),r.elementaryStreams=t.elementaryStreams,r.loader=t.loader,r.stats=t.stats,t.initSegment&&(r.initSegment=t.initSegment,i=t.initSegment)})),i&&(e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments).forEach((function(t){var e;!t||t.initSegment&&t.initSegment.relurl!==(null==(e=i)?void 0:e.relurl)||(t.initSegment=i)})),e.skippedSegments)if(e.deltaUpdateFailed=e.fragments.some((function(t){return!t})),e.deltaUpdateFailed){F.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(var l=e.skippedSegments;l--;)e.fragments.shift();e.startSN=e.fragments[0].sn,e.startCC=e.fragments[0].cc}else e.canSkipDateRanges&&(e.dateRanges=wi(t.dateRanges,e.dateRanges,e.recentlyRemovedDateranges));var h=e.fragments;if(o){F.warn("discontinuity sliding from playlist, take drift into account");for(var d=0;d<h.length;d++)h[d].cc+=o}e.skippedSegments&&(e.startCC=e.fragments[0].cc),Ci(t.partList,e.partList,(function(t,e){e.elementaryStreams=t.elementaryStreams,e.stats=t.stats})),a?Di(e,a,a.startPTS,a.endPTS,a.startDTS,a.endDTS):Pi(t,e),h.length&&(e.totalduration=e.edge-h[0].start),e.driftStartTime=t.driftStartTime,e.driftStart=t.driftStart;var u=e.advancedDateTime;if(e.advanced&&u){var c=e.edge;e.driftStart||(e.driftStartTime=u,e.driftStart=c),e.driftEndTime=u,e.driftEnd=c}else e.driftEndTime=t.driftEndTime,e.driftEnd=t.driftEnd,e.advancedDateTime=t.advancedDateTime}function wi(t,e,i){var r=h({},t);return i&&i.forEach((function(t){delete r[t]})),Object.keys(e).forEach((function(t){var i=new H(e[t].attr,r[t]);i.isValid?r[t]=i:F.warn('Ignoring invalid Playlist Delta Update DATERANGE tag: "'+JSON.stringify(e[t].attr)+'"')})),r}function Ci(t,e,i){if(t&&e)for(var r=0,s=0,n=t.length;s<=n;s++){var a=t[s],o=e[s+r];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?i(a,o):r--}}function _i(t,e,i){for(var r=e.skippedSegments,s=Math.max(t.startSN,e.startSN)-e.startSN,n=(t.fragmentHint?1:0)+(r?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,a=e.startSN-t.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,h=s;h<=n;h++){var d=l[a+h],u=o[h];r&&!u&&h<r&&(u=e.fragments[h]=d),d&&u&&i(d,u)}}function Pi(t,e){var i=e.startSN+e.skippedSegments-t.startSN,r=t.fragments;i<0||i>=r.length||xi(e,r[i].start)}function xi(t,e){if(e){for(var i=t.fragments,r=t.skippedSegments;r<i.length;r++)i[r].start+=e;t.fragmentHint&&(t.fragmentHint.start+=e)}}function Mi(t,e){void 0===e&&(e=1/0);var i=1e3*t.targetduration;if(t.updated){var r=t.fragments,s=4;if(r.length&&i*s>e){var n=1e3*r[r.length-1].duration;n<i&&(i=n)}}else i/=2;return Math.round(i)}function Oi(t,e,i){if(null==t||!t.details)return null;var r=t.details,s=r.fragments[e-r.startSN];return s||((s=r.fragmentHint)&&s.sn===e?s:e<r.startSN&&i&&i.sn===e?i:null)}function Fi(t,e,i){var r;return null!=t&&t.details?Ni(null==(r=t.details)?void 0:r.partList,e,i):null}function Ni(t,e,i){if(t)for(var r=t.length;r--;){var s=t[r];if(s.index===i&&s.fragment.sn===e)return s}return null}function Ui(t){t.forEach((function(t,e){var i=t.details;null!=i&&i.fragments&&i.fragments.forEach((function(t){t.level=e}))}))}function Bi(t){switch(t.details){case w.FRAG_LOAD_TIMEOUT:case w.KEY_LOAD_TIMEOUT:case w.LEVEL_LOAD_TIMEOUT:case w.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Gi(t,e){var i=Bi(e);return t.default[(i?"timeout":"error")+"Retry"]}function Ki(t,e){var i="linear"===t.backoff?1:Math.pow(2,e);return Math.min(i*t.retryDelayMs,t.maxRetryDelayMs)}function Hi(t){return r(r({},t),{errorRetry:null,timeoutRetry:null})}function $i(t,e,i,r){if(!t)return!1;var s=null==r?void 0:r.code,n=e<t.maxNumRetry&&(Vi(s)||!!i);return t.shouldRetry?t.shouldRetry(t,e,i,r,n):n}function Vi(t){return 0===t&&!1===navigator.onLine||!!t&&(t<400||t>499)}var Yi={search:function(t,e){for(var i=0,r=t.length-1,s=null,n=null;i<=r;){var a=e(n=t[s=(i+r)/2|0]);if(a>0)i=s+1;else{if(!(a<0))return n;r=s-1}}return null}};function Wi(t,e,i){if(null===e||!Array.isArray(t)||!t.length||!R(e))return null;if(e<(t[0].programDateTime||0))return null;if(e>=(t[t.length-1].endProgramDateTime||0))return null;i=i||0;for(var r=0;r<t.length;++r){var s=t[r];if(zi(e,i,s))return s}return null}function ji(t,e,i,r,s){void 0===i&&(i=0),void 0===r&&(r=0),void 0===s&&(s=.005);var n=null;if(t){n=e[t.sn-e[0].sn+1]||null;var a=t.endDTS-i;a>0&&a<15e-7&&(i+=15e-7)}else 0===i&&0===e[0].start&&(n=e[0]);if(n&&((!t||t.level===n.level)&&0===Xi(i,r,n)||qi(n,t,Math.min(s,r))))return n;var o=Yi.search(e,Xi.bind(null,i,r));return!o||o===t&&n?n:o}function qi(t,e,i){if(e&&0===e.start&&e.level<t.level&&(e.endPTS||0)>0){var r=e.tagList.reduce((function(t,e){return"INF"===e[0]&&(t+=parseFloat(e[1])),t}),i);return t.start<=r}return!1}function Xi(t,e,i){if(void 0===t&&(t=0),void 0===e&&(e=0),i.start<=t&&i.start+i.duration>t)return 0;var r=Math.min(e,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-r<=t?1:i.start-r>t&&i.start?-1:0}function zi(t,e,i){var r=1e3*Math.min(e,i.duration+(i.deltaPTS?i.deltaPTS:0));return(i.endProgramDateTime||0)-r>t}function Qi(t,e){return Yi.search(t,(function(t){return t.cc<e?1:t.cc>e?-1:0}))}var Ji={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},Zi={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,SwitchToSDR:4},tr=function(){function t(t){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=t,this.log=F.log.bind(F,"[info]:"),this.warn=F.warn.bind(F,"[warning]:"),this.error=F.error.bind(F,"[error]:"),this.registerListeners()}var e=t.prototype;return e.registerListeners=function(){var t=this.hls;t.on(D.ERROR,this.onError,this),t.on(D.MANIFEST_LOADING,this.onManifestLoading,this),t.on(D.LEVEL_UPDATED,this.onLevelUpdated,this)},e.unregisterListeners=function(){var t=this.hls;t&&(t.off(D.ERROR,this.onError,this),t.off(D.ERROR,this.onErrorOut,this),t.off(D.MANIFEST_LOADING,this.onManifestLoading,this),t.off(D.LEVEL_UPDATED,this.onLevelUpdated,this))},e.destroy=function(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}},e.startLoad=function(t){},e.stopLoad=function(){this.playlistError=0},e.getVariantLevelIndex=function(t){return(null==t?void 0:t.type)===Qe.MAIN?t.level:this.hls.loadLevel},e.onManifestLoading=function(){this.playlistError=0,this.penalizedRenditions={}},e.onLevelUpdated=function(){this.playlistError=0},e.onError=function(t,e){var i,r;if(!e.fatal){var s=this.hls,n=e.context;switch(e.details){case w.FRAG_LOAD_ERROR:case w.FRAG_LOAD_TIMEOUT:case w.KEY_LOAD_ERROR:case w.KEY_LOAD_TIMEOUT:return void(e.errorAction=this.getFragRetryOrSwitchAction(e));case w.FRAG_PARSING_ERROR:if(null!=(i=e.frag)&&i.gap)return void(e.errorAction={action:Ji.DoNothing,flags:Zi.None});case w.FRAG_GAP:case w.FRAG_DECRYPT_ERROR:return e.errorAction=this.getFragRetryOrSwitchAction(e),void(e.errorAction.action=Ji.SendAlternateToPenaltyBox);case w.LEVEL_EMPTY_ERROR:case w.LEVEL_PARSING_ERROR:var a,o,l=e.parent===Qe.MAIN?e.level:s.loadLevel;return void(e.details===w.LEVEL_EMPTY_ERROR&&null!=(a=e.context)&&null!=(o=a.levelDetails)&&o.live?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,l):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,l)));case w.LEVEL_LOAD_ERROR:case w.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==n?void 0:n.level)&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,n.level)));case w.AUDIO_TRACK_LOAD_ERROR:case w.AUDIO_TRACK_LOAD_TIMEOUT:case w.SUBTITLE_LOAD_ERROR:case w.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){var h=s.levels[s.loadLevel];if(h&&(n.type===ze.AUDIO_TRACK&&h.hasAudioGroup(n.groupId)||n.type===ze.SUBTITLE_TRACK&&h.hasSubtitleGroup(n.groupId)))return e.errorAction=this.getPlaylistRetryOrSwitchAction(e,s.loadLevel),e.errorAction.action=Ji.SendAlternateToPenaltyBox,void(e.errorAction.flags=Zi.MoveAllAlternatesMatchingHost)}return;case w.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:var d=s.levels[s.loadLevel],u=null==d?void 0:d.attrs["HDCP-LEVEL"];return void(u?e.errorAction={action:Ji.SendAlternateToPenaltyBox,flags:Zi.MoveAllAlternatesMatchingHDCP,hdcpLevel:u}:this.keySystemError(e));case w.BUFFER_ADD_CODEC_ERROR:case w.REMUX_ALLOC_ERROR:case w.BUFFER_APPEND_ERROR:return void(e.errorAction=this.getLevelSwitchAction(e,null!=(r=e.level)?r:s.loadLevel));case w.INTERNAL_EXCEPTION:case w.BUFFER_APPENDING_ERROR:case w.BUFFER_FULL_ERROR:case w.LEVEL_SWITCH_ERROR:case w.BUFFER_STALLED_ERROR:case w.BUFFER_SEEK_OVER_HOLE:case w.BUFFER_NUDGE_ON_STALL:return void(e.errorAction={action:Ji.DoNothing,flags:Zi.None})}e.type===I.KEY_SYSTEM_ERROR&&this.keySystemError(e)}},e.keySystemError=function(t){var e=this.getVariantLevelIndex(t.frag);t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e)},e.getPlaylistRetryOrSwitchAction=function(t,e){var i=Gi(this.hls.config.playlistLoadPolicy,t),r=this.playlistError++;if($i(i,r,Bi(t),t.response))return{action:Ji.RetryRequest,flags:Zi.None,retryConfig:i,retryCount:r};var s=this.getLevelSwitchAction(t,e);return i&&(s.retryConfig=i,s.retryCount=r),s},e.getFragRetryOrSwitchAction=function(t){var e=this.hls,i=this.getVariantLevelIndex(t.frag),r=e.levels[i],s=e.config,n=s.fragLoadPolicy,a=s.keyLoadPolicy,o=Gi(t.details.startsWith("key")?a:n,t),l=e.levels.reduce((function(t,e){return t+e.fragmentError}),0);if(r&&(t.details!==w.FRAG_GAP&&r.fragmentError++,$i(o,l,Bi(t),t.response)))return{action:Ji.RetryRequest,flags:Zi.None,retryConfig:o,retryCount:l};var h=this.getLevelSwitchAction(t,i);return o&&(h.retryConfig=o,h.retryCount=l),h},e.getLevelSwitchAction=function(t,e){var i=this.hls;null==e&&(e=i.loadLevel);var r=this.hls.levels[e];if(r){var s,n,a=t.details;r.loadError++,a===w.BUFFER_APPEND_ERROR&&r.fragmentError++;var o=-1,l=i.levels,h=i.loadLevel,d=i.minAutoLevel,u=i.maxAutoLevel;i.autoLevelEnabled||(i.loadLevel=-1);for(var c,f=null==(s=t.frag)?void 0:s.type,g=(f===Qe.AUDIO&&a===w.FRAG_PARSING_ERROR||"audio"===t.sourceBufferName&&(a===w.BUFFER_ADD_CODEC_ERROR||a===w.BUFFER_APPEND_ERROR))&&l.some((function(t){var e=t.audioCodec;return r.audioCodec!==e})),m="video"===t.sourceBufferName&&(a===w.BUFFER_ADD_CODEC_ERROR||a===w.BUFFER_APPEND_ERROR)&&l.some((function(t){var e=t.codecSet,i=t.audioCodec;return r.codecSet!==e&&r.audioCodec===i})),p=null!=(n=t.context)?n:{},v=p.type,y=p.groupId,E=function(){var e=(T+h)%l.length;if(e!==h&&e>=d&&e<=u&&0===l[e].loadError){var i,s,n=l[e];if(a===w.FRAG_GAP&&f===Qe.MAIN&&t.frag){var c=l[e].details;if(c){var p=ji(t.frag,c.fragments,t.frag.start);if(null!=p&&p.gap)return 0}}else{if(v===ze.AUDIO_TRACK&&n.hasAudioGroup(y)||v===ze.SUBTITLE_TRACK&&n.hasSubtitleGroup(y))return 0;if(f===Qe.AUDIO&&null!=(i=r.audioGroups)&&i.some((function(t){return n.hasAudioGroup(t)}))||f===Qe.SUBTITLE&&null!=(s=r.subtitleGroups)&&s.some((function(t){return n.hasSubtitleGroup(t)}))||g&&r.audioCodec===n.audioCodec||!g&&r.audioCodec!==n.audioCodec||m&&r.codecSet===n.codecSet)return 0}return o=e,1}},T=l.length;T--&&(0===(c=E())||1!==c););if(o>-1&&i.loadLevel!==o)return t.levelRetry=!0,this.playlistError=0,{action:Ji.SendAlternateToPenaltyBox,flags:Zi.None,nextAutoLevel:o}}return{action:Ji.SendAlternateToPenaltyBox,flags:Zi.MoveAllAlternatesMatchingHost}},e.onErrorOut=function(t,e){var i;switch(null==(i=e.errorAction)?void 0:i.action){case Ji.DoNothing:break;case Ji.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(e),e.errorAction.resolved||e.details===w.FRAG_GAP?/MediaSource readyState: ended/.test(e.error.message)&&(this.warn('MediaSource ended after "'+e.sourceBufferName+'" sourceBuffer append error. Attempting to recover from media error.'),this.hls.recoverMediaError()):e.fatal=!0}e.fatal&&this.hls.stopLoad()},e.sendAlternateToPenaltyBox=function(t){var e=this.hls,i=t.errorAction;if(i){var r=i.flags,s=i.hdcpLevel,n=i.nextAutoLevel;switch(r){case Zi.None:this.switchLevel(t,n);break;case Zi.MoveAllAlternatesMatchingHDCP:s&&(e.maxHdcpLevel=vi[vi.indexOf(s)-1],i.resolved=!0),this.warn('Restricting playback to HDCP-LEVEL of "'+e.maxHdcpLevel+'" or lower')}i.resolved||this.switchLevel(t,n)}},e.switchLevel=function(t,e){void 0!==e&&t.errorAction&&(this.warn("switching to level "+e+" after "+t.details),this.hls.nextAutoLevel=e,t.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)},t}(),er=function(){function t(t,e){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=F.log.bind(F,e+":"),this.warn=F.warn.bind(F,e+":"),this.hls=t}var e=t.prototype;return e.destroy=function(){this.clearTimer(),this.hls=this.log=this.warn=null},e.clearTimer=function(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)},e.startLoad=function(){this.canLoad=!0,this.requestScheduled=-1,this.loadPlaylist()},e.stopLoad=function(){this.canLoad=!1,this.clearTimer()},e.switchParams=function(t,e,i){var r=null==e?void 0:e.renditionReports;if(r){for(var s=-1,n=0;n<r.length;n++){var a=r[n],o=void 0;try{o=new self.URL(a.URI,e.url).href}catch(t){F.warn("Could not construct new URL for Rendition Report: "+t),o=a.URI||""}if(o===t){s=n;break}o===t.substring(0,o.length)&&(s=n)}if(-1!==s){var l=r[s],h=parseInt(l["LAST-MSN"])||(null==e?void 0:e.lastPartSn),d=parseInt(l["LAST-PART"])||(null==e?void 0:e.lastPartIndex);if(this.hls.config.lowLatencyMode){var u=Math.min(e.age-e.partTarget,e.targetduration);d>=0&&u>e.partTarget&&(d+=1)}var c=i&&Ai(i);return new Li(h,d>=0?d:void 0,c)}}},e.loadPlaylist=function(t){-1===this.requestScheduled&&(this.requestScheduled=self.performance.now())},e.shouldLoadPlaylist=function(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)},e.shouldReloadPlaylist=function(t){return-1===this.timer&&-1===this.requestScheduled&&this.shouldLoadPlaylist(t)},e.playlistLoaded=function(t,e,i){var r=this,s=e.details,n=e.stats,a=self.performance.now(),o=n.loading.first?Math.max(0,a-n.loading.first):0;if(s.advancedDateTime=Date.now()-o,s.live||null!=i&&i.live){if(s.reloaded(i),i&&this.log("live playlist "+t+" "+(s.advanced?"REFRESHED "+s.lastPartSn+"-"+s.lastPartIndex:s.updated?"UPDATED":"MISSED")),i&&s.fragments.length>0&&Ii(i,s),!this.canLoad||!s.live)return;var l,h=void 0,d=void 0;if(s.canBlockReload&&s.endSN&&s.advanced){var u=this.hls.config.lowLatencyMode,c=s.lastPartSn,f=s.endSN,g=s.lastPartIndex,m=c===f;-1!==g?(h=m?f+1:c,d=m?u?0:g:g+1):h=f+1;var p=s.age,v=p+s.ageHeader,y=Math.min(v-s.partTarget,1.5*s.targetduration);if(y>0){if(i&&y>i.tuneInGoal)this.warn("CDN Tune-in goal increased from: "+i.tuneInGoal+" to: "+y+" with playlist age: "+s.age),y=0;else{var E=Math.floor(y/s.targetduration);h+=E,void 0!==d&&(d+=Math.round(y%s.targetduration/s.partTarget)),this.log("CDN Tune-in age: "+s.ageHeader+"s last advanced "+p.toFixed(2)+"s goal: "+y+" skip sn "+E+" to part "+d)}s.tuneInGoal=y}if(l=this.getDeliveryDirectives(s,e.deliveryDirectives,h,d),u||!m)return void this.loadPlaylist(l)}else(s.canBlockReload||s.canSkipUntil)&&(l=this.getDeliveryDirectives(s,e.deliveryDirectives,h,d));var T=this.hls.mainForwardBufferInfo,S=T?T.end-T.len:0,A=Mi(s,1e3*(s.edge-S));s.updated&&a>this.requestScheduled+A&&(this.requestScheduled=n.loading.start),void 0!==h&&s.canBlockReload?this.requestScheduled=n.loading.first+A-(1e3*s.partTarget||1e3):-1===this.requestScheduled||this.requestScheduled+A<a?this.requestScheduled=a:this.requestScheduled-a<=0&&(this.requestScheduled+=A);var L=this.requestScheduled-a;L=Math.max(0,L),this.log("reload live playlist "+t+" in "+Math.round(L)+" ms"),this.timer=self.setTimeout((function(){return r.loadPlaylist(l)}),L)}else this.clearTimer()},e.getDeliveryDirectives=function(t,e,i,r){var s=Ai(t);return null!=e&&e.skip&&t.deltaUpdateFailed&&(i=e.msn,r=e.part,s=Si.No),new Li(i,r,s)},e.checkRetry=function(t){var e=this,i=t.details,r=Bi(t),s=t.errorAction,n=s||{},a=n.action,o=n.retryCount,l=void 0===o?0:o,h=n.retryConfig,d=!!s&&!!h&&(a===Ji.RetryRequest||!s.resolved&&a===Ji.SendAlternateToPenaltyBox);if(d){var u;if(this.requestScheduled=-1,l>=h.maxNumRetry)return!1;if(r&&null!=(u=t.context)&&u.deliveryDirectives)this.warn("Retrying playlist loading "+(l+1)+"/"+h.maxNumRetry+' after "'+i+'" without delivery-directives'),this.loadPlaylist();else{var c=Ki(h,l);this.timer=self.setTimeout((function(){return e.loadPlaylist()}),c),this.warn("Retrying playlist loading "+(l+1)+"/"+h.maxNumRetry+' after "'+i+'" in '+c+"ms")}t.levelRetry=!0,s.resolved=!0}return d},t}(),ir=function(){function t(t,e,i){void 0===e&&(e=0),void 0===i&&(i=0),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_=e,this.totalWeight_=i}var e=t.prototype;return e.sample=function(t,e){var i=Math.pow(this.alpha_,t);this.estimate_=e*(1-i)+i*this.estimate_,this.totalWeight_+=t},e.getTotalWeight=function(){return this.totalWeight_},e.getEstimate=function(){if(this.alpha_){var t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_},t}(),rr=function(){function t(t,e,i,r){void 0===r&&(r=100),this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new ir(t),this.fast_=new ir(e),this.defaultTTFB_=r,this.ttfb_=new ir(t)}var e=t.prototype;return e.update=function(t,e){var i=this.slow_,r=this.fast_,s=this.ttfb_;i.halfLife!==t&&(this.slow_=new ir(t,i.getEstimate(),i.getTotalWeight())),r.halfLife!==e&&(this.fast_=new ir(e,r.getEstimate(),r.getTotalWeight())),s.halfLife!==t&&(this.ttfb_=new ir(t,s.getEstimate(),s.getTotalWeight()))},e.sample=function(t,e){var i=(t=Math.max(t,this.minDelayMs_))/1e3,r=8*e/i;this.fast_.sample(i,r),this.slow_.sample(i,r)},e.sampleTTFB=function(t){var e=t/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(e,2)/2);this.ttfb_.sample(i,Math.max(t,5))},e.canEstimate=function(){return this.fast_.getTotalWeight()>=this.minWeight_},e.getEstimate=function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_},e.getEstimateTTFB=function(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_},e.destroy=function(){},t}(),sr={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},nr={};function ar(t,e,i,r,s,n){var a=t.audioCodec?t.audioGroups:null,o=null==n?void 0:n.audioCodec,l=null==n?void 0:n.channels,h=l?parseInt(l):o?1/0:2,d=null;if(null!=a&&a.length)try{d=1===a.length&&a[0]?e.groups[a[0]].channels:a.reduce((function(t,i){if(i){var r=e.groups[i];if(!r)throw new Error("Audio track group "+i+" not found");Object.keys(r.channels).forEach((function(e){t[e]=(t[e]||0)+r.channels[e]}))}return t}),{2:0})}catch(t){return!0}return void 0!==t.videoCodec&&(t.width>1920&&t.height>1088||t.height>1920&&t.width>1088||t.frameRate>Math.max(r,30)||"SDR"!==t.videoRange&&t.videoRange!==i||t.bitrate>Math.max(s,8e6))||!!d&&R(h)&&Object.keys(d).some((function(t){return parseInt(t)>h}))}function or(t,e,i){var s=t.videoCodec,n=t.audioCodec;if(!s||!n||!i)return Promise.resolve(sr);var a={width:t.width,height:t.height,bitrate:Math.ceil(Math.max(.9*t.bitrate,t.averageBitrate)),framerate:t.frameRate||30},o=t.videoRange;"SDR"!==o&&(a.transferFunction=o.toLowerCase());var l=s.split(",").map((function(t){return{type:"media-source",video:r(r({},a),{},{contentType:De(t,"video")})}}));return n&&t.audioGroups&&t.audioGroups.forEach((function(t){var i;t&&(null==(i=e.groups[t])||i.tracks.forEach((function(e){if(e.groupId===t){var i=e.channels||"",r=parseFloat(i);R(r)&&r>2&&l.push.apply(l,n.split(",").map((function(t){return{type:"media-source",audio:{contentType:De(t,"audio"),channels:""+r}}})))}})))})),Promise.all(l.map((function(t){var e=lr(t);return nr[e]||(nr[e]=i.decodingInfo(t))}))).then((function(t){return{supported:!t.some((function(t){return!t.supported})),configurations:l,decodingInfoResults:t}})).catch((function(t){return{supported:!1,configurations:l,decodingInfoResults:[],error:t}}))}function lr(t){var e=t.audio,i=t.video,r=i||e;if(r){var s=r.contentType.split('"')[1];if(i)return"r"+i.height+"x"+i.width+"f"+Math.ceil(i.framerate)+(i.transferFunction||"sd")+"_"+s+"_"+Math.ceil(i.bitrate/1e5);if(e)return"c"+e.channels+(e.spatialRendering?"s":"n")+"_"+s}return""}function hr(){if("function"==typeof matchMedia){var t=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(t.media!==e.media)return!0===t.matches}return!1}function dr(t,e){var i=!1,r=[];return t&&(i="SDR"!==t,r=[t]),e&&(r=e.allowedVideoRanges||Ei.slice(0),r=(i=void 0!==e.preferHDR?e.preferHDR:hr())?r.filter((function(t){return"SDR"!==t})):["SDR"]),{preferHDR:i,allowedVideoRanges:r}}function ur(t,e,i,r,s){for(var n=Object.keys(t),a=null==r?void 0:r.channels,o=null==r?void 0:r.audioCodec,l=a&&2===parseInt(a),h=!0,d=!1,u=1/0,c=1/0,f=1/0,g=0,m=[],p=dr(e,s),v=p.preferHDR,y=p.allowedVideoRanges,E=function(){var e=t[n[T]];h=e.channels[2]>0,u=Math.min(u,e.minHeight),c=Math.min(c,e.minFramerate),f=Math.min(f,e.minBitrate);var i=y.filter((function(t){return e.videoRanges[t]>0}));i.length>0&&(d=!0,m=i)},T=n.length;T--;)E();u=R(u)?u:0,c=R(c)?c:0;var S=Math.max(1080,u),A=Math.max(30,c);return f=R(f)?f:i,i=Math.max(f,i),d||(e=void 0,m=[]),{codecSet:n.reduce((function(e,r){var s=t[r];if(r===e)return e;if(s.minBitrate>i)return cr(r,"min bitrate of "+s.minBitrate+" > current estimate of "+i),e;if(!s.hasDefaultAudio)return cr(r,"no renditions with default or auto-select sound found"),e;if(o&&r.indexOf(o.substring(0,4))%5!=0)return cr(r,'audio codec preference "'+o+'" not found'),e;if(a&&!l){if(!s.channels[a])return cr(r,"no renditions with "+a+" channel sound found (channels options: "+Object.keys(s.channels)+")"),e}else if((!o||l)&&h&&0===s.channels[2])return cr(r,"no renditions with stereo sound found"),e;return s.minHeight>S?(cr(r,"min resolution of "+s.minHeight+" > maximum of "+S),e):s.minFramerate>A?(cr(r,"min framerate of "+s.minFramerate+" > maximum of "+A),e):m.some((function(t){return s.videoRanges[t]>0}))?s.maxScore<g?(cr(r,"max score of "+s.maxScore+" < selected max of "+g),e):e&&(we(r)>=we(e)||s.fragmentError>t[e].fragmentError)?e:(g=s.maxScore,r):(cr(r,"no variants with VIDEO-RANGE of "+JSON.stringify(m)+" found"),e)}),void 0),videoRanges:m,preferHDR:v,minFramerate:c,minBitrate:f}}function cr(t,e){F.log('[abr] start candidates with "'+t+'" ignored because '+e)}function fr(t){return t.reduce((function(t,e){var i=t.groups[e.groupId];i||(i=t.groups[e.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(e);var r=e.channels||"2";return i.channels[r]=(i.channels[r]||0)+1,i.hasDefault=i.hasDefault||e.default,i.hasAutoSelect=i.hasAutoSelect||e.autoselect,i.hasDefault&&(t.hasDefaultAudio=!0),i.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t}),{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function gr(t,e,i,r){return t.slice(i,r+1).reduce((function(t,i){if(!i.codecSet)return t;var r=i.audioGroups,s=t[i.codecSet];s||(t[i.codecSet]=s={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!r,fragmentError:0}),s.minBitrate=Math.min(s.minBitrate,i.bitrate);var n=Math.min(i.height,i.width);return s.minHeight=Math.min(s.minHeight,n),s.minFramerate=Math.min(s.minFramerate,i.frameRate),s.maxScore=Math.max(s.maxScore,i.score),s.fragmentError+=i.fragmentError,s.videoRanges[i.videoRange]=(s.videoRanges[i.videoRange]||0)+1,r&&r.forEach((function(t){if(t){var i=e.groups[t];i&&(s.hasDefaultAudio=s.hasDefaultAudio||e.hasDefaultAudio?i.hasDefault:i.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(i.channels).forEach((function(t){s.channels[t]=(s.channels[t]||0)+i.channels[t]})))}})),t}),{})}function mr(t,e,i){if("attrs"in t){var r=e.indexOf(t);if(-1!==r)return r}for(var s=0;s<e.length;s++)if(pr(t,e[s],i))return s;return-1}function pr(t,e,i){var r=t.groupId,s=t.name,n=t.lang,a=t.assocLang,o=t.characteristics,l=t.default,h=t.forced;return(void 0===r||e.groupId===r)&&(void 0===s||e.name===s)&&(void 0===n||e.lang===n)&&(void 0===n||e.assocLang===a)&&(void 0===l||e.default===l)&&(void 0===h||e.forced===h)&&(void 0===o||vr(o,e.characteristics))&&(void 0===i||i(t,e))}function vr(t,e){void 0===e&&(e="");var i=t.split(","),r=e.split(",");return i.length===r.length&&!i.some((function(t){return-1===r.indexOf(t)}))}function yr(t,e){var i=t.audioCodec,r=t.channels;return!(void 0!==i&&(e.audioCodec||"").substring(0,4)!==i.substring(0,4)||void 0!==r&&r!==(e.channels||"2"))}function Er(t,e,i,r,s){var n=e[r],a=e.reduce((function(t,e,i){var r=e.uri;return(t[r]||(t[r]=[])).push(i),t}),{})[n.uri];a.length>1&&(r=Math.max.apply(Math,a));var o=n.videoRange,l=n.frameRate,h=n.codecSet.substring(0,4),d=Tr(e,r,(function(e){if(e.videoRange!==o||e.frameRate!==l||e.codecSet.substring(0,4)!==h)return!1;var r=e.audioGroups,n=i.filter((function(t){return!r||-1!==r.indexOf(t.groupId)}));return mr(t,n,s)>-1}));return d>-1?d:Tr(e,r,(function(e){var r=e.audioGroups,n=i.filter((function(t){return!r||-1!==r.indexOf(t.groupId)}));return mr(t,n,s)>-1}))}function Tr(t,e,i){for(var r=e;r;r--)if(i(t[r]))return r;for(var s=e+1;s<t.length;s++)if(i(t[s]))return s;return-1}var Sr=function(){function t(t){var e=this;this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this._abandonRulesCheck=function(){var t=e.fragCurrent,i=e.partCurrent,r=e.hls,s=r.autoLevelEnabled,n=r.media;if(t&&n){var a=performance.now(),o=i?i.stats:t.stats,l=i?i.duration:t.duration,h=a-o.loading.start,d=r.minAutoLevel;if(o.aborted||o.loaded&&o.loaded===o.total||t.level<=d)return e.clearTimer(),void(e._nextAutoLevel=-1);if(s&&!n.paused&&n.playbackRate&&n.readyState){var u=r.mainForwardBufferInfo;if(null!==u){var c=e.bwEstimator.getEstimateTTFB(),f=Math.abs(n.playbackRate);if(!(h<=Math.max(c,l/(2*f)*1e3))){var g=u.len/f,m=o.loading.first?o.loading.first-o.loading.start:-1,p=o.loaded&&m>-1,v=e.getBwEstimate(),y=r.levels,E=y[t.level],T=o.total||Math.max(o.loaded,Math.round(l*E.averageBitrate/8)),S=p?h-m:h;S<1&&p&&(S=Math.min(h,8*o.loaded/v));var A=p?1e3*o.loaded/S:0,L=A?(T-o.loaded)/A:8*T/v+c/1e3;if(!(L<=g)){var b,k=A?8*A:v,I=Number.POSITIVE_INFINITY;for(b=t.level-1;b>d;b--){var w=y[b].maxBitrate;if((I=e.getTimeToLoadFrag(c/1e3,k,l*w,!y[b].details))<g)break}if(!(I>=L||I>10*l)){r.nextLoadLevel=r.nextAutoLevel=b,p?e.bwEstimator.sample(h-Math.min(c,m),o.loaded):e.bwEstimator.sampleTTFB(h);var C=y[b].maxBitrate;e.getBwEstimate()*e.hls.config.abrBandWidthUpFactor>C&&e.resetEstimator(C),e.clearTimer(),F.warn("[abr] Fragment "+t.sn+(i?" part "+i.index:"")+" of level "+t.level+" is loading too slowly;\n Time to underbuffer: "+g.toFixed(3)+" s\n Estimated load time for current fragment: "+L.toFixed(3)+" s\n Estimated load time for down switch fragment: "+I.toFixed(3)+" s\n TTFB estimate: "+(0|m)+" ms\n Current BW estimate: "+(R(v)?0|v:"Unknown")+" bps\n New BW estimate: "+(0|e.getBwEstimate())+" bps\n Switching to level "+b+" @ "+(0|C)+" bps"),r.trigger(D.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:i,stats:o})}}}}}}},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}var e=t.prototype;return e.resetEstimator=function(t){t&&(F.log("setting initial bwe to "+t),this.hls.config.abrEwmaDefaultEstimate=t),this.firstSelection=-1,this.bwEstimator=this.initEstimator()},e.initEstimator=function(){var t=this.hls.config;return new rr(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)},e.registerListeners=function(){var t=this.hls;t.on(D.MANIFEST_LOADING,this.onManifestLoading,this),t.on(D.FRAG_LOADING,this.onFragLoading,this),t.on(D.FRAG_LOADED,this.onFragLoaded,this),t.on(D.FRAG_BUFFERED,this.onFragBuffered,this),t.on(D.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(D.LEVEL_LOADED,this.onLevelLoaded,this),t.on(D.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(D.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(D.ERROR,this.onError,this)},e.unregisterListeners=function(){var t=this.hls;t&&(t.off(D.MANIFEST_LOADING,this.onManifestLoading,this),t.off(D.FRAG_LOADING,this.onFragLoading,this),t.off(D.FRAG_LOADED,this.onFragLoaded,this),t.off(D.FRAG_BUFFERED,this.onFragBuffered,this),t.off(D.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(D.LEVEL_LOADED,this.onLevelLoaded,this),t.off(D.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(D.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(D.ERROR,this.onError,this))},e.destroy=function(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null},e.onManifestLoading=function(t,e){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()},e.onLevelsUpdated=function(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null},e.onMaxAutoLevelUpdated=function(){this.firstSelection=-1,this.nextAutoLevelKey=""},e.onFragLoading=function(t,e){var i,r=e.frag;this.ignoreFragment(r)||(r.bitrateTest||(this.fragCurrent=r,this.partCurrent=null!=(i=e.part)?i:null),this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100))},e.onLevelSwitching=function(t,e){this.clearTimer()},e.onError=function(t,e){if(!e.fatal)switch(e.details){case w.BUFFER_ADD_CODEC_ERROR:case w.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case w.FRAG_LOAD_TIMEOUT:var i=e.frag,r=this.fragCurrent,s=this.partCurrent;if(i&&r&&i.sn===r.sn&&i.level===r.level){var n=performance.now(),a=s?s.stats:i.stats,o=n-a.loading.start,l=a.loading.first?a.loading.first-a.loading.start:-1;if(a.loaded&&l>-1){var h=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(o-Math.min(h,l),a.loaded)}else this.bwEstimator.sampleTTFB(o)}}},e.getTimeToLoadFrag=function(t,e,i,r){return t+i/e+(r?this.lastLevelLoadSec:0)},e.onLevelLoaded=function(t,e){var i=this.hls.config,r=e.stats.loading,s=r.end-r.start;R(s)&&(this.lastLevelLoadSec=s/1e3),e.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD)},e.onFragLoaded=function(t,e){var i=e.frag,r=e.part,s=r?r.stats:i.stats;if(i.type===Qe.MAIN&&this.bwEstimator.sampleTTFB(s.loading.first-s.loading.start),!this.ignoreFragment(i)){if(this.clearTimer(),i.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){var n=r?r.duration:i.duration,a=this.hls.levels[i.level],o=(a.loaded?a.loaded.bytes:0)+s.loaded,l=(a.loaded?a.loaded.duration:0)+n;a.loaded={bytes:o,duration:l},a.realBitrate=Math.round(8*o/l)}if(i.bitrateTest){var h={stats:s,frag:i,part:r,id:i.type};this.onFragBuffered(D.FRAG_BUFFERED,h),i.bitrateTest=!1}else this.lastLoadedFragLevel=i.level}},e.onFragBuffered=function(t,e){var i=e.frag,r=e.part,s=null!=r&&r.stats.loaded?r.stats:i.stats;if(!s.aborted&&!this.ignoreFragment(i)){var n=s.parsing.end-s.loading.start-Math.min(s.loading.first-s.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,s.loaded),s.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}},e.ignoreFragment=function(t){return t.type!==Qe.MAIN||"initSegment"===t.sn},e.clearTimer=function(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)},e.getAutoLevelKey=function(){return this.getBwEstimate()+"_"+this.getStarvationDelay().toFixed(2)},e.getNextABRAutoLevel=function(){var t=this.fragCurrent,e=this.partCurrent,i=this.hls,r=i.maxAutoLevel,s=i.config,n=i.minAutoLevel,a=e?e.duration:t?t.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay(),h=s.abrBandWidthFactor,d=s.abrBandWidthUpFactor;if(l){var u=this.findBestLevel(o,n,r,l,0,h,d);if(u>=0)return u}var c=a?Math.min(a,s.maxStarvationDelay):s.maxStarvationDelay;if(!l){var f=this.bitrateTestDelay;f&&(c=(a?Math.min(a,s.maxLoadingDelay):s.maxLoadingDelay)-f,F.info("[abr] bitrate test took "+Math.round(1e3*f)+"ms, set first fragment max fetchDuration to "+Math.round(1e3*c)+" ms"),h=d=1)}var g=this.findBestLevel(o,n,r,l,c,h,d);if(F.info("[abr] "+(l?"rebuffering expected":"buffer is empty")+", optimal quality level "+g),g>-1)return g;var m=i.levels[n],p=i.levels[i.loadLevel];return(null==m?void 0:m.bitrate)<(null==p?void 0:p.bitrate)?n:i.loadLevel},e.getStarvationDelay=function(){var t=this.hls,e=t.media;if(!e)return 1/0;var i=e&&0!==e.playbackRate?Math.abs(e.playbackRate):1,r=t.mainForwardBufferInfo;return(r?r.len:0)/i},e.getBwEstimate=function(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate},e.findBestLevel=function(t,e,i,r,s,n,a){var o,l=this,h=r+s,d=this.lastLoadedFragLevel,u=-1===d?this.hls.firstLevel:d,c=this.fragCurrent,f=this.partCurrent,g=this.hls,m=g.levels,p=g.allAudioTracks,v=g.loadLevel,y=g.config;if(1===m.length)return 0;var E,T=m[u],S=!(null==T||null==(o=T.details)||!o.live),A=-1===v||-1===d,L="SDR",b=(null==T?void 0:T.frameRate)||0,k=y.audioPreference,D=y.videoPreference,I=this.audioTracksByGroup||(this.audioTracksByGroup=fr(p));if(A){if(-1!==this.firstSelection)return this.firstSelection;var w=ur(this.codecTiers||(this.codecTiers=gr(m,I,e,i)),L,t,k,D),C=w.codecSet,_=w.videoRanges,P=w.minFramerate,x=w.minBitrate,M=w.preferHDR;E=C,L=M?_[_.length-1]:_[0],b=P,t=Math.max(t,x),F.log("[abr] picked start tier "+JSON.stringify(w))}else E=null==T?void 0:T.codecSet,L=null==T?void 0:T.videoRange;for(var O,N=f?f.duration:c?c.duration:0,U=this.bwEstimator.getEstimateTTFB()/1e3,B=[],G=function(){var e,o=m[K],c=K>u;if(!o)return 0;if(y.useMediaCapabilities&&!o.supportedResult&&!o.supportedPromise){var g=navigator.mediaCapabilities;"function"==typeof(null==g?void 0:g.decodingInfo)&&ar(o,I,L,b,t,k)?(o.supportedPromise=or(o,I,g),o.supportedPromise.then((function(t){if(l.hls){o.supportedResult=t;var e=l.hls.levels,i=e.indexOf(o);t.error?F.warn('[abr] MediaCapabilities decodingInfo error: "'+t.error+'" for level '+i+" "+JSON.stringify(t)):t.supported||(F.warn("[abr] Unsupported MediaCapabilities decodingInfo result for level "+i+" "+JSON.stringify(t)),i>-1&&e.length>1&&(F.log("[abr] Removing unsupported level "+i),l.hls.removeLevel(i)))}}))):o.supportedResult=sr}if(E&&o.codecSet!==E||L&&o.videoRange!==L||c&&b>o.frameRate||!c&&b>0&&b<o.frameRate||o.supportedResult&&(null==(e=o.supportedResult.decodingInfoResults)||!e[0].smooth))return B.push(K),0;var p,D=o.details,w=(f?null==D?void 0:D.partTarget:null==D?void 0:D.averagetargetduration)||N;p=c?a*t:n*t;var C=N&&r>=2*N&&0===s?m[K].averageBitrate:m[K].maxBitrate,_=l.getTimeToLoadFrag(U,p,C*w,void 0===D);if(p>=C&&(K===d||0===o.loadError&&0===o.fragmentError)&&(_<=U||!R(_)||S&&!l.bitrateTestDelay||_<h)){var P=l.forcedAutoLevel;return K===v||-1!==P&&P===v||(B.length&&F.trace("[abr] Skipped level(s) "+B.join(",")+" of "+i+' max with CODECS and VIDEO-RANGE:"'+m[B[0]].codecs+'" '+m[B[0]].videoRange+'; not compatible with "'+T.codecs+'" '+L),F.info("[abr] switch candidate:"+u+"->"+K+" adjustedbw("+Math.round(p)+")-bitrate="+Math.round(p-C)+" ttfb:"+U.toFixed(1)+" avgDuration:"+w.toFixed(1)+" maxFetchDuration:"+h.toFixed(1)+" fetchDuration:"+_.toFixed(1)+" firstSelection:"+A+" codecSet:"+E+" videoRange:"+L+" hls.loadLevel:"+v)),A&&(l.firstSelection=K),{v:K}}},K=i;K>=e;K--)if(0!==(O=G())&&O)return O.v;return-1},o(t,[{key:"firstAutoLevel",get:function(){var t=this.hls,e=t.maxAutoLevel,i=t.minAutoLevel,r=this.getBwEstimate(),s=this.hls.config.maxStarvationDelay,n=this.findBestLevel(r,i,e,0,s,1,1);if(n>-1)return n;var a=this.hls.firstLevel,o=Math.min(Math.max(a,i),e);return F.warn("[abr] Could not find best starting auto level. Defaulting to first in playlist "+a+" clamped to "+o),o}},{key:"forcedAutoLevel",get:function(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}},{key:"nextAutoLevel",get:function(){var t=this.forcedAutoLevel,e=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(!(-1===t||e&&i&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return t;var r=e&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==t){var s=this.hls.levels;if(s.length>Math.max(t,r)&&s[t].loadError<=s[r].loadError)return t}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r},set:function(t){var e=this.hls,i=e.maxAutoLevel,r=e.minAutoLevel,s=Math.min(Math.max(t,r),i);this._nextAutoLevel!==s&&(this.nextAutoLevelKey="",this._nextAutoLevel=s)}}]),t}(),Ar=function(){function t(){this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}var e=t.prototype;return e.destroy=function(){this.onHandlerDestroying(),this.onHandlerDestroyed()},e.onHandlerDestroying=function(){this.clearNextTick(),this.clearInterval()},e.onHandlerDestroyed=function(){},e.hasInterval=function(){return!!this._tickInterval},e.hasNextTick=function(){return!!this._tickTimer},e.setInterval=function(t){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,t),!0)},e.clearInterval=function(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)},e.clearNextTick=function(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)},e.tick=function(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)},e.tickImmediate=function(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)},e.doTick=function(){},t}(),Lr={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"},Rr=function(){function t(t){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()}var e=t.prototype;return e._registerListeners=function(){var t=this.hls;t.on(D.BUFFER_APPENDED,this.onBufferAppended,this),t.on(D.FRAG_BUFFERED,this.onFragBuffered,this),t.on(D.FRAG_LOADED,this.onFragLoaded,this)},e._unregisterListeners=function(){var t=this.hls;t.off(D.BUFFER_APPENDED,this.onBufferAppended,this),t.off(D.FRAG_BUFFERED,this.onFragBuffered,this),t.off(D.FRAG_LOADED,this.onFragLoaded,this)},e.destroy=function(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null},e.getAppendedFrag=function(t,e){var i=this.activePartLists[e];if(i)for(var r=i.length;r--;){var s=i[r];if(!s)break;var n=s.end;if(s.start<=t&&null!==n&&t<=n)return s}return this.getBufferedFrag(t,e)},e.getBufferedFrag=function(t,e){for(var i=this.fragments,r=Object.keys(i),s=r.length;s--;){var n=i[r[s]];if((null==n?void 0:n.body.type)===e&&n.buffered){var a=n.body;if(a.start<=t&&t<=a.end)return a}}return null},e.detectEvictedFragments=function(t,e,i,r){var s=this;this.timeRanges&&(this.timeRanges[t]=e);var n=(null==r?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach((function(r){var a=s.fragments[r];if(a&&!(n>=a.body.sn))if(a.buffered||a.loaded){var o=a.range[t];o&&o.time.some((function(t){var i=!s.isTimeBuffered(t.startPTS,t.endPTS,e);return i&&s.removeFragment(a.body),i}))}else a.body.type===i&&s.removeFragment(a.body)}))},e.detectPartialFragments=function(t){var e=this,i=this.timeRanges,r=t.frag,s=t.part;if(i&&"initSegment"!==r.sn){var n=kr(r),a=this.fragments[n];if(!(!a||a.buffered&&r.gap)){var o=!r.relurl;Object.keys(i).forEach((function(t){var n=r.elementaryStreams[t];if(n){var l=i[t],h=o||!0===n.partial;a.range[t]=e.getBufferedTimes(r,s,h,l)}})),a.loaded=null,Object.keys(a.range).length?(a.buffered=!0,(a.body.endList=r.endList||a.body.endList)&&(this.endListFragments[a.body.type]=a),br(a)||this.removeParts(r.sn-1,r.type)):this.removeFragment(a.body)}}},e.removeParts=function(t,e){var i=this.activePartLists[e];i&&(this.activePartLists[e]=i.filter((function(e){return e.fragment.sn>=t})))},e.fragBuffered=function(t,e){var i=kr(t),r=this.fragments[i];!r&&e&&(r=this.fragments[i]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,r.buffered=!0)},e.getBufferedTimes=function(t,e,i,r){for(var s={time:[],partial:i},n=t.start,a=t.end,o=t.minEndPTS||a,l=t.maxStartPTS||n,h=0;h<r.length;h++){var d=r.start(h)-this.bufferPadding,u=r.end(h)+this.bufferPadding;if(l>=d&&o<=u){s.time.push({startPTS:Math.max(n,r.start(h)),endPTS:Math.min(a,r.end(h))});break}if(n<u&&a>d){var c=Math.max(n,r.start(h)),f=Math.min(a,r.end(h));f>c&&(s.partial=!0,s.time.push({startPTS:c,endPTS:f}))}else if(a<=d)break}return s},e.getPartialFragment=function(t){var e,i,r,s=null,n=0,a=this.bufferPadding,o=this.fragments;return Object.keys(o).forEach((function(l){var h=o[l];h&&br(h)&&(i=h.body.start-a,r=h.body.end+a,t>=i&&t<=r&&(e=Math.min(t-i,r-t),n<=e&&(s=h.body,n=e)))})),s},e.isEndListAppended=function(t){var e=this.endListFragments[t];return void 0!==e&&(e.buffered||br(e))},e.getState=function(t){var e=kr(t),i=this.fragments[e];return i?i.buffered?br(i)?Lr.PARTIAL:Lr.OK:Lr.APPENDING:Lr.NOT_LOADED},e.isTimeBuffered=function(t,e,i){for(var r,s,n=0;n<i.length;n++){if(r=i.start(n)-this.bufferPadding,s=i.end(n)+this.bufferPadding,t>=r&&e<=s)return!0;if(e<=r)return!1}return!1},e.onFragLoaded=function(t,e){var i=e.frag,r=e.part;if("initSegment"!==i.sn&&!i.bitrateTest){var s=r?null:e,n=kr(i);this.fragments[n]={body:i,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}},e.onBufferAppended=function(t,e){var i=this,r=e.frag,s=e.part,n=e.timeRanges;if("initSegment"!==r.sn){var a=r.type;if(s){var o=this.activePartLists[a];o||(this.activePartLists[a]=o=[]),o.push(s)}this.timeRanges=n,Object.keys(n).forEach((function(t){var e=n[t];i.detectEvictedFragments(t,e,a,s)}))}},e.onFragBuffered=function(t,e){this.detectPartialFragments(e)},e.hasFragment=function(t){var e=kr(t);return!!this.fragments[e]},e.hasParts=function(t){var e;return!(null==(e=this.activePartLists[t])||!e.length)},e.removeFragmentsInRange=function(t,e,i,r,s){var n=this;r&&!this.hasGaps||Object.keys(this.fragments).forEach((function(a){var o=n.fragments[a];if(o){var l=o.body;l.type!==i||r&&!l.gap||l.start<e&&l.end>t&&(o.buffered||s)&&n.removeFragment(l)}}))},e.removeFragment=function(t){var e=kr(t);t.stats.loaded=0,t.clearElementaryStreamInfo();var i=this.activePartLists[t.type];if(i){var r=t.sn;this.activePartLists[t.type]=i.filter((function(t){return t.fragment.sn!==r}))}delete this.fragments[e],t.endList&&delete this.endListFragments[t.type]},e.removeAllFragments=function(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1},t}();function br(t){var e,i,r;return t.buffered&&(t.body.gap||(null==(e=t.range.video)?void 0:e.partial)||(null==(i=t.range.audio)?void 0:i.partial)||(null==(r=t.range.audiovideo)?void 0:r.partial))}function kr(t){return t.type+"_"+t.level+"_"+t.sn}var Dr={length:0,start:function(){return 0},end:function(){return 0}},Ir=function(){function t(){}return t.isBuffered=function(e,i){try{if(e)for(var r=t.getBuffered(e),s=0;s<r.length;s++)if(i>=r.start(s)&&i<=r.end(s))return!0}catch(t){}return!1},t.bufferInfo=function(e,i,r){try{if(e){var s,n=t.getBuffered(e),a=[];for(s=0;s<n.length;s++)a.push({start:n.start(s),end:n.end(s)});return this.bufferedInfo(a,i,r)}}catch(t){}return{len:0,start:i,end:i,nextStart:void 0}},t.bufferedInfo=function(t,e,i){e=Math.max(0,e),t.sort((function(t,e){var i=t.start-e.start;return i||e.end-t.end}));var r=[];if(i)for(var s=0;s<t.length;s++){var n=r.length;if(n){var a=r[n-1].end;t[s].start-a<i?t[s].end>a&&(r[n-1].end=t[s].end):r.push(t[s])}else r.push(t[s])}else r=t;for(var o,l=0,h=e,d=e,u=0;u<r.length;u++){var c=r[u].start,f=r[u].end;if(e+i>=c&&e<f)h=c,l=(d=f)-e;else if(e+i<c){o=c;break}}return{len:l,start:h||0,end:d||0,nextStart:o}},t.getBuffered=function(t){try{return t.buffered}catch(t){return F.log("failed to get media.buffered",t),Dr}},t}(),wr=function(t,e,i,r,s,n){void 0===r&&(r=0),void 0===s&&(s=-1),void 0===n&&(n=!1),this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=Cr(),this.buffering={audio:Cr(),video:Cr(),audiovideo:Cr()},this.level=t,this.sn=e,this.id=i,this.size=r,this.part=s,this.partial=n};function Cr(){return{start:0,executeStart:0,executeEnd:0,end:0}}function _r(t,e){for(var i=0,r=t.length;i<r;i++){var s;if((null==(s=t[i])?void 0:s.cc)===e)return t[i]}return null}function Pr(t,e,i){return!(!e||!(i.endCC>i.startCC||t&&t.cc<i.startCC))}function xr(t,e){var i=t.fragments,r=e.fragments;if(r.length&&i.length){var s=_r(i,r[0].cc);if(s&&(!s||s.startPTS))return s;F.log("No frag in previous level to align on")}else F.log("No fragments to align")}function Mr(t,e){if(t){var i=t.start+e;t.start=t.startPTS=i,t.endPTS=i+t.duration}}function Or(t,e){for(var i=e.fragments,r=0,s=i.length;r<s;r++)Mr(i[r],t);e.fragmentHint&&Mr(e.fragmentHint,t),e.alignedSliding=!0}function Fr(t,e,i){e&&(Nr(t,i,e),!i.alignedSliding&&e&&Ur(i,e),i.alignedSliding||!e||i.skippedSegments||Pi(e,i))}function Nr(t,e,i){if(Pr(t,i,e)){var r=xr(i,e);r&&R(r.start)&&(F.log("Adjusting PTS using last level due to CC increase within current level "+e.url),Or(r.start,e))}}function Ur(t,e){if(t.hasProgramDateTime&&e.hasProgramDateTime){var i=t.fragments,r=e.fragments;if(i.length&&r.length){var s,n,a=Math.min(e.endCC,t.endCC);e.startCC<a&&t.startCC<a&&(s=_r(r,a),n=_r(i,a)),s&&n||(n=_r(i,(s=r[Math.floor(r.length/2)]).cc)||i[Math.floor(i.length/2)]);var o=s.programDateTime,l=n.programDateTime;o&&l&&Or((l-o)/1e3-(n.start-s.start),t)}}}var Br=Math.pow(2,17),Gr=function(){function t(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}var e=t.prototype;return e.destroy=function(){this.loader&&(this.loader.destroy(),this.loader=null)},e.abort=function(){this.loader&&this.loader.abort()},e.load=function(t,e){var i=this,s=t.url;if(!s)return Promise.reject(new $r({type:I.NETWORK_ERROR,details:w.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error("Fragment does not have a "+(s?"part list":"url")),networkDetails:null}));this.abort();var n=this.config,a=n.fLoader,o=n.loader;return new Promise((function(l,h){if(i.loader&&i.loader.destroy(),t.gap){if(t.tagList.some((function(t){return"GAP"===t[0]})))return void h(Hr(t));t.gap=!1}var d=i.loader=t.loader=a?new a(n):new o(n),u=Kr(t),c=Hi(n.fragLoadPolicy.default),f={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?1/0:Br};t.stats=d.stats,d.load(u,f,{onSuccess:function(e,r,s,n){i.resetLoader(t,d);var a=e.data;s.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(a.slice(0,16)),a=a.slice(16)),l({frag:t,part:null,payload:a,networkDetails:n})},onError:function(e,n,a,o){i.resetLoader(t,d),h(new $r({type:I.NETWORK_ERROR,details:w.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:r({url:s,data:void 0},e),error:new Error("HTTP Error "+e.code+" "+e.text),networkDetails:a,stats:o}))},onAbort:function(e,r,s){i.resetLoader(t,d),h(new $r({type:I.NETWORK_ERROR,details:w.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:s,stats:e}))},onTimeout:function(e,r,s){i.resetLoader(t,d),h(new $r({type:I.NETWORK_ERROR,details:w.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error("Timeout after "+f.timeout+"ms"),networkDetails:s,stats:e}))},onProgress:function(i,r,s,n){e&&e({frag:t,part:null,payload:s,networkDetails:n})}})}))},e.loadPart=function(t,e,i){var s=this;this.abort();var n=this.config,a=n.fLoader,o=n.loader;return new Promise((function(l,h){if(s.loader&&s.loader.destroy(),t.gap||e.gap)h(Hr(t,e));else{var d=s.loader=t.loader=a?new a(n):new o(n),u=Kr(t,e),c=Hi(n.fragLoadPolicy.default),f={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Br};e.stats=d.stats,d.load(u,f,{onSuccess:function(r,n,a,o){s.resetLoader(t,d),s.updateStatsFromPart(t,e);var h={frag:t,part:e,payload:r.data,networkDetails:o};i(h),l(h)},onError:function(i,n,a,o){s.resetLoader(t,d),h(new $r({type:I.NETWORK_ERROR,details:w.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:r({url:u.url,data:void 0},i),error:new Error("HTTP Error "+i.code+" "+i.text),networkDetails:a,stats:o}))},onAbort:function(i,r,n){t.stats.aborted=e.stats.aborted,s.resetLoader(t,d),h(new $r({type:I.NETWORK_ERROR,details:w.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:n,stats:i}))},onTimeout:function(i,r,n){s.resetLoader(t,d),h(new $r({type:I.NETWORK_ERROR,details:w.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error("Timeout after "+f.timeout+"ms"),networkDetails:n,stats:i}))}})}}))},e.updateStatsFromPart=function(t,e){var i=t.stats,r=e.stats,s=r.total;if(i.loaded+=r.loaded,s){var n=Math.round(t.duration/e.duration),a=Math.min(Math.round(i.loaded/s),n),o=(n-a)*Math.round(i.loaded/a);i.total=i.loaded+o}else i.total=Math.max(i.loaded,i.total);var l=i.loading,h=r.loading;l.start?l.first+=h.first-h.start:(l.start=h.start,l.first=h.first),l.end=h.end},e.resetLoader=function(t,e){t.loader=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()},t}();function Kr(t,e){void 0===e&&(e=null);var i=e||t,r={frag:t,part:e,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},s=i.byteRangeStartOffset,n=i.byteRangeEndOffset;if(R(s)&&R(n)){var a,o=s,l=n;if("initSegment"===t.sn&&"AES-128"===(null==(a=t.decryptdata)?void 0:a.method)){var h=n-s;h%16&&(l=n+(16-h%16)),0!==s&&(r.resetIV=!0,o=s-16)}r.rangeStart=o,r.rangeEnd=l}return r}function Hr(t,e){var i=new Error("GAP "+(t.gap?"tag":"attribute")+" found"),r={type:I.MEDIA_ERROR,details:w.FRAG_GAP,fatal:!1,frag:t,error:i,networkDetails:null};return e&&(r.part=e),(e||t).stats.aborted=!0,new $r(r)}var $r=function(t){function e(e){var i;return(i=t.call(this,e.error.message)||this).data=void 0,i.data=e,i}return d(e,t),e}(p(Error)),Vr=function(){function t(t,e){this.subtle=void 0,this.aesIV=void 0,this.subtle=t,this.aesIV=e}return t.prototype.decrypt=function(t,e){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t)},t}(),Yr=function(){function t(t,e){this.subtle=void 0,this.key=void 0,this.subtle=t,this.key=e}return t.prototype.expandKey=function(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])},t}();function Wr(t){var e=t.byteLength,i=e&&new DataView(t.buffer).getUint8(e-1);return i?ft(t,0,e-i):t}var jr=function(){function t(){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()}var e=t.prototype;return e.uint8ArrayToUint32Array_=function(t){for(var e=new DataView(t),i=new Uint32Array(4),r=0;r<4;r++)i[r]=e.getUint32(4*r);return i},e.initTable=function(){var t=this.sBox,e=this.invSBox,i=this.subMix,r=i[0],s=i[1],n=i[2],a=i[3],o=this.invSubMix,l=o[0],h=o[1],d=o[2],u=o[3],c=new Uint32Array(256),f=0,g=0,m=0;for(m=0;m<256;m++)c[m]=m<128?m<<1:m<<1^283;for(m=0;m<256;m++){var p=g^g<<1^g<<2^g<<3^g<<4;p=p>>>8^255&p^99,t[f]=p,e[p]=f;var v=c[f],y=c[v],E=c[y],T=257*c[p]^16843008*p;r[f]=T<<24|T>>>8,s[f]=T<<16|T>>>16,n[f]=T<<8|T>>>24,a[f]=T,T=16843009*E^65537*y^257*v^16843008*f,l[p]=T<<24|T>>>8,h[p]=T<<16|T>>>16,d[p]=T<<8|T>>>24,u[p]=T,f?(f=v^c[c[c[E^v]]],g^=c[c[g]]):f=g=1}},e.expandKey=function(t){for(var e=this.uint8ArrayToUint32Array_(t),i=!0,r=0;r<e.length&&i;)i=e[r]===this.key[r],r++;if(!i){this.key=e;var s=this.keySize=e.length;if(4!==s&&6!==s&&8!==s)throw new Error("Invalid aes key size="+s);var n,a,o,l,h=this.ksRows=4*(s+6+1),d=this.keySchedule=new Uint32Array(h),u=this.invKeySchedule=new Uint32Array(h),c=this.sBox,f=this.rcon,g=this.invSubMix,m=g[0],p=g[1],v=g[2],y=g[3];for(n=0;n<h;n++)n<s?o=d[n]=e[n]:(l=o,n%s==0?(l=c[(l=l<<8|l>>>24)>>>24]<<24|c[l>>>16&255]<<16|c[l>>>8&255]<<8|c[255&l],l^=f[n/s|0]<<24):s>6&&n%s==4&&(l=c[l>>>24]<<24|c[l>>>16&255]<<16|c[l>>>8&255]<<8|c[255&l]),d[n]=o=(d[n-s]^l)>>>0);for(a=0;a<h;a++)n=h-a,l=3&a?d[n]:d[n-4],u[a]=a<4||n<=4?l:m[c[l>>>24]]^p[c[l>>>16&255]]^v[c[l>>>8&255]]^y[c[255&l]],u[a]=u[a]>>>0}},e.networkToHostOrderSwap=function(t){return t<<24|(65280&t)<<8|(16711680&t)>>8|t>>>24},e.decrypt=function(t,e,i){for(var r,s,n,a,o,l,h,d,u,c,f,g,m,p,v=this.keySize+6,y=this.invKeySchedule,E=this.invSBox,T=this.invSubMix,S=T[0],A=T[1],L=T[2],R=T[3],b=this.uint8ArrayToUint32Array_(i),k=b[0],D=b[1],I=b[2],w=b[3],C=new Int32Array(t),_=new Int32Array(C.length),P=this.networkToHostOrderSwap;e<C.length;){for(u=P(C[e]),c=P(C[e+1]),f=P(C[e+2]),g=P(C[e+3]),o=u^y[0],l=g^y[1],h=f^y[2],d=c^y[3],m=4,p=1;p<v;p++)r=S[o>>>24]^A[l>>16&255]^L[h>>8&255]^R[255&d]^y[m],s=S[l>>>24]^A[h>>16&255]^L[d>>8&255]^R[255&o]^y[m+1],n=S[h>>>24]^A[d>>16&255]^L[o>>8&255]^R[255&l]^y[m+2],a=S[d>>>24]^A[o>>16&255]^L[l>>8&255]^R[255&h]^y[m+3],o=r,l=s,h=n,d=a,m+=4;r=E[o>>>24]<<24^E[l>>16&255]<<16^E[h>>8&255]<<8^E[255&d]^y[m],s=E[l>>>24]<<24^E[h>>16&255]<<16^E[d>>8&255]<<8^E[255&o]^y[m+1],n=E[h>>>24]<<24^E[d>>16&255]<<16^E[o>>8&255]<<8^E[255&l]^y[m+2],a=E[d>>>24]<<24^E[o>>16&255]<<16^E[l>>8&255]<<8^E[255&h]^y[m+3],_[e]=P(r^k),_[e+1]=P(a^D),_[e+2]=P(n^I),_[e+3]=P(s^w),k=u,D=c,I=f,w=g,e+=4}return _.buffer},t}(),qr=16,Xr=function(){function t(t,e){var i=(void 0===e?{}:e).removePKCS7Padding,r=void 0===i||i;if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.useSoftware=t.enableSoftwareAES,this.removePKCS7Padding=r,r)try{var s=self.crypto;s&&(this.subtle=s.subtle||s.webkitSubtle)}catch(t){}this.useSoftware=!this.subtle}var e=t.prototype;return e.destroy=function(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null},e.isSync=function(){return this.useSoftware},e.flush=function(){var t=this.currentResult,e=this.remainderData;if(!t||e)return this.reset(),null;var i=new Uint8Array(t);return this.reset(),this.removePKCS7Padding?Wr(i):i},e.reset=function(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)},e.decrypt=function(t,e,i){var r=this;return this.useSoftware?new Promise((function(s,n){r.softwareDecrypt(new Uint8Array(t),e,i);var a=r.flush();a?s(a.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))})):this.webCryptoDecrypt(new Uint8Array(t),e,i)},e.softwareDecrypt=function(t,e,i){var r=this.currentIV,s=this.currentResult,n=this.remainderData;this.logOnce("JS AES decrypt"),n&&(t=ie(n,t),this.remainderData=null);var a=this.getValidChunk(t);if(!a.length)return null;r&&(i=r);var o=this.softwareDecrypter;o||(o=this.softwareDecrypter=new jr),o.expandKey(e);var l=s;return this.currentResult=o.decrypt(a.buffer,0,i),this.currentIV=ft(a,-16).buffer,l||null},e.webCryptoDecrypt=function(t,e,i){var r=this;if(this.key!==e||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,e,i));this.key=e,this.fastAesKey=new Yr(this.subtle,e)}return this.fastAesKey.expandKey().then((function(e){return r.subtle?(r.logOnce("WebCrypto AES decrypt"),new Vr(r.subtle,new Uint8Array(i)).decrypt(t.buffer,e)):Promise.reject(new Error("web crypto not initialized"))})).catch((function(s){return F.warn("[decrypter]: WebCrypto Error, disable WebCrypto API, "+s.name+": "+s.message),r.onWebCryptoError(t,e,i)}))},e.onWebCryptoError=function(t,e,i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,i);var r=this.flush();if(r)return r.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")},e.getValidChunk=function(t){var e=t,i=t.length-t.length%qr;return i!==t.length&&(e=ft(t,0,i),this.remainderData=ft(t,i)),e},e.logOnce=function(t){this.logEnabled&&(F.log("[decrypter]: "+t),this.logEnabled=!1)},t}(),zr={toString:function(t){for(var e="",i=t.length,r=0;r<i;r++)e+="["+t.start(r).toFixed(3)+"-"+t.end(r).toFixed(3)+"]";return e}},Qr={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"},Jr=function(t){function e(e,i,r,s,n){var a;return(a=t.call(this)||this).hls=void 0,a.fragPrevious=null,a.fragCurrent=null,a.fragmentTracker=void 0,a.transmuxer=null,a._state=Qr.STOPPED,a.playlistType=void 0,a.media=null,a.mediaBuffer=null,a.config=void 0,a.bitrateTest=!1,a.lastCurrentTime=0,a.nextLoadPosition=0,a.startPosition=0,a.startTimeOffset=null,a.loadedmetadata=!1,a.retryDate=0,a.levels=null,a.fragmentLoader=void 0,a.keyLoader=void 0,a.levelLastLoaded=null,a.startFragRequested=!1,a.decrypter=void 0,a.initPTS=[],a.onvseeking=null,a.onvended=null,a.logPrefix="",a.log=void 0,a.warn=void 0,a.playlistType=n,a.logPrefix=s,a.log=F.log.bind(F,s+":"),a.warn=F.warn.bind(F,s+":"),a.hls=e,a.fragmentLoader=new Gr(e.config),a.keyLoader=r,a.fragmentTracker=i,a.config=e.config,a.decrypter=new Xr(e.config),e.on(D.MANIFEST_LOADED,a.onManifestLoaded,v(a)),a}d(e,t);var i=e.prototype;return i.doTick=function(){this.onTickEnd()},i.onTickEnd=function(){},i.startLoad=function(t){},i.stopLoad=function(){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);var t=this.fragCurrent;null!=t&&t.loader&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=Qr.STOPPED},i._streamEnded=function(t,e){if(e.live||t.nextStart||!t.end||!this.media)return!1;var i=e.partList;if(null!=i&&i.length){var r=i[i.length-1];return Ir.isBuffered(this.media,r.start+r.duration/2)}var s=e.fragments[e.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(s)},i.getLevelDetails=function(){var t;if(this.levels&&null!==this.levelLastLoaded)return null==(t=this.levelLastLoaded)?void 0:t.details},i.onMediaAttached=function(t,e){var i=this.media=this.mediaBuffer=e.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),i.addEventListener("seeking",this.onvseeking),i.addEventListener("ended",this.onvended);var r=this.config;this.levels&&r.autoStartLoad&&this.state===Qr.STOPPED&&this.startLoad(r.startPosition)},i.onMediaDetaching=function(){var t=this.media;null!=t&&t.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),t&&this.onvseeking&&this.onvended&&(t.removeEventListener("seeking",this.onvseeking),t.removeEventListener("ended",this.onvended),this.onvseeking=this.onvended=null),this.keyLoader&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()},i.onMediaSeeking=function(){var t=this.config,e=this.fragCurrent,i=this.media,r=this.mediaBuffer,s=this.state,n=i?i.currentTime:0,a=Ir.bufferInfo(r||i,n,t.maxBufferHole);if(this.log("media seeking to "+(R(n)?n.toFixed(3):n)+", state: "+s),this.state===Qr.ENDED)this.resetLoadingState();else if(e){var o=t.maxFragLookUpTolerance,l=e.start-o,h=e.start+e.duration+o;if(!a.len||h<a.start||l>a.end){var d=n>h;(n<l||d)&&(d&&e.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),e.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}i&&(this.fragmentTracker.removeFragmentsInRange(n,1/0,this.playlistType,!0),this.lastCurrentTime=n),this.loadedmetadata||a.len||(this.nextLoadPosition=this.startPosition=n),this.tickImmediate()},i.onMediaEnded=function(){this.startPosition=this.lastCurrentTime=0},i.onManifestLoaded=function(t,e){this.startTimeOffset=e.startTimeOffset,this.initPTS=[]},i.onHandlerDestroying=function(){this.hls.off(D.MANIFEST_LOADED,this.onManifestLoaded,this),this.stopLoad(),t.prototype.onHandlerDestroying.call(this),this.hls=null},i.onHandlerDestroyed=function(){this.state=Qr.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,t.prototype.onHandlerDestroyed.call(this)},i.loadFragment=function(t,e,i){this._loadFragForPlayback(t,e,i)},i._loadFragForPlayback=function(t,e,i){var r=this,s=function(e){if(r.fragContextChanged(t))return r.warn("Fragment "+t.sn+(e.part?" p: "+e.part.index:"")+" of level "+t.level+" was dropped during download."),void r.fragmentTracker.removeFragment(t);t.stats.chunkCount++,r._handleFragmentLoadProgress(e)};this._doFragLoad(t,e,i,s).then((function(e){if(e){var i=r.state;r.fragContextChanged(t)?(i===Qr.FRAG_LOADING||!r.fragCurrent&&i===Qr.PARSING)&&(r.fragmentTracker.removeFragment(t),r.state=Qr.IDLE):("payload"in e&&(r.log("Loaded fragment "+t.sn+" of level "+t.level),r.hls.trigger(D.FRAG_LOADED,e)),r._handleFragmentLoadComplete(e))}})).catch((function(e){r.state!==Qr.STOPPED&&r.state!==Qr.ERROR&&(r.warn("Frag error: "+((null==e?void 0:e.message)||e)),r.resetFragmentLoading(t))}))},i.clearTrackerIfNeeded=function(t){var e,i=this.fragmentTracker;if(i.getState(t)===Lr.APPENDING){var r=t.type,s=this.getFwdBufferInfo(this.mediaBuffer,r),n=Math.max(t.duration,s?s.len:this.config.maxBufferLength),a=this.backtrackFragment;(1==(a?t.sn-a.sn:0)||this.reduceMaxBufferLength(n,t.duration))&&i.removeFragment(t)}else 0===(null==(e=this.mediaBuffer)?void 0:e.buffered.length)?i.removeAllFragments():i.hasParts(t.type)&&(i.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),i.getState(t)===Lr.PARTIAL&&i.removeFragment(t))},i.checkLiveUpdate=function(t){if(t.updated&&!t.live){var e=t.fragments[t.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type})}t.fragments[0]||(t.deltaUpdateFailed=!0)},i.flushMainBuffer=function(t,e,i){if(void 0===i&&(i=null),t-e){var r={startOffset:t,endOffset:e,type:i};this.hls.trigger(D.BUFFER_FLUSHING,r)}},i._loadInitSegment=function(t,e){var i=this;this._doFragLoad(t,e).then((function(e){if(!e||i.fragContextChanged(t)||!i.levels)throw new Error("init load aborted");return e})).then((function(e){var r=i.hls,s=e.payload,n=t.decryptdata;if(s&&s.byteLength>0&&null!=n&&n.key&&n.iv&&"AES-128"===n.method){var a=self.performance.now();return i.decrypter.decrypt(new Uint8Array(s),n.key.buffer,n.iv.buffer).catch((function(e){throw r.trigger(D.ERROR,{type:I.MEDIA_ERROR,details:w.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e})).then((function(s){var n=self.performance.now();return r.trigger(D.FRAG_DECRYPTED,{frag:t,payload:s,stats:{tstart:a,tdecrypt:n}}),e.payload=s,i.completeInitSegmentLoad(e)}))}return i.completeInitSegmentLoad(e)})).catch((function(e){i.state!==Qr.STOPPED&&i.state!==Qr.ERROR&&(i.warn(e),i.resetFragmentLoading(t))}))},i.completeInitSegmentLoad=function(t){if(!this.levels)throw new Error("init load aborted, missing levels");var e=t.frag.stats;this.state=Qr.IDLE,t.frag.data=new Uint8Array(t.payload),e.parsing.start=e.buffering.start=self.performance.now(),e.parsing.end=e.buffering.end=self.performance.now(),this.tick()},i.fragContextChanged=function(t){var e=this.fragCurrent;return!t||!e||t.sn!==e.sn||t.level!==e.level},i.fragBufferedComplete=function(t,e){var i,r,s,n,a=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log("Buffered "+t.type+" sn: "+t.sn+(e?" part: "+e.index:"")+" of "+(this.playlistType===Qe.MAIN?"level":"track")+" "+t.level+" (frag:["+(null!=(i=t.startPTS)?i:NaN).toFixed(3)+"-"+(null!=(r=t.endPTS)?r:NaN).toFixed(3)+"] > buffer:"+(a?zr.toString(Ir.getBuffered(a)):"(detached)")+")"),"initSegment"!==t.sn){var o;if(t.type!==Qe.SUBTITLE){var l=t.elementaryStreams;if(!Object.keys(l).some((function(t){return!!l[t]})))return void(this.state=Qr.IDLE)}var h=null==(o=this.levels)?void 0:o[t.level];null!=h&&h.fragmentError&&(this.log("Resetting level fragment error count of "+h.fragmentError+" on frag buffered"),h.fragmentError=0)}this.state=Qr.IDLE,a&&(!this.loadedmetadata&&t.type==Qe.MAIN&&a.buffered.length&&(null==(s=this.fragCurrent)?void 0:s.sn)===(null==(n=this.fragPrevious)?void 0:n.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())},i.seekToStartPos=function(){},i._handleFragmentLoadComplete=function(t){var e=this.transmuxer;if(e){var i=t.frag,r=t.part,s=t.partsLoaded,n=!s||0===s.length||s.some((function(t){return!t})),a=new wr(i.level,i.sn,i.stats.chunkCount+1,0,r?r.index:-1,!n);e.flush(a)}},i._handleFragmentLoadProgress=function(t){},i._doFragLoad=function(t,e,i,r){var s,n=this;void 0===i&&(i=null);var a=null==e?void 0:e.details;if(!this.levels||!a)throw new Error("frag load aborted, missing level"+(a?"":" detail")+"s");var o=null;if(!t.encrypted||null!=(s=t.decryptdata)&&s.key?!t.encrypted&&a.encryptedFragments.length&&this.keyLoader.loadClear(t,a.encryptedFragments):(this.log("Loading key for "+t.sn+" of ["+a.startSN+"-"+a.endSN+"], "+("[stream-controller]"===this.logPrefix?"level":"track")+" "+t.level),this.state=Qr.KEY_LOADING,this.fragCurrent=t,o=this.keyLoader.load(t).then((function(t){if(!n.fragContextChanged(t.frag))return n.hls.trigger(D.KEY_LOADED,t),n.state===Qr.KEY_LOADING&&(n.state=Qr.IDLE),t})),this.hls.trigger(D.KEY_LOADING,{frag:t}),null===this.fragCurrent&&(o=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))),i=Math.max(t.start,i||0),this.config.lowLatencyMode&&"initSegment"!==t.sn){var l=a.partList;if(l&&r){i>t.end&&a.fragmentHint&&(t=a.fragmentHint);var h=this.getNextPart(l,t,i);if(h>-1){var d,u=l[h];return this.log("Loading part sn: "+t.sn+" p: "+u.index+" cc: "+t.cc+" of playlist ["+a.startSN+"-"+a.endSN+"] parts [0-"+h+"-"+(l.length-1)+"] "+("[stream-controller]"===this.logPrefix?"level":"track")+": "+t.level+", target: "+parseFloat(i.toFixed(3))),this.nextLoadPosition=u.start+u.duration,this.state=Qr.FRAG_LOADING,d=o?o.then((function(i){return!i||n.fragContextChanged(i.frag)?null:n.doFragPartsLoad(t,u,e,r)})).catch((function(t){return n.handleFragLoadError(t)})):this.doFragPartsLoad(t,u,e,r).catch((function(t){return n.handleFragLoadError(t)})),this.hls.trigger(D.FRAG_LOADING,{frag:t,part:u,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):d}if(!t.url||this.loadedEndOfParts(l,i))return Promise.resolve(null)}}this.log("Loading fragment "+t.sn+" cc: "+t.cc+" "+(a?"of ["+a.startSN+"-"+a.endSN+"] ":"")+("[stream-controller]"===this.logPrefix?"level":"track")+": "+t.level+", target: "+parseFloat(i.toFixed(3))),R(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=Qr.FRAG_LOADING;var c,f=this.config.progressive;return c=f&&o?o.then((function(e){return!e||n.fragContextChanged(null==e?void 0:e.frag)?null:n.fragmentLoader.load(t,r)})).catch((function(t){return n.handleFragLoadError(t)})):Promise.all([this.fragmentLoader.load(t,f?r:void 0),o]).then((function(t){var e=t[0];return!f&&e&&r&&r(e),e})).catch((function(t){return n.handleFragLoadError(t)})),this.hls.trigger(D.FRAG_LOADING,{frag:t,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):c},i.doFragPartsLoad=function(t,e,i,r){var s=this;return new Promise((function(n,a){var o,l=[],h=null==(o=i.details)?void 0:o.partList;!function e(o){s.fragmentLoader.loadPart(t,o,r).then((function(r){l[o.index]=r;var a=r.part;s.hls.trigger(D.FRAG_LOADED,r);var d=Fi(i,t.sn,o.index+1)||Ni(h,t.sn,o.index+1);if(!d)return n({frag:t,part:a,partsLoaded:l});e(d)})).catch(a)}(e)}))},i.handleFragLoadError=function(t){if("data"in t){var e=t.data;t.data&&e.details===w.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):this.hls.trigger(D.ERROR,e)}else this.hls.trigger(D.ERROR,{type:I.OTHER_ERROR,details:w.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null},i._handleTransmuxerFlush=function(t){var e=this.getCurrentContext(t);if(e&&this.state===Qr.PARSING){var i=e.frag,r=e.part,s=e.level,n=self.performance.now();i.stats.parsing.end=n,r&&(r.stats.parsing.end=n),this.updateLevelTiming(i,r,s,t.partial)}else this.fragCurrent||this.state===Qr.STOPPED||this.state===Qr.ERROR||(this.state=Qr.IDLE)},i.getCurrentContext=function(t){var e=this.levels,i=this.fragCurrent,r=t.level,s=t.sn,n=t.part;if(null==e||!e[r])return this.warn("Levels object was unset while buffering fragment "+s+" of level "+r+". The current chunk will not be buffered."),null;var a=e[r],o=n>-1?Fi(a,s,n):null,l=o?o.fragment:Oi(a,s,i);return l?(i&&i!==l&&(l.stats=i.stats),{frag:l,part:o,level:a}):null},i.bufferFragmentData=function(t,e,i,r,s){var n;if(t&&this.state===Qr.PARSING){var a=t.data1,o=t.data2,l=a;if(a&&o&&(l=ie(a,o)),null!=(n=l)&&n.length){var h={type:t.type,frag:e,part:i,chunkMeta:r,parent:e.type,data:l};if(this.hls.trigger(D.BUFFER_APPENDING,h),t.dropped&&t.independent&&!i){if(s)return;this.flushBufferGap(e)}}}},i.flushBufferGap=function(t){var e=this.media;if(e)if(Ir.isBuffered(e,e.currentTime)){var i=e.currentTime,r=Ir.bufferInfo(e,i,0),s=t.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*s),a=Math.max(Math.min(t.start-n,r.end-n),i+n);t.start-a>n&&this.flushMainBuffer(a,t.start)}else this.flushMainBuffer(0,t.start)},i.getFwdBufferInfo=function(t,e){var i=this.getLoadPosition();return R(i)?this.getFwdBufferInfoAtPos(t,i,e):null},i.getFwdBufferInfoAtPos=function(t,e,i){var r=this.config.maxBufferHole,s=Ir.bufferInfo(t,e,r);if(0===s.len&&void 0!==s.nextStart){var n=this.fragmentTracker.getBufferedFrag(e,i);if(n&&s.nextStart<n.end)return Ir.bufferInfo(t,e,Math.max(s.nextStart,r))}return s},i.getMaxBufferLength=function(t){var e,i=this.config;return e=t?Math.max(8*i.maxBufferSize/t,i.maxBufferLength):i.maxBufferLength,Math.min(e,i.maxMaxBufferLength)},i.reduceMaxBufferLength=function(t,e){var i=this.config,r=Math.max(Math.min(t-e,i.maxBufferLength),e),s=Math.max(t-3*e,i.maxMaxBufferLength/2,r);return s>=r&&(i.maxMaxBufferLength=s,this.warn("Reduce max buffer length to "+s+"s"),!0)},i.getAppendedFrag=function(t,e){var i=this.fragmentTracker.getAppendedFrag(t,Qe.MAIN);return i&&"fragment"in i?i.fragment:i},i.getNextFragment=function(t,e){var i=e.fragments,r=i.length;if(!r)return null;var s,n=this.config,a=i[0].start;if(e.live){var o=n.initialLiveManifestSize;if(r<o)return this.warn("Not enough fragments to start playback (have: "+r+", need: "+o+")"),null;(!e.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||t<a)&&(s=this.getInitialLiveFragment(e,i),this.startPosition=this.nextLoadPosition=s?this.hls.liveSyncPosition||s.start:t)}else t<=a&&(s=i[0]);if(!s){var l=n.lowLatencyMode?e.partEnd:e.fragmentEnd;s=this.getFragmentAtPosition(t,l,e)}return this.mapToInitFragWhenRequired(s)},i.isLoopLoading=function(t,e){var i=this.fragmentTracker.getState(t);return(i===Lr.OK||i===Lr.PARTIAL&&!!t.gap)&&this.nextLoadPosition>e},i.getNextFragmentLoopLoading=function(t,e,i,r,s){var n=t.gap,a=this.getNextFragment(this.nextLoadPosition,e);if(null===a)return a;if(t=a,n&&t&&!t.gap&&i.nextStart){var o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,r);if(null!==o&&i.len+o.len>=s)return this.log('buffer full after gaps in "'+r+'" playlist starting at sn: '+t.sn),null}return t},i.mapToInitFragWhenRequired=function(t){return null==t||!t.initSegment||null!=t&&t.initSegment.data||this.bitrateTest?t:t.initSegment},i.getNextPart=function(t,e,i){for(var r=-1,s=!1,n=!0,a=0,o=t.length;a<o;a++){var l=t[a];if(n=n&&!l.independent,r>-1&&i<l.start)break;var h=l.loaded;h?r=-1:(s||l.independent||n)&&l.fragment===e&&(r=a),s=h}return r},i.loadedEndOfParts=function(t,e){var i=t[t.length-1];return i&&e>i.start&&i.loaded},i.getInitialLiveFragment=function(t,e){var i=this.fragPrevious,r=null;if(i){if(t.hasProgramDateTime&&(this.log("Live playlist, switching playlist, load frag with same PDT: "+i.programDateTime),r=Wi(e,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){var s=i.sn+1;if(s>=t.startSN&&s<=t.endSN){var n=e[s-t.startSN];i.cc===n.cc&&(r=n,this.log("Live playlist, switching playlist, load frag with next SN: "+r.sn))}r||(r=Qi(e,i.cc))&&this.log("Live playlist, switching playlist, load frag with same CC: "+r.sn)}}else{var a=this.hls.liveSyncPosition;null!==a&&(r=this.getFragmentAtPosition(a,this.bitrateTest?t.fragmentEnd:t.edge,t))}return r},i.getFragmentAtPosition=function(t,e,i){var r,s=this.config,n=this.fragPrevious,a=i.fragments,o=i.endSN,l=i.fragmentHint,h=s.maxFragLookUpTolerance,d=i.partList,u=!!(s.lowLatencyMode&&null!=d&&d.length&&l);if(u&&l&&!this.bitrateTest&&(a=a.concat(l),o=l.sn),r=t<e?ji(n,a,t,t>e-h?0:h):a[a.length-1]){var c=r.sn-i.startSN,f=this.fragmentTracker.getState(r);if((f===Lr.OK||f===Lr.PARTIAL&&r.gap)&&(n=r),n&&r.sn===n.sn&&(!u||d[0].fragment.sn>r.sn)&&n&&r.level===n.level){var g=a[c+1];r=r.sn<o&&this.fragmentTracker.getState(g)!==Lr.OK?g:null}}return r},i.synchronizeToLiveEdge=function(t){var e=this.config,i=this.media;if(i){var r=this.hls.liveSyncPosition,s=i.currentTime,n=t.fragments[0].start,a=t.edge,o=s>=n-e.maxFragLookUpTolerance&&s<=a;if(null!==r&&i.duration>r&&(s<r||!o)){var l=void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.targetduration;(!o&&i.readyState<4||s<a-l)&&(this.loadedmetadata||(this.nextLoadPosition=r),i.readyState&&(this.warn("Playback: "+s.toFixed(3)+" is located too far from the end of live sliding playlist: "+a+", reset currentTime to : "+r.toFixed(3)),i.currentTime=r))}}},i.alignPlaylists=function(t,e,i){var r=t.fragments.length;if(!r)return this.warn("No fragments in live playlist"),0;var s=t.fragments[0].start,n=!e,a=t.alignedSliding&&R(s);if(n||!a&&!s){var o=this.fragPrevious;Fr(o,i,t);var l=t.fragments[0].start;return this.log("Live playlist sliding: "+l.toFixed(2)+" start-sn: "+(e?e.startSN:"na")+"->"+t.startSN+" prev-sn: "+(o?o.sn:"na")+" fragments: "+r),l}return s},i.waitForCdnTuneIn=function(t){var e=3;return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,t.partTarget*e)},i.setStartPosition=function(t,e){var i=this.startPosition;if(i<e&&(i=-1),-1===i||-1===this.lastCurrentTime){var r=null!==this.startTimeOffset,s=r?this.startTimeOffset:t.startTimeOffset;null!==s&&R(s)?(i=e+s,s<0&&(i+=t.totalduration),i=Math.min(Math.max(e,i),e+t.totalduration),this.log("Start time offset "+s+" found in "+(r?"multivariant":"media")+" playlist, adjust startPosition to "+i),this.startPosition=i):t.live?i=this.hls.liveSyncPosition||e:this.startPosition=i=0,this.lastCurrentTime=i}this.nextLoadPosition=i},i.getLoadPosition=function(){var t=this.media,e=0;return this.loadedmetadata&&t?e=t.currentTime:this.nextLoadPosition&&(e=this.nextLoadPosition),e},i.handleFragLoadAborted=function(t,e){this.transmuxer&&"initSegment"!==t.sn&&t.stats.aborted&&(this.warn("Fragment "+t.sn+(e?" part "+e.index:"")+" of level "+t.level+" was aborted"),this.resetFragmentLoading(t))},i.resetFragmentLoading=function(t){this.fragCurrent&&(this.fragContextChanged(t)||this.state===Qr.FRAG_LOADING_WAITING_RETRY)||(this.state=Qr.IDLE)},i.onFragmentOrKeyLoadError=function(t,e){if(e.chunkMeta&&!e.frag){var i=this.getCurrentContext(e.chunkMeta);i&&(e.frag=i.frag)}var r=e.frag;if(r&&r.type===t&&this.levels)if(this.fragContextChanged(r)){var s;this.warn("Frag load error must match current frag to retry "+r.url+" > "+(null==(s=this.fragCurrent)?void 0:s.url))}else{var n=e.details===w.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(r,!0);var a=e.errorAction,o=a||{},l=o.action,h=o.retryCount,d=void 0===h?0:h,u=o.retryConfig;if(a&&l===Ji.RetryRequest&&u){this.resetStartWhenNotLoaded(this.levelLastLoaded);var c=Ki(u,d);this.warn("Fragment "+r.sn+" of "+t+" "+r.level+" errored with "+e.details+", retrying loading "+(d+1)+"/"+u.maxNumRetry+" in "+c+"ms"),a.resolved=!0,this.retryDate=self.performance.now()+c,this.state=Qr.FRAG_LOADING_WAITING_RETRY}else if(u&&a){if(this.resetFragmentErrors(t),!(d<u.maxNumRetry))return void F.warn(e.details+" reached or exceeded max retry ("+d+")");n||l===Ji.RemoveAlternatePermanently||(a.resolved=!0)}else(null==a?void 0:a.action)===Ji.SendAlternateToPenaltyBox?this.state=Qr.WAITING_LEVEL:this.state=Qr.ERROR;this.tickImmediate()}},i.reduceLengthAndFlushBuffer=function(t){if(this.state===Qr.PARSING||this.state===Qr.PARSED){var e=t.frag,i=t.parent,r=this.getFwdBufferInfo(this.mediaBuffer,i),s=r&&r.len>.5;s&&this.reduceMaxBufferLength(r.len,(null==e?void 0:e.duration)||10);var n=!s;return n&&this.warn("Buffer full error while media.currentTime is not buffered, flush "+i+" buffer"),e&&(this.fragmentTracker.removeFragment(e),this.nextLoadPosition=e.start),this.resetLoadingState(),n}return!1},i.resetFragmentErrors=function(t){t===Qe.AUDIO&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==Qr.STOPPED&&(this.state=Qr.IDLE)},i.afterBufferFlushed=function(t,e,i){if(t){var r=Ir.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,r,i),this.state===Qr.ENDED&&this.resetLoadingState()}},i.resetLoadingState=function(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=Qr.IDLE},i.resetStartWhenNotLoaded=function(t){if(!this.loadedmetadata){this.startFragRequested=!1;var e=t?t.details:null;null!=e&&e.live?(this.startPosition=-1,this.setStartPosition(e,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}},i.resetWhenMissingContext=function(t){this.warn("The loading context changed while buffering fragment "+t.sn+" of level "+t.level+". This chunk will not be buffered."),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()},i.removeUnbufferedFrags=function(t){void 0===t&&(t=0),this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)},i.updateLevelTiming=function(t,e,i,r){var s,n=this,a=i.details;if(a){if(!Object.keys(t.elementaryStreams).reduce((function(e,s){var o=t.elementaryStreams[s];if(o){var l=o.endPTS-o.startPTS;if(l<=0)return n.warn("Could not parse fragment "+t.sn+" "+s+" duration reliably ("+l+")"),e||!1;var h=r?0:Di(a,t,o.startPTS,o.endPTS,o.startDTS,o.endDTS);return n.hls.trigger(D.LEVEL_PTS_UPDATED,{details:a,level:i,drift:h,type:s,frag:t,start:o.startPTS,end:o.endPTS}),!0}return e}),!1)&&null===(null==(s=this.transmuxer)?void 0:s.error)){var o=new Error("Found no media in fragment "+t.sn+" of level "+t.level+" resetting transmuxer to fallback to playlist timing");if(0===i.fragmentError&&(i.fragmentError++,t.gap=!0,this.fragmentTracker.removeFragment(t),this.fragmentTracker.fragBuffered(t,!0)),this.warn(o.message),this.hls.trigger(D.ERROR,{type:I.MEDIA_ERROR,details:w.FRAG_PARSING_ERROR,fatal:!1,error:o,frag:t,reason:"Found no media in msn "+t.sn+' of level "'+i.url+'"'}),!this.hls)return;this.resetTransmuxer()}this.state=Qr.PARSED,this.hls.trigger(D.FRAG_PARSED,{frag:t,part:e})}else this.warn("level.details undefined")},i.resetTransmuxer=function(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)},i.recoverWorkerError=function(t){"demuxerWorker"===t.event&&(this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())},o(e,[{key:"state",get:function(){return this._state},set:function(t){var e=this._state;e!==t&&(this._state=t,this.log(e+"->"+t))}}]),e}(Ar),Zr=function(){function t(){this.chunks=[],this.dataLength=0}var e=t.prototype;return e.push=function(t){this.chunks.push(t),this.dataLength+=t.length},e.flush=function(){var t,e=this.chunks,i=this.dataLength;return e.length?(t=1===e.length?e[0]:ts(e,i),this.reset(),t):new Uint8Array(0)},e.reset=function(){this.chunks.length=0,this.dataLength=0},t}();function ts(t,e){for(var i=new Uint8Array(e),r=0,s=0;s<t.length;s++){var n=t[s];i.set(n,r),r+=n.length}return i}function es(t,e){return void 0===t&&(t=""),void 0===e&&(e=9e4),{type:t,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}var is=function(){function t(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}var e=t.prototype;return e.resetInitSegment=function(t,e,i,r){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}},e.resetTimeStamp=function(t){this.initPTS=t,this.resetContiguity()},e.resetContiguity=function(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0},e.canParse=function(t,e){return!1},e.appendFrame=function(t,e,i){},e.demux=function(t,e){this.cachedData&&(t=ie(this.cachedData,t),this.cachedData=null);var i,r=vt(t,0),s=r?r.length:0,n=this._audioTrack,a=this._id3Track,o=r?Tt(r):void 0,l=t.length;for((null===this.basePTS||0===this.frameIndex&&R(o))&&(this.basePTS=rs(o,e,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),r&&r.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:li.audioId3,duration:Number.POSITIVE_INFINITY});s<l;){if(this.canParse(t,s)){var h=this.appendFrame(n,t,s);h?(this.frameIndex++,this.lastPTS=h.sample.pts,i=s+=h.length):s=l}else Et(t,s)?(r=vt(t,s),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:li.audioId3,duration:Number.POSITIVE_INFINITY}),i=s+=r.length):s++;if(s===l&&i!==l){var d=ft(t,i);this.cachedData?this.cachedData=ie(this.cachedData,d):this.cachedData=d}}return{audioTrack:n,videoTrack:es(),id3Track:a,textTrack:es()}},e.demuxSampleAes=function(t,e,i){return Promise.reject(new Error("["+this+"] This demuxer does not support Sample-AES decryption"))},e.flush=function(t){var e=this.cachedData;return e&&(this.cachedData=null,this.demux(e,0)),{audioTrack:this._audioTrack,videoTrack:es(),id3Track:this._id3Track,textTrack:es()}},e.destroy=function(){},t}(),rs=function(t,e,i){return R(t)?90*t:9e4*e+(i?9e4*i.baseTime/i.timescale:0)};function ss(t,e,i,r){var s,n,a,o,l=navigator.userAgent.toLowerCase(),h=r,d=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];s=1+((192&e[i+2])>>>6);var u=(60&e[i+2])>>>2;if(!(u>d.length-1))return a=(1&e[i+2])<<2,a|=(192&e[i+3])>>>6,F.log("manifest codec:"+r+", ADTS type:"+s+", samplingIndex:"+u),/firefox/i.test(l)?u>=6?(s=5,o=new Array(4),n=u-3):(s=2,o=new Array(2),n=u):-1!==l.indexOf("android")?(s=2,o=new Array(2),n=u):(s=5,o=new Array(4),r&&(-1!==r.indexOf("mp4a.40.29")||-1!==r.indexOf("mp4a.40.5"))||!r&&u>=6?n=u-3:((r&&-1!==r.indexOf("mp4a.40.2")&&(u>=6&&1===a||/vivaldi/i.test(l))||!r&&1===a)&&(s=2,o=new Array(2)),n=u)),o[0]=s<<3,o[0]|=(14&u)>>1,o[1]|=(1&u)<<7,o[1]|=a<<3,5===s&&(o[1]|=(14&n)>>1,o[2]=(1&n)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:d[u],channelCount:a,codec:"mp4a.40."+s,manifestCodec:h};var c=new Error("invalid ADTS sampling index:"+u);t.emit(D.ERROR,D.ERROR,{type:I.MEDIA_ERROR,details:w.FRAG_PARSING_ERROR,fatal:!0,error:c,reason:c.message})}function ns(t,e){return 255===t[e]&&240==(246&t[e+1])}function as(t,e){return 1&t[e+1]?7:9}function os(t,e){return(3&t[e+3])<<11|t[e+4]<<3|(224&t[e+5])>>>5}function ls(t,e){return e+5<t.length}function hs(t,e){return e+1<t.length&&ns(t,e)}function ds(t,e){return ls(t,e)&&ns(t,e)&&os(t,e)<=t.length-e}function us(t,e){if(hs(t,e)){var i=as(t,e);if(e+i>=t.length)return!1;var r=os(t,e);if(r<=i)return!1;var s=e+r;return s===t.length||hs(t,s)}return!1}function cs(t,e,i,r,s){if(!t.samplerate){var n=ss(e,i,r,s);if(!n)return;t.config=n.config,t.samplerate=n.samplerate,t.channelCount=n.channelCount,t.codec=n.codec,t.manifestCodec=n.manifestCodec,F.log("parsed codec:"+t.codec+", rate:"+n.samplerate+", channels:"+n.channelCount)}}function fs(t){return 9216e4/t}function gs(t,e){var i=as(t,e);if(e+i<=t.length){var r=os(t,e)-i;if(r>0)return{headerLength:i,frameLength:r}}}function ms(t,e,i,r,s){var n,a=r+s*fs(t.samplerate),o=gs(e,i);if(o){var l=o.frameLength,h=o.headerLength,d=h+l,u=Math.max(0,i+d-e.length);u?(n=new Uint8Array(d-h)).set(e.subarray(i+h,e.length),0):n=e.subarray(i+h,i+d);var c={unit:n,pts:a};return u||t.samples.push(c),{sample:c,length:d,missing:u}}var f=e.length-i;return(n=new Uint8Array(f)).set(e.subarray(i,e.length),0),{sample:{unit:n,pts:a},length:f,missing:-1}}var ps=null,vs=[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],ys=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Es=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Ts=[0,1,1,4];function Ss(t,e,i,r,s){if(!(i+24>e.length)){var n=As(e,i);if(n&&i+n.frameLength<=e.length){var a=r+s*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:e.subarray(i,i+n.frameLength),pts:a,dts:a};return t.config=[],t.channelCount=n.channelCount,t.samplerate=n.sampleRate,t.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}}function As(t,e){var i=t[e+1]>>3&3,r=t[e+1]>>1&3,s=t[e+2]>>4&15,n=t[e+2]>>2&3;if(1!==i&&0!==s&&15!==s&&3!==n){var a=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*vs[14*(3===i?3-r:3===r?3:4)+s-1],h=ys[3*(3===i?0:2===i?1:2)+n],d=3===o?1:2,u=Es[i][r],c=Ts[r],f=8*u*c,g=Math.floor(u*l/h+a)*c;if(null===ps){var m=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);ps=m?parseInt(m[1]):0}return!!ps&&ps<=87&&2===r&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:h,channelCount:d,frameLength:g,samplesPerFrame:f}}}function Ls(t,e){return!(255!==t[e]||224&~t[e+1]||!(6&t[e+1]))}function Rs(t,e){return e+1<t.length&&Ls(t,e)}function bs(t,e){var i=4;return Ls(t,e)&&i<=t.length-e}function ks(t,e){if(e+1<t.length&&Ls(t,e)){var i=4,r=As(t,e),s=i;null!=r&&r.frameLength&&(s=r.frameLength);var n=e+s;return n===t.length||Rs(t,n)}return!1}var Ds=function(t){function e(e,i){var r;return(r=t.call(this)||this).observer=void 0,r.config=void 0,r.observer=e,r.config=i,r}d(e,t);var i=e.prototype;return i.resetInitSegment=function(e,i,r,s){t.prototype.resetInitSegment.call(this,e,i,r,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:i,duration:s,inputTimeScale:9e4,dropped:0}},e.probe=function(t){if(!t)return!1;var e=vt(t,0),i=(null==e?void 0:e.length)||0;if(ks(t,i))return!1;for(var r=t.length;i<r;i++)if(us(t,i))return F.log("ADTS sync word found !"),!0;return!1},i.canParse=function(t,e){return ds(t,e)},i.appendFrame=function(t,e,i){cs(t,this.observer,e,i,t.manifestCodec);var r=ms(t,e,i,this.basePTS,this.frameIndex);if(r&&0===r.missing)return r},e}(is),Is=/\/emsg[-/]ID3/i,ws=function(){function t(t,e){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=e}var e=t.prototype;return e.resetTimeStamp=function(){},e.resetInitSegment=function(t,e,i,r){var s=this.videoTrack=es("video",1),n=this.audioTrack=es("audio",1),a=this.txtTrack=es("text",1);if(this.id3Track=es("id3",1),this.timeOffset=0,null!=t&&t.byteLength){var o=Vt(t);if(o.video){var l=o.video,h=l.id,d=l.timescale,u=l.codec;s.id=h,s.timescale=a.timescale=d,s.codec=u}if(o.audio){var c=o.audio,f=c.id,g=c.timescale,m=c.codec;n.id=f,n.timescale=g,n.codec=m}a.id=Mt.text,s.sampleDuration=0,s.duration=n.duration=r}},e.resetContiguity=function(){this.remainderData=null},t.probe=function(t){return Kt(t)},e.demux=function(t,e){this.timeOffset=e;var i=t,r=this.videoTrack,s=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=ie(this.remainderData,t));var n=ee(i);this.remainderData=n.remainder,r.samples=n.valid||new Uint8Array}else r.samples=i;var a=this.extractID3Track(r,e);return s.samples=re(e,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}},e.flush=function(){var t=this.timeOffset,e=this.videoTrack,i=this.txtTrack;e.samples=this.remainderData||new Uint8Array,this.remainderData=null;var r=this.extractID3Track(e,this.timeOffset);return i.samples=re(t,e),{videoTrack:e,audioTrack:es(),id3Track:r,textTrack:es()}},e.extractID3Track=function(t,e){var i=this.id3Track;if(t.samples.length){var r=Ht(t.samples,["emsg"]);r&&r.forEach((function(t){var r=le(t);if(Is.test(r.schemeIdUri)){var s=R(r.presentationTime)?r.presentationTime/r.timeScale:e+r.presentationTimeDelta/r.timeScale,n=4294967295===r.eventDuration?Number.POSITIVE_INFINITY:r.eventDuration/r.timeScale;n<=.001&&(n=Number.POSITIVE_INFINITY);var a=r.payload;i.samples.push({data:a,len:a.byteLength,dts:s,pts:s,type:li.emsg,duration:n})}}))}return i},e.demuxSampleAes=function(t,e,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))},e.destroy=function(){},t}(),Cs=function(t,e){var i=0,r=5;e+=r;for(var s=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);r>0;){a[0]=t[e];var o=Math.min(r,8),l=8-o;n[0]=4278190080>>>24+l<<l,s[0]=(a[0]&n[0])>>l,i=i?i<<o|s[0]:s[0],e+=1,r-=o}return i},_s=function(t){function e(e){var i;return(i=t.call(this)||this).observer=void 0,i.observer=e,i}d(e,t);var i=e.prototype;return i.resetInitSegment=function(e,i,r,s){t.prototype.resetInitSegment.call(this,e,i,r,s),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:i,duration:s,inputTimeScale:9e4,dropped:0}},i.canParse=function(t,e){return e+64<t.length},i.appendFrame=function(t,e,i){var r=Ps(t,e,i,this.basePTS,this.frameIndex);if(-1!==r)return{sample:t.samples[t.samples.length-1],length:r,missing:0}},e.probe=function(t){if(!t)return!1;var e=vt(t,0);if(!e)return!1;var i=e.length;return 11===t[i]&&119===t[i+1]&&void 0!==Tt(e)&&Cs(t,i)<16},e}(is);function Ps(t,e,i,r,s){if(i+8>e.length)return-1;if(11!==e[i]||119!==e[i+1])return-1;var n=e[i+4]>>6;if(n>=3)return-1;var a=[48e3,44100,32e3][n],o=63&e[i+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+n];if(i+l>e.length)return-1;var h=e[i+6]>>5,d=0;2===h?d+=2:(1&h&&1!==h&&(d+=2),4&h&&(d+=2));var u=(e[i+6]<<8|e[i+7])>>12-d&1,c=[2,1,2,3,3,4,4,5][h]+u,f=e[i+5]>>3,g=7&e[i+5],m=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|h<<3|u<<2|o>>4,o<<4&224]),p=r+s*(1536/a*9e4),v=e.subarray(i,i+l);return t.config=m,t.channelCount=c,t.samplerate=a,t.samples.push({unit:v,pts:p}),l}var xs=function(){function t(){this.VideoSample=null}var e=t.prototype;return e.createVideoSample=function(t,e,i,r){return{key:t,frame:!1,pts:e,dts:i,units:[],debug:r,length:0}},e.getLastNalUnit=function(t){var e,i,r=this.VideoSample;if(r&&0!==r.units.length||(r=t[t.length-1]),null!=(e=r)&&e.units){var s=r.units;i=s[s.length-1]}return i},e.pushAccessUnit=function(t,e){if(t.units.length&&t.frame){if(void 0===t.pts){var i=e.samples,r=i.length;if(!r)return void e.dropped++;var s=i[r-1];t.pts=s.pts,t.dts=s.dts}e.samples.push(t)}t.debug.length&&F.log(t.pts+"/"+t.dts+":"+t.debug)},t}(),Ms=function(){function t(t){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}var e=t.prototype;return e.loadWord=function(){var t=this.data,e=this.bytesAvailable,i=t.byteLength-e,r=new Uint8Array(4),s=Math.min(4,e);if(0===s)throw new Error("no bytes available");r.set(t.subarray(i,i+s)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=8*s,this.bytesAvailable-=s},e.skipBits=function(t){var e;t=Math.min(t,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(t-=this.bitsAvailable,t-=(e=t>>3)<<3,this.bytesAvailable-=e,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)},e.readBits=function(t){var e=Math.min(this.bitsAvailable,t),i=this.word>>>32-e;if(t>32&&F.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0)this.word<<=e;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return(e=t-e)>0&&this.bitsAvailable?i<<e|this.readBits(e):i},e.skipLZ=function(){var t;for(t=0;t<this.bitsAvailable;++t)if(this.word&2147483648>>>t)return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()},e.skipUEG=function(){this.skipBits(1+this.skipLZ())},e.skipEG=function(){this.skipBits(1+this.skipLZ())},e.readUEG=function(){var t=this.skipLZ();return this.readBits(t+1)-1},e.readEG=function(){var t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)},e.readBoolean=function(){return 1===this.readBits(1)},e.readUByte=function(){return this.readBits(8)},e.readUShort=function(){return this.readBits(16)},e.readUInt=function(){return this.readBits(32)},e.skipScalingList=function(t){for(var e=8,i=8,r=0;r<t;r++)0!==i&&(i=(e+this.readEG()+256)%256),e=0===i?e:i},e.readSPS=function(){var t,e,i,r=0,s=0,n=0,a=0,o=this.readUByte.bind(this),l=this.readBits.bind(this),h=this.readUEG.bind(this),d=this.readBoolean.bind(this),u=this.skipBits.bind(this),c=this.skipEG.bind(this),f=this.skipUEG.bind(this),g=this.skipScalingList.bind(this);o();var m=o();if(l(5),u(3),o(),f(),100===m||110===m||122===m||244===m||44===m||83===m||86===m||118===m||128===m){var p=h();if(3===p&&u(1),f(),f(),u(1),d())for(e=3!==p?8:12,i=0;i<e;i++)d()&&g(i<6?16:64)}f();var v=h();if(0===v)h();else if(1===v)for(u(1),c(),c(),t=h(),i=0;i<t;i++)c();f(),u(1);var y=h(),E=h(),T=l(1);0===T&&u(1),u(1),d()&&(r=h(),s=h(),n=h(),a=h());var S=[1,1];if(d()&&d())switch(o()){case 1:S=[1,1];break;case 2:S=[12,11];break;case 3:S=[10,11];break;case 4:S=[16,11];break;case 5:S=[40,33];break;case 6:S=[24,11];break;case 7:S=[20,11];break;case 8:S=[32,11];break;case 9:S=[80,33];break;case 10:S=[18,11];break;case 11:S=[15,11];break;case 12:S=[64,33];break;case 13:S=[160,99];break;case 14:S=[4,3];break;case 15:S=[3,2];break;case 16:S=[2,1];break;case 255:S=[o()<<8|o(),o()<<8|o()]}return{width:Math.ceil(16*(y+1)-2*r-2*s),height:(2-T)*(E+1)*16-(T?2:4)*(n+a),pixelRatio:S}},e.readSliceType=function(){return this.readUByte(),this.readUEG(),this.readUEG()},t}(),Os=function(t){function e(){return t.apply(this,arguments)||this}d(e,t);var i=e.prototype;return i.parseAVCPES=function(t,e,i,r,s){var n,a=this,o=this.parseAVCNALu(t,i.data),l=this.VideoSample,h=!1;i.data=null,l&&o.length&&!t.audFound&&(this.pushAccessUnit(l,t),l=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts,"")),o.forEach((function(r){var o;switch(r.type){case 1:var d=!1;n=!0;var u,c=r.data;if(h&&c.length>4){var f=new Ms(c).readSliceType();2!==f&&4!==f&&7!==f&&9!==f||(d=!0)}d&&null!=(u=l)&&u.frame&&!l.key&&(a.pushAccessUnit(l,t),l=a.VideoSample=null),l||(l=a.VideoSample=a.createVideoSample(!0,i.pts,i.dts,"")),l.frame=!0,l.key=d;break;case 5:n=!0,null!=(o=l)&&o.frame&&!l.key&&(a.pushAccessUnit(l,t),l=a.VideoSample=null),l||(l=a.VideoSample=a.createVideoSample(!0,i.pts,i.dts,"")),l.key=!0,l.frame=!0;break;case 6:n=!0,ae(r.data,1,i.pts,e.samples);break;case 7:var g,m;n=!0,h=!0;var p=r.data,v=new Ms(p).readSPS();if(!t.sps||t.width!==v.width||t.height!==v.height||(null==(g=t.pixelRatio)?void 0:g[0])!==v.pixelRatio[0]||(null==(m=t.pixelRatio)?void 0:m[1])!==v.pixelRatio[1]){t.width=v.width,t.height=v.height,t.pixelRatio=v.pixelRatio,t.sps=[p],t.duration=s;for(var y=p.subarray(1,4),E="avc1.",T=0;T<3;T++){var S=y[T].toString(16);S.length<2&&(S="0"+S),E+=S}t.codec=E}break;case 8:n=!0,t.pps=[r.data];break;case 9:n=!0,t.audFound=!0,l&&a.pushAccessUnit(l,t),l=a.VideoSample=a.createVideoSample(!1,i.pts,i.dts,"");break;case 12:n=!0;break;default:n=!1,l&&(l.debug+="unknown NAL "+r.type+" ")}l&&n&&l.units.push(r)})),r&&l&&(this.pushAccessUnit(l,t),this.VideoSample=null)},i.parseAVCNALu=function(t,e){var i,r,s=e.byteLength,n=t.naluState||0,a=n,o=[],l=0,h=-1,d=0;for(-1===n&&(h=0,d=31&e[0],n=0,l=1);l<s;)if(i=e[l++],n)if(1!==n)if(i)if(1===i){if(r=l-n-1,h>=0){var u={data:e.subarray(h,r),type:d};o.push(u)}else{var c=this.getLastNalUnit(t.samples);c&&(a&&l<=4-a&&c.state&&(c.data=c.data.subarray(0,c.data.byteLength-a)),r>0&&(c.data=ie(c.data,e.subarray(0,r)),c.state=0))}l<s?(h=l,d=31&e[l],n=0):n=-1}else n=0;else n=3;else n=i?0:2;else n=i?0:1;if(h>=0&&n>=0){var f={data:e.subarray(h,s),type:d,state:n};o.push(f)}if(0===o.length){var g=this.getLastNalUnit(t.samples);g&&(g.data=ie(g.data,e))}return t.naluState=n,o},e}(xs),Fs=function(){function t(t,e,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Xr(e,{removePKCS7Padding:!1})}var e=t.prototype;return e.decryptBuffer=function(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer)},e.decryptAacSample=function(t,e,i){var r=this,s=t[e].unit;if(!(s.length<=16)){var n=s.subarray(16,s.length-s.length%16),a=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(a).then((function(n){var a=new Uint8Array(n);s.set(a,16),r.decrypter.isSync()||r.decryptAacSamples(t,e+1,i)}))}},e.decryptAacSamples=function(t,e,i){for(;;e++){if(e>=t.length)return void i();if(!(t[e].unit.length<32||(this.decryptAacSample(t,e,i),this.decrypter.isSync())))return}},e.getAvcEncryptedData=function(t){for(var e=16*Math.floor((t.length-48)/160)+16,i=new Int8Array(e),r=0,s=32;s<t.length-16;s+=160,r+=16)i.set(t.subarray(s,s+16),r);return i},e.getAvcDecryptedUnit=function(t,e){for(var i=new Uint8Array(e),r=0,s=32;s<t.length-16;s+=160,r+=16)t.set(i.subarray(r,r+16),s);return t},e.decryptAvcSample=function(t,e,i,r,s){var n=this,a=oe(s.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then((function(o){s.data=n.getAvcDecryptedUnit(a,o),n.decrypter.isSync()||n.decryptAvcSamples(t,e,i+1,r)}))},e.decryptAvcSamples=function(t,e,i,r){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,i=0){if(e>=t.length)return void r();for(var s=t[e].units;!(i>=s.length);i++){var n=s[i];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(t,e,i,r,n),this.decrypter.isSync())))return}}},t}(),Ns=188,Us=function(){function t(t,e,i){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._duration=0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=t,this.config=e,this.typeSupported=i,this.videoParser=new Os}t.probe=function(e){var i=t.syncOffset(e);return i>0&&F.warn("MPEG2-TS detected but first sync word found @ offset "+i),-1!==i},t.syncOffset=function(t){for(var e=t.length,i=Math.min(5*Ns,e-Ns)+1,r=0;r<i;){for(var s=!1,n=-1,a=0,o=r;o<e;o+=Ns){if(71!==t[o]||e-o!==Ns&&71!==t[o+Ns]){if(a)return-1;break}if(a++,-1===n&&0!==(n=o)&&(i=Math.min(n+99*Ns,t.length-Ns)+1),s||(s=0===Bs(t,o)),s&&a>1&&(0===n&&a>2||o+Ns>i))return n}r++}return-1},t.createTrack=function(t,e){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:Mt[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===t?e:void 0}};var e=t.prototype;return e.resetInitSegment=function(e,i,r,s){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=t.createTrack("video"),this._audioTrack=t.createTrack("audio",s),this._id3Track=t.createTrack("id3"),this._txtTrack=t.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=i,this.videoCodec=r,this._duration=s},e.resetTimeStamp=function(){},e.resetContiguity=function(){var t=this._audioTrack,e=this._videoTrack,i=this._id3Track;t&&(t.pesData=null),e&&(e.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null},e.demux=function(e,i,r,s){var n;void 0===r&&(r=!1),void 0===s&&(s=!1),r||(this.sampleAes=null);var a=this._videoTrack,o=this._audioTrack,l=this._id3Track,h=this._txtTrack,d=a.pid,u=a.pesData,c=o.pid,f=l.pid,g=o.pesData,m=l.pesData,p=null,v=this.pmtParsed,y=this._pmtId,E=e.length;if(this.remainderData&&(E=(e=ie(this.remainderData,e)).length,this.remainderData=null),E<Ns&&!s)return this.remainderData=e,{audioTrack:o,videoTrack:a,id3Track:l,textTrack:h};var T=Math.max(0,t.syncOffset(e));(E-=(E-T)%Ns)<e.byteLength&&!s&&(this.remainderData=new Uint8Array(e.buffer,E,e.buffer.byteLength-E));for(var S=0,A=T;A<E;A+=Ns)if(71===e[A]){var L=!!(64&e[A+1]),R=Bs(e,A),b=void 0;if((48&e[A+3])>>4>1){if((b=A+5+e[A+4])===A+Ns)continue}else b=A+4;switch(R){case d:L&&(u&&(n=Vs(u))&&this.videoParser.parseAVCPES(a,h,n,!1,this._duration),u={data:[],size:0}),u&&(u.data.push(e.subarray(b,A+Ns)),u.size+=A+Ns-b);break;case c:if(L){if(g&&(n=Vs(g)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,n);break;case"mp3":this.parseMPEGPES(o,n);break;case"ac3":this.parseAC3PES(o,n)}g={data:[],size:0}}g&&(g.data.push(e.subarray(b,A+Ns)),g.size+=A+Ns-b);break;case f:L&&(m&&(n=Vs(m))&&this.parseID3PES(l,n),m={data:[],size:0}),m&&(m.data.push(e.subarray(b,A+Ns)),m.size+=A+Ns-b);break;case 0:L&&(b+=e[b]+1),y=this._pmtId=Gs(e,b);break;case y:L&&(b+=e[b]+1);var k=Ks(e,b,this.typeSupported,r,this.observer);(d=k.videoPid)>0&&(a.pid=d,a.segmentCodec=k.segmentVideoCodec),(c=k.audioPid)>0&&(o.pid=c,o.segmentCodec=k.segmentAudioCodec),(f=k.id3Pid)>0&&(l.pid=f),null===p||v||(F.warn("MPEG-TS PMT found at "+A+" after unknown PID '"+p+"'. Backtracking to sync byte @"+T+" to parse all TS packets."),p=null,A=T-188),v=this.pmtParsed=!0;break;case 17:case 8191:break;default:p=R}}else S++;S>0&&Hs(this.observer,new Error("Found "+S+" TS packet/s that do not start with 0x47")),a.pesData=u,o.pesData=g,l.pesData=m;var D={audioTrack:o,videoTrack:a,id3Track:l,textTrack:h};return s&&this.extractRemainingSamples(D),D},e.flush=function(){var t,e=this.remainderData;return this.remainderData=null,t=e?this.demux(e,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t},e.extractRemainingSamples=function(t){var e,i=t.audioTrack,r=t.videoTrack,s=t.id3Track,n=t.textTrack,a=r.pesData,o=i.pesData,l=s.pesData;if(a&&(e=Vs(a))?(this.videoParser.parseAVCPES(r,n,e,!0,this._duration),r.pesData=null):r.pesData=a,o&&(e=Vs(o))){switch(i.segmentCodec){case"aac":this.parseAACPES(i,e);break;case"mp3":this.parseMPEGPES(i,e);break;case"ac3":this.parseAC3PES(i,e)}i.pesData=null}else null!=o&&o.size&&F.log("last AAC PES packet truncated,might overlap between fragments"),i.pesData=o;l&&(e=Vs(l))?(this.parseID3PES(s,e),s.pesData=null):s.pesData=l},e.demuxSampleAes=function(t,e,i){var r=this.demux(t,i,!0,!this.config.progressive),s=this.sampleAes=new Fs(this.observer,this.config,e);return this.decrypt(r,s)},e.decrypt=function(t,e){return new Promise((function(i){var r=t.audioTrack,s=t.videoTrack;r.samples&&"aac"===r.segmentCodec?e.decryptAacSamples(r.samples,0,(function(){s.samples?e.decryptAvcSamples(s.samples,0,0,(function(){i(t)})):i(t)})):s.samples&&e.decryptAvcSamples(s.samples,0,0,(function(){i(t)}))}))},e.destroy=function(){this._duration=0},e.parseAACPES=function(t,e){var i,r,s,n=0,a=this.aacOverFlow,o=e.data;if(a){this.aacOverFlow=null;var l=a.missing,h=a.sample.unit.byteLength;if(-1===l)o=ie(a.sample.unit,o);else{var d=h-l;a.sample.unit.set(o.subarray(0,l),d),t.samples.push(a.sample),n=a.missing}}for(i=n,r=o.length;i<r-1&&!hs(o,i);i++);if(i!==n){var u,c=i<r-1;if(u=c?"AAC PES did not start with ADTS header,offset:"+i:"No ADTS header found in AAC PES",Hs(this.observer,new Error(u),c),!c)return}if(cs(t,this.observer,o,i,this.audioCodec),void 0!==e.pts)s=e.pts;else{if(!a)return void F.warn("[tsdemuxer]: AAC PES unknown PTS");var f=fs(t.samplerate);s=a.sample.pts+f}for(var g,m=0;i<r;){if(i+=(g=ms(t,o,i,s,m)).length,g.missing){this.aacOverFlow=g;break}for(m++;i<r-1&&!hs(o,i);i++);}},e.parseMPEGPES=function(t,e){var i=e.data,r=i.length,s=0,n=0,a=e.pts;if(void 0!==a)for(;n<r;)if(Rs(i,n)){var o=Ss(t,i,n,a,s);if(!o)break;n+=o.length,s++}else n++;else F.warn("[tsdemuxer]: MPEG PES unknown PTS")},e.parseAC3PES=function(t,e){var i=e.data,r=e.pts;if(void 0!==r)for(var s,n=i.length,a=0,o=0;o<n&&(s=Ps(t,i,o,r,a++))>0;)o+=s;else F.warn("[tsdemuxer]: AC3 PES unknown PTS")},e.parseID3PES=function(t,e){if(void 0!==e.pts){var i=h({},e,{type:this._videoTrack?li.emsg:li.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(i)}else F.warn("[tsdemuxer]: ID3 PES unknown PTS")},t}();function Bs(t,e){return((31&t[e+1])<<8)+t[e+2]}function Gs(t,e){return(31&t[e+10])<<8|t[e+11]}function Ks(t,e,i,r,s){var n={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},a=e+3+((15&t[e+1])<<8|t[e+2])-4;for(e+=12+((15&t[e+10])<<8|t[e+11]);e<a;){var o=Bs(t,e),l=(15&t[e+3])<<8|t[e+4];switch(t[e]){case 207:if(!r){$s("ADTS AAC");break}case 15:-1===n.audioPid&&(n.audioPid=o);break;case 21:-1===n.id3Pid&&(n.id3Pid=o);break;case 219:if(!r){$s("H.264");break}case 27:-1===n.videoPid&&(n.videoPid=o,n.segmentVideoCodec="avc");break;case 3:case 4:i.mpeg||i.mp3?-1===n.audioPid&&(n.audioPid=o,n.segmentAudioCodec="mp3"):F.log("MPEG audio found, not supported in this browser");break;case 193:if(!r){$s("AC-3");break}case 129:i.ac3?-1===n.audioPid&&(n.audioPid=o,n.segmentAudioCodec="ac3"):F.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===n.audioPid&&l>0)for(var h=e+5,d=l;d>2;){106===t[h]&&(!0!==i.ac3?F.log("AC-3 audio found, not supported in this browser for now"):(n.audioPid=o,n.segmentAudioCodec="ac3"));var u=t[h+1]+2;h+=u,d-=u}break;case 194:case 135:return Hs(s,new Error("Unsupported EC-3 in M2TS found")),n;case 36:return Hs(s,new Error("Unsupported HEVC in M2TS found")),n}e+=l+5}return n}function Hs(t,e,i){F.warn("parsing error: "+e.message),t.emit(D.ERROR,D.ERROR,{type:I.MEDIA_ERROR,details:w.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,error:e,reason:e.message})}function $s(t){F.log(t+" with AES-128-CBC encryption found in unencrypted stream")}function Vs(t){var e,i,r,s,n,a=0,o=t.data;if(!t||0===t.size)return null;for(;o[0].length<19&&o.length>1;)o[0]=ie(o[0],o[1]),o.splice(1,1);if(1===((e=o[0])[0]<<16)+(e[1]<<8)+e[2]){if((i=(e[4]<<8)+e[5])&&i>t.size-6)return null;var l=e[7];192&l&&(s=536870912*(14&e[9])+4194304*(255&e[10])+16384*(254&e[11])+128*(255&e[12])+(254&e[13])/2,64&l?s-(n=536870912*(14&e[14])+4194304*(255&e[15])+16384*(254&e[16])+128*(255&e[17])+(254&e[18])/2)>54e5&&(F.warn(Math.round((s-n)/9e4)+"s delta between PTS and DTS, align them"),s=n):n=s);var h=(r=e[8])+9;if(t.size<=h)return null;t.size-=h;for(var d=new Uint8Array(t.size),u=0,c=o.length;u<c;u++){var f=(e=o[u]).byteLength;if(h){if(h>f){h-=f;continue}e=e.subarray(h),f-=h,h=0}d.set(e,a),a+=f}return i&&(i-=r+3),{data:d,pts:s,dts:n,len:i}}return null}var Ys=function(t){function e(){return t.apply(this,arguments)||this}d(e,t);var i=e.prototype;return i.resetInitSegment=function(e,i,r,s){t.prototype.resetInitSegment.call(this,e,i,r,s),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:i,duration:s,inputTimeScale:9e4,dropped:0}},e.probe=function(t){if(!t)return!1;var e=vt(t,0),i=(null==e?void 0:e.length)||0;if(e&&11===t[i]&&119===t[i+1]&&void 0!==Tt(e)&&Cs(t,i)<=16)return!1;for(var r=t.length;i<r;i++)if(ks(t,i))return F.log("MPEG Audio sync word found !"),!0;return!1},i.canParse=function(t,e){return bs(t,e)},i.appendFrame=function(t,e,i){if(null!==this.basePTS)return Ss(t,e,i,this.basePTS,this.frameIndex)},e}(is),Ws=function(){function t(){}return t.getSilentFrame=function(t,e){if("mp4a.40.2"===t){if(1===e)return new Uint8Array([0,200,0,128,35,128]);if(2===e)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===e)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===e)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===e)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===e)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===e)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])}},t}(),js=Math.pow(2,32)-1,qs=function(){function t(){}return t.init=function(){var e;for(e in t.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},t.types)t.types.hasOwnProperty(e)&&(t.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);var i=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),r=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);t.HDLR_TYPES={video:i,audio:r};var s=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),n=new Uint8Array([0,0,0,0,0,0,0,0]);t.STTS=t.STSC=t.STCO=n,t.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),t.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),t.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),t.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);var a=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);t.FTYP=t.box(t.types.ftyp,a,l,a,o),t.DINF=t.box(t.types.dinf,t.box(t.types.dref,s))},t.box=function(t){for(var e=8,i=arguments.length,r=new Array(i>1?i-1:0),s=1;s<i;s++)r[s-1]=arguments[s];for(var n=r.length,a=n;n--;)e+=r[n].byteLength;var o=new Uint8Array(e);for(o[0]=e>>24&255,o[1]=e>>16&255,o[2]=e>>8&255,o[3]=255&e,o.set(t,4),n=0,e=8;n<a;n++)o.set(r[n],e),e+=r[n].byteLength;return o},t.hdlr=function(e){return t.box(t.types.hdlr,t.HDLR_TYPES[e])},t.mdat=function(e){return t.box(t.types.mdat,e)},t.mdhd=function(e,i){i*=e;var r=Math.floor(i/(js+1)),s=Math.floor(i%(js+1));return t.box(t.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,r>>24,r>>16&255,r>>8&255,255&r,s>>24,s>>16&255,s>>8&255,255&s,85,196,0,0]))},t.mdia=function(e){return t.box(t.types.mdia,t.mdhd(e.timescale,e.duration),t.hdlr(e.type),t.minf(e))},t.mfhd=function(e){return t.box(t.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))},t.minf=function(e){return"audio"===e.type?t.box(t.types.minf,t.box(t.types.smhd,t.SMHD),t.DINF,t.stbl(e)):t.box(t.types.minf,t.box(t.types.vmhd,t.VMHD),t.DINF,t.stbl(e))},t.moof=function(e,i,r){return t.box(t.types.moof,t.mfhd(e),t.traf(r,i))},t.moov=function(e){for(var i=e.length,r=[];i--;)r[i]=t.trak(e[i]);return t.box.apply(null,[t.types.moov,t.mvhd(e[0].timescale,e[0].duration)].concat(r).concat(t.mvex(e)))},t.mvex=function(e){for(var i=e.length,r=[];i--;)r[i]=t.trex(e[i]);return t.box.apply(null,[t.types.mvex].concat(r))},t.mvhd=function(e,i){i*=e;var r=Math.floor(i/(js+1)),s=Math.floor(i%(js+1)),n=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,r>>24,r>>16&255,r>>8&255,255&r,s>>24,s>>16&255,s>>8&255,255&s,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return t.box(t.types.mvhd,n)},t.sdtp=function(e){var i,r,s=e.samples||[],n=new Uint8Array(4+s.length);for(i=0;i<s.length;i++)r=s[i].flags,n[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return t.box(t.types.sdtp,n)},t.stbl=function(e){return t.box(t.types.stbl,t.stsd(e),t.box(t.types.stts,t.STTS),t.box(t.types.stsc,t.STSC),t.box(t.types.stsz,t.STSZ),t.box(t.types.stco,t.STCO))},t.avc1=function(e){var i,r,s,n=[],a=[];for(i=0;i<e.sps.length;i++)s=(r=e.sps[i]).byteLength,n.push(s>>>8&255),n.push(255&s),n=n.concat(Array.prototype.slice.call(r));for(i=0;i<e.pps.length;i++)s=(r=e.pps[i]).byteLength,a.push(s>>>8&255),a.push(255&s),a=a.concat(Array.prototype.slice.call(r));var o=t.box(t.types.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|e.sps.length].concat(n).concat([e.pps.length]).concat(a))),l=e.width,h=e.height,d=e.pixelRatio[0],u=e.pixelRatio[1];return t.box(t.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,h>>8&255,255&h,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,t.box(t.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),t.box(t.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,u>>24,u>>16&255,u>>8&255,255&u])))},t.esds=function(t){var e=t.config.length;return new Uint8Array([0,0,0,0,3,23+e,0,1,0,4,15+e,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([e]).concat(t.config).concat([6,1,2]))},t.audioStsd=function(t){var e=t.samplerate;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,e>>8&255,255&e,0,0])},t.mp4a=function(e){return t.box(t.types.mp4a,t.audioStsd(e),t.box(t.types.esds,t.esds(e)))},t.mp3=function(e){return t.box(t.types[".mp3"],t.audioStsd(e))},t.ac3=function(e){return t.box(t.types["ac-3"],t.audioStsd(e),t.box(t.types.dac3,e.config))},t.stsd=function(e){return"audio"===e.type?"mp3"===e.segmentCodec&&"mp3"===e.codec?t.box(t.types.stsd,t.STSD,t.mp3(e)):"ac3"===e.segmentCodec?t.box(t.types.stsd,t.STSD,t.ac3(e)):t.box(t.types.stsd,t.STSD,t.mp4a(e)):t.box(t.types.stsd,t.STSD,t.avc1(e))},t.tkhd=function(e){var i=e.id,r=e.duration*e.timescale,s=e.width,n=e.height,a=Math.floor(r/(js+1)),o=Math.floor(r%(js+1));return t.box(t.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,i>>24&255,i>>16&255,i>>8&255,255&i,0,0,0,0,a>>24,a>>16&255,a>>8&255,255&a,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,s>>8&255,255&s,0,0,n>>8&255,255&n,0,0]))},t.traf=function(e,i){var r=t.sdtp(e),s=e.id,n=Math.floor(i/(js+1)),a=Math.floor(i%(js+1));return t.box(t.types.traf,t.box(t.types.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s])),t.box(t.types.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a])),t.trun(e,r.length+16+20+8+16+8+8),r)},t.trak=function(e){return e.duration=e.duration||4294967295,t.box(t.types.trak,t.tkhd(e),t.mdia(e))},t.trex=function(e){var i=e.id;return t.box(t.types.trex,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,255&i,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))},t.trun=function(e,i){var r,s,n,a,o,l,h=e.samples||[],d=h.length,u=12+16*d,c=new Uint8Array(u);for(i+=8+u,c.set(["video"===e.type?1:0,0,15,1,d>>>24&255,d>>>16&255,d>>>8&255,255&d,i>>>24&255,i>>>16&255,i>>>8&255,255&i],0),r=0;r<d;r++)n=(s=h[r]).duration,a=s.size,o=s.flags,l=s.cts,c.set([n>>>24&255,n>>>16&255,n>>>8&255,255&n,a>>>24&255,a>>>16&255,a>>>8&255,255&a,o.isLeading<<2|o.dependsOn,o.isDependedOn<<6|o.hasRedundancy<<4|o.paddingValue<<1|o.isNonSync,61440&o.degradPrio,15&o.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*r);return t.box(t.types.trun,c)},t.initSegment=function(e){t.types||t.init();var i=t.moov(e);return ie(t.FTYP,i)},t}();qs.types=void 0,qs.HDLR_TYPES=void 0,qs.STTS=void 0,qs.STSC=void 0,qs.STCO=void 0,qs.STSZ=void 0,qs.VMHD=void 0,qs.SMHD=void 0,qs.STSD=void 0,qs.FTYP=void 0,qs.DINF=void 0;var Xs=9e4;function zs(t,e,i,r){void 0===i&&(i=1),void 0===r&&(r=!1);var s=t*e*i;return r?Math.round(s):s}function Qs(t,e,i,r){return void 0===i&&(i=1),void 0===r&&(r=!1),zs(t,e,1/i,r)}function Js(t,e){return void 0===e&&(e=!1),zs(t,1e3,1/Xs,e)}function Zs(t,e){return void 0===e&&(e=1),zs(t,Xs,1/e)}var tn=1e4,en=1024,rn=1152,sn=1536,nn=null,an=null,on=function(){function t(t,e,i,r){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=t,this.config=e,this.typeSupported=i,this.ISGenerated=!1,null===nn){var s=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);nn=s?parseInt(s[1]):0}if(null===an){var n=navigator.userAgent.match(/Safari\/(\d+)/i);an=n?parseInt(n[1]):0}}var e=t.prototype;return e.destroy=function(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null},e.resetTimeStamp=function(t){F.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=t},e.resetNextTimestamp=function(){F.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1},e.resetInitSegment=function(){F.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0},e.getVideoStartPts=function(t){var e=!1,i=t.reduce((function(t,i){var r=i.pts-t;return r<-4294967296?(e=!0,ln(t,i.pts)):r>0?t:i.pts}),t[0].pts);return e&&F.debug("PTS rollover detected"),i},e.remux=function(t,e,i,r,s,n,a,o){var l,h,d,u,c,f,g=s,m=s,p=t.pid>-1,v=e.pid>-1,y=e.samples.length,E=t.samples.length>0,T=a&&y>0||y>1;if((!p||E)&&(!v||T)||this.ISGenerated||a){if(this.ISGenerated){var S,A,L,R,b=this.videoTrackConfig;!b||e.width===b.width&&e.height===b.height&&(null==(S=e.pixelRatio)?void 0:S[0])===(null==(A=b.pixelRatio)?void 0:A[0])&&(null==(L=e.pixelRatio)?void 0:L[1])===(null==(R=b.pixelRatio)?void 0:R[1])||this.resetInitSegment()}else d=this.generateIS(t,e,s,n);var k,D=this.isVideoContiguous,I=-1;if(T&&(I=hn(e.samples),!D&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,I>0){F.warn("[mp4-remuxer]: Dropped "+I+" out of "+y+" video samples due to a missing keyframe");var w=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(I),e.dropped+=I,k=m+=(e.samples[0].pts-w)/e.inputTimeScale}else-1===I&&(F.warn("[mp4-remuxer]: No keyframe found out of "+y+" video samples"),f=!1);if(this.ISGenerated){if(E&&T){var C=this.getVideoStartPts(e.samples),_=(ln(t.samples[0].pts,C)-C)/e.inputTimeScale;g+=Math.max(0,_),m+=Math.max(0,-_)}if(E){if(t.samplerate||(F.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),d=this.generateIS(t,e,s,n)),h=this.remuxAudio(t,g,this.isAudioContiguous,n,v||T||o===Qe.AUDIO?m:void 0),T){var P=h?h.endPTS-h.startPTS:0;e.inputTimeScale||(F.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),d=this.generateIS(t,e,s,n)),l=this.remuxVideo(e,m,D,P)}}else T&&(l=this.remuxVideo(e,m,D,0));l&&(l.firstKeyFrame=I,l.independent=-1!==I,l.firstKeyFramePTS=k)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(c=dn(i,s,this._initPTS,this._initDTS)),r.samples.length&&(u=un(r,s,this._initPTS))),{audio:h,video:l,initSegment:d,independent:f,text:u,id3:c}},e.generateIS=function(t,e,i,r){var s,n,a,o=t.samples,l=e.samples,h=this.typeSupported,d={},u=this._initPTS,c=!u||r,f="audio/mp4";if(c&&(s=n=1/0),t.config&&o.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":h.mpeg?(f="audio/mpeg",t.codec=""):h.mp3&&(t.codec="mp3");break;case"ac3":t.codec="ac-3"}d.audio={id:"audio",container:f,codec:t.codec,initSegment:"mp3"===t.segmentCodec&&h.mpeg?new Uint8Array(0):qs.initSegment([t]),metadata:{channelCount:t.channelCount}},c&&(a=t.inputTimeScale,u&&a===u.timescale?c=!1:s=n=o[0].pts-Math.round(a*i))}if(e.sps&&e.pps&&l.length){if(e.timescale=e.inputTimeScale,d.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:qs.initSegment([e]),metadata:{width:e.width,height:e.height}},c)if(a=e.inputTimeScale,u&&a===u.timescale)c=!1;else{var g=this.getVideoStartPts(l),m=Math.round(a*i);n=Math.min(n,ln(l[0].dts,g)-m),s=Math.min(s,g-m)}this.videoTrackConfig={width:e.width,height:e.height,pixelRatio:e.pixelRatio}}if(Object.keys(d).length)return this.ISGenerated=!0,c?(this._initPTS={baseTime:s,timescale:a},this._initDTS={baseTime:n,timescale:a}):s=a=void 0,{tracks:d,initPTS:s,timescale:a}},e.remuxVideo=function(t,e,i,r){var s,n,a=t.inputTimeScale,o=t.samples,l=[],d=o.length,u=this._initPTS,c=this.nextAvcDts,f=8,g=this.videoSampleDuration,m=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY,v=!1;if(!i||null===c){var y=e*a,E=o[0].pts-ln(o[0].dts,o[0].pts);nn&&null!==c&&Math.abs(y-E-c)<15e3?i=!0:c=y-E}for(var T=u.baseTime*a/u.timescale,S=0;S<d;S++){var A=o[S];A.pts=ln(A.pts-T,c),A.dts=ln(A.dts-T,c),A.dts<o[S>0?S-1:S].dts&&(v=!0)}v&&o.sort((function(t,e){var i=t.dts-e.dts,r=t.pts-e.pts;return i||r})),s=o[0].dts;var L=(n=o[o.length-1].dts)-s,R=L?Math.round(L/(d-1)):g||t.inputTimeScale/30;if(i){var b=s-c,k=b>R,C=b<-1;if((k||C)&&(k?F.warn("AVC: "+Js(b,!0)+" ms ("+b+"dts) hole between fragments detected at "+e.toFixed(3)):F.warn("AVC: "+Js(-b,!0)+" ms ("+b+"dts) overlapping between fragments detected at "+e.toFixed(3)),!C||c>=o[0].pts||nn)){s=c;var _=o[0].pts-b;if(k)o[0].dts=s,o[0].pts=_;else for(var P=0;P<o.length&&!(o[P].dts>_);P++)o[P].dts-=b,o[P].pts-=b;F.log("Video: Initial PTS/DTS adjusted: "+Js(_,!0)+"/"+Js(s,!0)+", delta: "+Js(b,!0)+" ms")}}for(var x=0,M=0,O=s=Math.max(0,s),N=0;N<d;N++){for(var U=o[N],B=U.units,G=B.length,K=0,H=0;H<G;H++)K+=B[H].data.length;M+=K,x+=G,U.length=K,U.dts<O?(U.dts=O,O+=R/4|0||1):O=U.dts,m=Math.min(U.pts,m),p=Math.max(U.pts,p)}n=o[d-1].dts;var $,V=M+4*x+8;try{$=new Uint8Array(V)}catch(t){return void this.observer.emit(D.ERROR,D.ERROR,{type:I.MUX_ERROR,details:w.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:V,reason:"fail allocating video mdat "+V})}var Y=new DataView($.buffer);Y.setUint32(0,V),$.set(qs.types.mdat,4);for(var W=!1,j=Number.POSITIVE_INFINITY,q=Number.POSITIVE_INFINITY,X=Number.NEGATIVE_INFINITY,z=Number.NEGATIVE_INFINITY,Q=0;Q<d;Q++){for(var J=o[Q],Z=J.units,tt=0,et=0,it=Z.length;et<it;et++){var rt=Z[et],st=rt.data,nt=rt.data.byteLength;Y.setUint32(f,nt),f+=4,$.set(st,f),f+=nt,tt+=4+nt}var at=void 0;if(Q<d-1)g=o[Q+1].dts-J.dts,at=o[Q+1].pts-J.pts;else{var ot=this.config,lt=Q>0?J.dts-o[Q-1].dts:R;if(at=Q>0?J.pts-o[Q-1].pts:R,ot.stretchShortVideoTrack&&null!==this.nextAudioPts){var ht=Math.floor(ot.maxBufferHole*a),dt=(r?m+r*a:this.nextAudioPts)-J.pts;dt>ht?((g=dt-lt)<0?g=lt:W=!0,F.log("[mp4-remuxer]: It is approximately "+dt/90+" ms to the next segment; using duration "+g/90+" ms for the last video frame.")):g=lt}else g=lt}var ut=Math.round(J.pts-J.dts);j=Math.min(j,g),X=Math.max(X,g),q=Math.min(q,at),z=Math.max(z,at),l.push(new fn(J.key,g,tt,ut))}if(l.length)if(nn){if(nn<70){var ct=l[0].flags;ct.dependsOn=2,ct.isNonSync=0}}else if(an&&z-q<X-j&&R/X<.025&&0===l[0].cts){F.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");for(var ft=s,gt=0,mt=l.length;gt<mt;gt++){var pt=ft+l[gt].duration,vt=ft+l[gt].cts;if(gt<mt-1){var yt=pt+l[gt+1].cts;l[gt].duration=yt-vt}else l[gt].duration=gt?l[gt-1].duration:R;l[gt].cts=0,ft=pt}}g=W||!g?R:g,this.nextAvcDts=c=n+g,this.videoSampleDuration=g,this.isVideoContiguous=!0;var Et={data1:qs.moof(t.sequenceNumber++,s,h({},t,{samples:l})),data2:$,startPTS:m/a,endPTS:(p+g)/a,startDTS:s/a,endDTS:c/a,type:"video",hasAudio:!1,hasVideo:!0,nb:l.length,dropped:t.dropped};return t.samples=[],t.dropped=0,Et},e.getSamplesPerFrame=function(t){switch(t.segmentCodec){case"mp3":return rn;case"ac3":return sn;default:return en}},e.remuxAudio=function(t,e,i,r,s){var n=t.inputTimeScale,a=n/(t.samplerate?t.samplerate:n),o=this.getSamplesPerFrame(t),l=o*a,d=this._initPTS,u="mp3"===t.segmentCodec&&this.typeSupported.mpeg,c=[],f=void 0!==s,g=t.samples,m=u?0:8,p=this.nextAudioPts||-1,v=e*n,y=d.baseTime*n/d.timescale;if(this.isAudioContiguous=i=i||g.length&&p>0&&(r&&Math.abs(v-p)<9e3||Math.abs(ln(g[0].pts-y,v)-p)<20*l),g.forEach((function(t){t.pts=ln(t.pts-y,v)})),!i||p<0){if(g=g.filter((function(t){return t.pts>=0})),!g.length)return;p=0===s?0:r&&!f?Math.max(0,v):g[0].pts}if("aac"===t.segmentCodec)for(var E=this.config.maxAudioFramesDrift,T=0,S=p;T<g.length;T++){var A=g[T],L=A.pts,R=L-S,b=Math.abs(1e3*R/n);if(R<=-E*l&&f)0===T&&(F.warn("Audio frame @ "+(L/n).toFixed(3)+"s overlaps nextAudioPts by "+Math.round(1e3*R/n)+" ms."),this.nextAudioPts=p=S=L);else if(R>=E*l&&b<tn&&f){var k=Math.round(R/l);(S=L-k*l)<0&&(k--,S+=l),0===T&&(this.nextAudioPts=p=S),F.warn("[mp4-remuxer]: Injecting "+k+" audio frame @ "+(S/n).toFixed(3)+"s due to "+Math.round(1e3*R/n)+" ms gap.");for(var C=0;C<k;C++){var _=Math.max(S,0),P=Ws.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);P||(F.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),P=A.unit.subarray()),g.splice(T,0,{unit:P,pts:_}),S+=l,T++}}A.pts=S,S+=l}for(var x,M=null,O=null,N=0,U=g.length;U--;)N+=g[U].unit.byteLength;for(var B=0,G=g.length;B<G;B++){var K=g[B],H=K.unit,$=K.pts;if(null!==O)c[B-1].duration=Math.round(($-O)/a);else{if(i&&"aac"===t.segmentCodec&&($=p),M=$,!(N>0))return;N+=m;try{x=new Uint8Array(N)}catch(t){return void this.observer.emit(D.ERROR,D.ERROR,{type:I.MUX_ERROR,details:w.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:N,reason:"fail allocating audio mdat "+N})}u||(new DataView(x.buffer).setUint32(0,N),x.set(qs.types.mdat,4))}x.set(H,m);var V=H.byteLength;m+=V,c.push(new fn(!0,o,V,0)),O=$}var Y=c.length;if(Y){var W=c[c.length-1];this.nextAudioPts=p=O+a*W.duration;var j=u?new Uint8Array(0):qs.moof(t.sequenceNumber++,M/a,h({},t,{samples:c}));t.samples=[];var q=M/n,X=p/n,z={data1:j,data2:x,startPTS:q,endPTS:X,startDTS:q,endDTS:X,type:"audio",hasAudio:!0,hasVideo:!1,nb:Y};return this.isAudioContiguous=!0,z}},e.remuxEmptyAudio=function(t,e,i,r){var s=t.inputTimeScale,n=s/(t.samplerate?t.samplerate:s),a=this.nextAudioPts,o=this._initDTS,l=9e4*o.baseTime/o.timescale,h=(null!==a?a:r.startDTS*s)+l,d=r.endDTS*s+l,u=n*en,c=Math.ceil((d-h)/u),f=Ws.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);if(F.warn("[mp4-remuxer]: remux empty Audio"),f){for(var g=[],m=0;m<c;m++){var p=h+m*u;g.push({unit:f,pts:p,dts:p})}return t.samples=g,this.remuxAudio(t,e,i,!1)}F.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec")},t}();function ln(t,e){var i;if(null===e)return t;for(i=e<t?-8589934592:8589934592;Math.abs(t-e)>4294967296;)t+=i;return t}function hn(t){for(var e=0;e<t.length;e++)if(t[e].key)return e;return-1}function dn(t,e,i,r){var s=t.samples.length;if(s){for(var n=t.inputTimeScale,a=0;a<s;a++){var o=t.samples[a];o.pts=ln(o.pts-i.baseTime*n/i.timescale,e*n)/n,o.dts=ln(o.dts-r.baseTime*n/r.timescale,e*n)/n}var l=t.samples;return t.samples=[],{samples:l}}}function un(t,e,i){var r=t.samples.length;if(r){for(var s=t.inputTimeScale,n=0;n<r;n++){var a=t.samples[n];a.pts=ln(a.pts-i.baseTime*s/i.timescale,e*s)/s}t.samples.sort((function(t,e){return t.pts-e.pts}));var o=t.samples;return t.samples=[],{samples:o}}}var cn,fn=function(t,e,i,r){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=e,this.size=i,this.cts=r,this.flags={isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1}},gn=function(){function t(){this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null}var e=t.prototype;return e.destroy=function(){},e.resetTimeStamp=function(t){this.initPTS=t,this.lastEndTime=null},e.resetNextTimestamp=function(){this.lastEndTime=null},e.resetInitSegment=function(t,e,i,r){this.audioCodec=e,this.videoCodec=i,this.generateInitSegment(Xt(t,r)),this.emitInitSegment=!0},e.generateInitSegment=function(t){var e=this.audioCodec,i=this.videoCodec;if(null==t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);var r=this.initData=Vt(t);r.audio&&(e=pn(r.audio,V.AUDIO)),r.video&&(i=pn(r.video,V.VIDEO));var s={};r.audio&&r.video?s.audiovideo={container:"video/mp4",codec:e+","+i,initSegment:t,id:"main"}:r.audio?s.audio={container:"audio/mp4",codec:e,initSegment:t,id:"audio"}:r.video?s.video={container:"video/mp4",codec:i,initSegment:t,id:"main"}:F.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=s},e.remux=function(t,e,i,r,s,n){var a,o,l=this.initPTS,h=this.lastEndTime,d={audio:void 0,video:void 0,text:r,id3:i,initSegment:void 0};R(h)||(h=this.lastEndTime=s||0);var u=e.samples;if(null==u||!u.length)return d;var c={initPTS:void 0,timescale:1},f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(u),f=this.initData),null==(o=f)||!o.length)return F.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),d;this.emitInitSegment&&(c.tracks=this.initTracks,this.emitInitSegment=!1);var g=Jt(u,f),m=Qt(f,u),p=null===m?s:m;(mn(l,p,s,g)||c.timescale!==l.timescale&&n)&&(c.initPTS=p-s,l&&1===l.timescale&&F.warn("Adjusting initPTS by "+(c.initPTS-l.baseTime)),this.initPTS=l={baseTime:c.initPTS,timescale:1});var v=t?p-l.baseTime/l.timescale:h,y=v+g;te(f,u,l.baseTime/l.timescale),g>0?this.lastEndTime=y:(F.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());var E=!!f.audio,T=!!f.video,S="";E&&(S+="audio"),T&&(S+="video");var A={data1:u,startPTS:v,startDTS:v,endPTS:y,endDTS:y,type:S,hasAudio:E,hasVideo:T,nb:1,dropped:0};return d.audio="audio"===A.type?A:void 0,d.video="audio"!==A.type?A:void 0,d.initSegment=c,d.id3=dn(i,s,l,l),r.samples.length&&(d.text=un(r,s,l)),d},t}();function mn(t,e,i,r){if(null===t)return!0;var s=Math.max(r,1),n=e-t.baseTime/t.timescale;return Math.abs(n-i)>s}function pn(t,e){var i=null==t?void 0:t.codec;if(i&&i.length>4)return i;if(e===V.AUDIO){if("ec-3"===i||"ac-3"===i||"alac"===i)return i;if("fLaC"===i||"Opus"===i)return xe(i,!1);var r="mp4a.40.5";return F.info('Parsed audio codec "'+i+'" or audio object type not handled. Using "'+r+'"'),r}return F.warn('Unhandled video codec "'+i+'"'),"hvc1"===i||"hev1"===i?"hvc1.1.6.L120.90":"av01"===i?"av01.0.04M.08":"avc1.42e01e"}try{cn=self.performance.now.bind(self.performance)}catch(t){F.debug("Unable to use Performance API on this environment"),cn=null==et?void 0:et.Date.now}var vn=[{demux:ws,remux:gn},{demux:Us,remux:on},{demux:Ds,remux:on},{demux:Ys,remux:on}];vn.splice(2,0,{demux:_s,remux:on});var yn=function(){function t(t,e,i,r,s){this.async=!1,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=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=e,this.config=i,this.vendor=r,this.id=s}var e=t.prototype;return e.configure=function(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()},e.push=function(t,e,i,r){var s=this,n=i.transmuxing;n.executeStart=cn();var a=new Uint8Array(t),o=this.currentTransmuxState,l=this.transmuxConfig;r&&(this.currentTransmuxState=r);var h=r||o,d=h.contiguous,u=h.discontinuity,c=h.trackSwitch,f=h.accurateTimeOffset,g=h.timeOffset,m=h.initSegmentChange,p=l.audioCodec,v=l.videoCodec,y=l.defaultInitPts,E=l.duration,T=l.initSegmentData,S=En(a,e);if(S&&"AES-128"===S.method){var A=this.getDecrypter();if(!A.isSync())return this.decryptionPromise=A.webCryptoDecrypt(a,S.key.buffer,S.iv.buffer).then((function(t){var e=s.push(t,null,i);return s.decryptionPromise=null,e})),this.decryptionPromise;var L=A.softwareDecrypt(a,S.key.buffer,S.iv.buffer);if(i.part>-1&&(L=A.flush()),!L)return n.executeEnd=cn(),Tn(i);a=new Uint8Array(L)}var R=this.needsProbing(u,c);if(R){var b=this.configureTransmuxer(a);if(b)return F.warn("[transmuxer] "+b.message),this.observer.emit(D.ERROR,D.ERROR,{type:I.MEDIA_ERROR,details:w.FRAG_PARSING_ERROR,fatal:!1,error:b,reason:b.message}),n.executeEnd=cn(),Tn(i)}(u||c||m||R)&&this.resetInitSegment(T,p,v,E,e),(u||m||R)&&this.resetInitialTimestamp(y),d||this.resetContiguity();var k=this.transmux(a,S,g,f,i),C=this.currentTransmuxState;return C.contiguous=!0,C.discontinuity=!1,C.trackSwitch=!1,n.executeEnd=cn(),k},e.flush=function(t){var e=this,i=t.transmuxing;i.executeStart=cn();var r=this.decrypter,s=this.currentTransmuxState,n=this.decryptionPromise;if(n)return n.then((function(){return e.flush(t)}));var a=[],o=s.timeOffset;if(r){var l=r.flush();l&&a.push(this.push(l,null,t))}var h=this.demuxer,d=this.remuxer;if(!h||!d)return i.executeEnd=cn(),[Tn(t)];var u=h.flush(o);return Sn(u)?u.then((function(i){return e.flushRemux(a,i,t),a})):(this.flushRemux(a,u,t),a)},e.flushRemux=function(t,e,i){var r=e.audioTrack,s=e.videoTrack,n=e.id3Track,a=e.textTrack,o=this.currentTransmuxState,l=o.accurateTimeOffset,h=o.timeOffset;F.log("[transmuxer.ts]: Flushed fragment "+i.sn+(i.part>-1?" p: "+i.part:"")+" of level "+i.level);var d=this.remuxer.remux(r,s,n,a,h,l,!0,this.id);t.push({remuxResult:d,chunkMeta:i}),i.transmuxing.executeEnd=cn()},e.resetInitialTimestamp=function(t){var e=this.demuxer,i=this.remuxer;e&&i&&(e.resetTimeStamp(t),i.resetTimeStamp(t))},e.resetContiguity=function(){var t=this.demuxer,e=this.remuxer;t&&e&&(t.resetContiguity(),e.resetNextTimestamp())},e.resetInitSegment=function(t,e,i,r,s){var n=this.demuxer,a=this.remuxer;n&&a&&(n.resetInitSegment(t,e,i,r),a.resetInitSegment(t,e,i,s))},e.destroy=function(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)},e.transmux=function(t,e,i,r,s){return e&&"SAMPLE-AES"===e.method?this.transmuxSampleAes(t,e,i,r,s):this.transmuxUnencrypted(t,i,r,s)},e.transmuxUnencrypted=function(t,e,i,r){var s=this.demuxer.demux(t,e,!1,!this.config.progressive),n=s.audioTrack,a=s.videoTrack,o=s.id3Track,l=s.textTrack;return{remuxResult:this.remuxer.remux(n,a,o,l,e,i,!1,this.id),chunkMeta:r}},e.transmuxSampleAes=function(t,e,i,r,s){var n=this;return this.demuxer.demuxSampleAes(t,e,i).then((function(t){return{remuxResult:n.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,i,r,!1,n.id),chunkMeta:s}}))},e.configureTransmuxer=function(t){for(var e,i=this.config,r=this.observer,s=this.typeSupported,n=this.vendor,a=0,o=vn.length;a<o;a++){var l;if(null!=(l=vn[a].demux)&&l.probe(t)){e=vn[a];break}}if(!e)return new Error("Failed to find demuxer by probing fragment data");var h=this.demuxer,d=this.remuxer,u=e.remux,c=e.demux;d&&d instanceof u||(this.remuxer=new u(r,i,s,n)),h&&h instanceof c||(this.demuxer=new c(r,i,s),this.probe=c.probe)},e.needsProbing=function(t,e){return!this.demuxer||!this.remuxer||t||e},e.getDecrypter=function(){var t=this.decrypter;return t||(t=this.decrypter=new Xr(this.config)),t},t}();function En(t,e){var i=null;return t.byteLength>0&&null!=(null==e?void 0:e.key)&&null!==e.iv&&null!=e.method&&(i=e),i}var Tn=function(t){return{remuxResult:{},chunkMeta:t}};function Sn(t){return"then"in t&&t.then instanceof Function}var An=function(t,e,i,r,s){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=e,this.initSegmentData=i,this.duration=r,this.defaultInitPts=s||null},Ln=function(t,e,i,r,s,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=t,this.contiguous=e,this.accurateTimeOffset=i,this.trackSwitch=r,this.timeOffset=s,this.initSegmentChange=n},Rn={exports:{}};!function(module){var t=Object.prototype.hasOwnProperty,e="~";function i(){}function r(t,e,i){this.fn=t,this.context=e,this.once=i||!1}function s(t,i,s,n,a){if("function"!=typeof s)throw new TypeError("The listener must be a function");var o=new r(s,n||t,a),l=e?e+i:i;return t._events[l]?t._events[l].fn?t._events[l]=[t._events[l],o]:t._events[l].push(o):(t._events[l]=o,t._eventsCount++),t}function n(t,e){0==--t._eventsCount?t._events=new i:delete t._events[e]}function a(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(e=!1)),a.prototype.eventNames=function(){var i,r,s=[];if(0===this._eventsCount)return s;for(r in i=this._events)t.call(i,r)&&s.push(e?r.slice(1):r);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(i)):s},a.prototype.listeners=function(t){var i=e?e+t:t,r=this._events[i];if(!r)return[];if(r.fn)return[r.fn];for(var s=0,n=r.length,a=new Array(n);s<n;s++)a[s]=r[s].fn;return a},a.prototype.listenerCount=function(t){var i=e?e+t:t,r=this._events[i];return r?r.fn?1:r.length:0},a.prototype.emit=function(t,i,r,s,n,a){var o=e?e+t:t;if(!this._events[o])return!1;var l,h,d=this._events[o],u=arguments.length;if(d.fn){switch(d.once&&this.removeListener(t,d.fn,void 0,!0),u){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,i),!0;case 3:return d.fn.call(d.context,i,r),!0;case 4:return d.fn.call(d.context,i,r,s),!0;case 5:return d.fn.call(d.context,i,r,s,n),!0;case 6:return d.fn.call(d.context,i,r,s,n,a),!0}for(h=1,l=new Array(u-1);h<u;h++)l[h-1]=arguments[h];d.fn.apply(d.context,l)}else{var c,f=d.length;for(h=0;h<f;h++)switch(d[h].once&&this.removeListener(t,d[h].fn,void 0,!0),u){case 1:d[h].fn.call(d[h].context);break;case 2:d[h].fn.call(d[h].context,i);break;case 3:d[h].fn.call(d[h].context,i,r);break;case 4:d[h].fn.call(d[h].context,i,r,s);break;default:if(!l)for(c=1,l=new Array(u-1);c<u;c++)l[c-1]=arguments[c];d[h].fn.apply(d[h].context,l)}}return!0},a.prototype.on=function(t,e,i){return s(this,t,e,i,!1)},a.prototype.once=function(t,e,i){return s(this,t,e,i,!0)},a.prototype.removeListener=function(t,i,r,s){var a=e?e+t:t;if(!this._events[a])return this;if(!i)return n(this,a),this;var o=this._events[a];if(o.fn)o.fn!==i||s&&!o.once||r&&o.context!==r||n(this,a);else{for(var l=0,h=[],d=o.length;l<d;l++)(o[l].fn!==i||s&&!o[l].once||r&&o[l].context!==r)&&h.push(o[l]);h.length?this._events[a]=1===h.length?h[0]:h:n(this,a)}return this},a.prototype.removeAllListeners=function(t){var r;return t?(r=e?e+t:t,this._events[r]&&n(this,r)):(this._events=new i,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=e,a.EventEmitter=a,module.exports=a}(Rn);var bn=S(Rn.exports);function kn(t){var e=new bn,i=function(e,i){t.postMessage({event:e,data:i})};e.on(D.FRAG_DECRYPTED,i),e.on(D.ERROR,i);var r=function(){var t=function(t){var e=function(e){i("workerLog",{logType:t,message:e})};F[t]=e};for(var e in F)t(e)};t.addEventListener("message",(function(s){var n=s.data;switch(n.cmd){case"init":var a=JSON.parse(n.config);t.transmuxer=new yn(e,n.typeSupported,a,"",n.id),O(a.debug,n.id),r(),i("init",null);break;case"configure":t.transmuxer.configure(n.config);break;case"demux":var o=t.transmuxer.push(n.data,n.decryptdata,n.chunkMeta,n.state);Sn(o)?(t.transmuxer.async=!0,o.then((function(e){Dn(t,e)})).catch((function(t){i(D.ERROR,{type:I.MEDIA_ERROR,details:w.FRAG_PARSING_ERROR,chunkMeta:n.chunkMeta,fatal:!1,error:t,err:t,reason:"transmuxer-worker push error"})}))):(t.transmuxer.async=!1,Dn(t,o));break;case"flush":var l=n.chunkMeta,h=t.transmuxer.flush(l);Sn(h)||t.transmuxer.async?(Sn(h)||(h=Promise.resolve(h)),h.then((function(e){wn(t,e,l)})).catch((function(t){i(D.ERROR,{type:I.MEDIA_ERROR,details:w.FRAG_PARSING_ERROR,chunkMeta:n.chunkMeta,fatal:!1,error:t,err:t,reason:"transmuxer-worker flush error"})}))):wn(t,h,l)}}))}function Dn(t,e){if(Cn(e.remuxResult))return!1;var i=[],r=e.remuxResult,s=r.audio,n=r.video;return s&&In(i,s),n&&In(i,n),t.postMessage({event:"transmuxComplete",data:e},i),!0}function In(t,e){e.data1&&t.push(e.data1.buffer),e.data2&&t.push(e.data2.buffer)}function wn(t,e,i){e.reduce((function(e,i){return Dn(t,i)||e}),!1)||t.postMessage({event:"transmuxComplete",data:e[0]}),t.postMessage({event:"flush",data:i})}function Cn(t){return!(t.audio||t.video||t.text||t.id3||t.initSegment)}function _n(){return!0}function Pn(){var e=new self.Blob(["var exports={};var module={exports:exports};function define(f){f()};define.amd=true;("+t.toString()+")(true);"],{type:"text/javascript"}),i=self.URL.createObjectURL(e);return{worker:new self.Worker(i),objectURL:i}}function xn(t){var e=new self.URL(t,self.location.href).href;return{worker:new self.Worker(e),scriptURL:e}}void 0!==e&&e&&kn(self);var Mn=function(){function t(t,e,i,r){var s=this;this.error=null,this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0;var n=t.config;this.hls=t,this.id=e,this.useWorker=!!n.enableWorker,this.onTransmuxComplete=i,this.onFlush=r;var a=function(t,e){(e=e||{}).frag=s.frag,e.id=s.id,t===D.ERROR&&(s.error=e.error),s.hls.trigger(t,e)};this.observer=new bn,this.observer.on(D.FRAG_DECRYPTED,a),this.observer.on(D.ERROR,a);var o=Se(n.preferManagedMediaSource)||{isTypeSupported:function(){return!1}},l={mpeg:o.isTypeSupported("audio/mpeg"),mp3:o.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:o.isTypeSupported('audio/mp4; codecs="ac-3"')};if(this.useWorker&&"undefined"!=typeof Worker&&(n.workerPath||_n()))try{n.workerPath?(F.log("loading Web Worker "+n.workerPath+' for "'+e+'"'),this.workerContext=xn(n.workerPath)):(F.log('injecting Web Worker for "'+e+'"'),this.workerContext=Pn()),this.onwmsg=function(t){return s.onWorkerMessage(t)};var h=this.workerContext.worker;h.addEventListener("message",this.onwmsg),h.onerror=function(t){var i=new Error(t.message+" ("+t.filename+":"+t.lineno+")");n.enableWorker=!1,F.warn('Error in "'+e+'" Web Worker, fallback to inline'),s.hls.trigger(D.ERROR,{type:I.OTHER_ERROR,details:w.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:i})},h.postMessage({cmd:"init",typeSupported:l,vendor:"",id:e,config:JSON.stringify(n)})}catch(t){F.warn('Error setting up "'+e+'" Web Worker, fallback to inline',t),this.resetWorker(),this.error=null,this.transmuxer=new yn(this.observer,l,n,"",e)}else this.transmuxer=new yn(this.observer,l,n,"",e)}var e=t.prototype;return e.resetWorker=function(){if(this.workerContext){var t=this.workerContext,e=t.worker,i=t.objectURL;i&&self.URL.revokeObjectURL(i),e.removeEventListener("message",this.onwmsg),e.onerror=null,e.terminate(),this.workerContext=null}},e.destroy=function(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{var t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}var e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null},e.push=function(t,e,i,r,s,n,a,o,l,h){var d,u,c=this;l.transmuxing.start=self.performance.now();var f=this.transmuxer,g=n?n.start:s.start,m=s.decryptdata,p=this.frag,v=!(p&&s.cc===p.cc),y=!(p&&l.level===p.level),E=p?l.sn-p.sn:-1,T=this.part?l.part-this.part.index:-1,S=0===E&&l.id>1&&l.id===(null==p?void 0:p.stats.chunkCount),A=!y&&(1===E||0===E&&(1===T||S&&T<=0)),L=self.performance.now();(y||E||0===s.stats.parsing.start)&&(s.stats.parsing.start=L),!n||!T&&A||(n.stats.parsing.start=L);var R=!(p&&(null==(d=s.initSegment)?void 0:d.url)===(null==(u=p.initSegment)?void 0:u.url)),b=new Ln(v,A,o,y,g,R);if(!A||v||R){F.log("[transmuxer-interface, "+s.type+"]: Starting new transmux session for sn: "+l.sn+" p: "+l.part+" level: "+l.level+" id: "+l.id+"\n discontinuity: "+v+"\n trackSwitch: "+y+"\n contiguous: "+A+"\n accurateTimeOffset: "+o+"\n timeOffset: "+g+"\n initSegmentChange: "+R);var k=new An(i,r,e,a,h);this.configureTransmuxer(k)}if(this.frag=s,this.part=n,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:t,decryptdata:m,chunkMeta:l,state:b},t instanceof ArrayBuffer?[t]:[]);else if(f){var D=f.push(t,m,l,b);Sn(D)?(f.async=!0,D.then((function(t){c.handleTransmuxComplete(t)})).catch((function(t){c.transmuxerError(t,l,"transmuxer-interface push error")}))):(f.async=!1,this.handleTransmuxComplete(D))}},e.flush=function(t){var e=this;t.transmuxing.start=self.performance.now();var i=this.transmuxer;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:t});else if(i){var r=i.flush(t);Sn(r)||i.async?(Sn(r)||(r=Promise.resolve(r)),r.then((function(i){e.handleFlushResult(i,t)})).catch((function(i){e.transmuxerError(i,t,"transmuxer-interface flush error")}))):this.handleFlushResult(r,t)}},e.transmuxerError=function(t,e,i){this.hls&&(this.error=t,this.hls.trigger(D.ERROR,{type:I.MEDIA_ERROR,details:w.FRAG_PARSING_ERROR,chunkMeta:e,frag:this.frag||void 0,fatal:!1,error:t,err:t,reason:i}))},e.handleFlushResult=function(t,e){var i=this;t.forEach((function(t){i.handleTransmuxComplete(t)})),this.onFlush(e)},e.onWorkerMessage=function(t){var e=t.data;if(null!=e&&e.event){var i=this.hls;if(this.hls)switch(e.event){case"init":var r,s=null==(r=this.workerContext)?void 0:r.objectURL;s&&self.URL.revokeObjectURL(s);break;case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;case"workerLog":F[e.data.logType]&&F[e.data.logType](e.data.message);break;default:e.data=e.data||{},e.data.frag=this.frag,e.data.id=this.id,i.trigger(e.event,e.data)}}else F.warn("worker message received with no "+(e?"event name":"data"))},e.configureTransmuxer=function(t){var e=this.transmuxer;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:t}):e&&e.configure(t)},e.handleTransmuxComplete=function(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)},t}();function On(t,e){if(t.length!==e.length)return!1;for(var i=0;i<t.length;i++)if(!Fn(t[i].attrs,e[i].attrs))return!1;return!0}function Fn(t,e,i){var r=t["STABLE-RENDITION-ID"];return r&&!i?r===e["STABLE-RENDITION-ID"]:!(i||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some((function(i){return t[i]!==e[i]}))}function Nn(t,e){return e.label.toLowerCase()===t.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(t.lang||"").toLowerCase())}var Un=100,Bn=function(t){function e(e,i,r){var s;return(s=t.call(this,e,i,r,"[audio-stream-controller]",Qe.AUDIO)||this).videoBuffer=null,s.videoTrackCC=-1,s.waitingVideoCC=-1,s.bufferedTrack=null,s.switchingTrack=null,s.trackId=-1,s.waitingData=null,s.mainDetails=null,s.flushing=!1,s.bufferFlushed=!1,s.cachedTrackLoadedData=null,s._registerListeners(),s}d(e,t);var i=e.prototype;return i.onHandlerDestroying=function(){this._unregisterListeners(),t.prototype.onHandlerDestroying.call(this),this.mainDetails=null,this.bufferedTrack=null,this.switchingTrack=null},i._registerListeners=function(){var t=this.hls;t.on(D.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(D.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(D.MANIFEST_LOADING,this.onManifestLoading,this),t.on(D.LEVEL_LOADED,this.onLevelLoaded,this),t.on(D.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(D.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(D.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(D.ERROR,this.onError,this),t.on(D.BUFFER_RESET,this.onBufferReset,this),t.on(D.BUFFER_CREATED,this.onBufferCreated,this),t.on(D.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(D.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(D.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(D.FRAG_BUFFERED,this.onFragBuffered,this)},i._unregisterListeners=function(){var t=this.hls;t.off(D.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(D.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(D.MANIFEST_LOADING,this.onManifestLoading,this),t.off(D.LEVEL_LOADED,this.onLevelLoaded,this),t.off(D.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(D.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(D.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(D.ERROR,this.onError,this),t.off(D.BUFFER_RESET,this.onBufferReset,this),t.off(D.BUFFER_CREATED,this.onBufferCreated,this),t.off(D.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(D.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(D.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(D.FRAG_BUFFERED,this.onFragBuffered,this)},i.onInitPtsFound=function(t,e){var i=e.frag,r=e.id,s=e.initPTS,n=e.timescale;if("main"===r){var a=i.cc;this.initPTS[i.cc]={baseTime:s,timescale:n},this.log("InitPTS for cc: "+a+" found from main: "+s),this.videoTrackCC=a,this.state===Qr.WAITING_INIT_PTS&&this.tick()}},i.startLoad=function(t){if(!this.levels)return this.startPosition=t,void(this.state=Qr.STOPPED);var e=this.lastCurrentTime;this.stopLoad(),this.setInterval(Un),e>0&&-1===t?(this.log("Override startPosition with lastCurrentTime @"+e.toFixed(3)),t=e,this.state=Qr.IDLE):(this.loadedmetadata=!1,this.state=Qr.WAITING_TRACK),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()},i.doTick=function(){switch(this.state){case Qr.IDLE:this.doTickIdle();break;case Qr.WAITING_TRACK:var e,i=this.levels,r=this.trackId,s=null==i||null==(e=i[r])?void 0:e.details;if(s){if(this.waitForCdnTuneIn(s))break;this.state=Qr.WAITING_INIT_PTS}break;case Qr.FRAG_LOADING_WAITING_RETRY:var n,a=performance.now(),o=this.retryDate;if(!o||a>=o||null!=(n=this.media)&&n.seeking){var l=this.levels,h=this.trackId;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((null==l?void 0:l[h])||null),this.state=Qr.IDLE}break;case Qr.WAITING_INIT_PTS:var d=this.waitingData;if(d){var u=d.frag,c=d.part,f=d.cache,g=d.complete;if(void 0!==this.initPTS[u.cc]){this.waitingData=null,this.waitingVideoCC=-1,this.state=Qr.FRAG_LOADING;var m={frag:u,part:c,payload:f.flush(),networkDetails:null};this._handleFragmentLoadProgress(m),g&&t.prototype._handleFragmentLoadComplete.call(this,m)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log("Waiting fragment cc ("+u.cc+") cancelled because video is at cc "+this.videoTrackCC),this.clearWaitingFragment();else{var p=this.getLoadPosition(),v=Ir.bufferInfo(this.mediaBuffer,p,this.config.maxBufferHole);Xi(v.end,this.config.maxFragLookUpTolerance,u)<0&&(this.log("Waiting fragment cc ("+u.cc+") @ "+u.start+" cancelled because another fragment at "+v.end+" is needed"),this.clearWaitingFragment())}}else this.state=Qr.IDLE}this.onTickEnd()},i.clearWaitingFragment=function(){var t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=Qr.IDLE)},i.resetLoadingState=function(){this.clearWaitingFragment(),t.prototype.resetLoadingState.call(this)},i.onTickEnd=function(){var t=this.media;null!=t&&t.readyState&&(this.lastCurrentTime=t.currentTime)},i.doTickIdle=function(){var t=this.hls,e=this.levels,i=this.media,r=this.trackId,s=t.config;if((i||!this.startFragRequested&&s.startFragPrefetch)&&null!=e&&e[r]){var n=e[r],a=n.details;if(!a||a.live&&this.levelLastLoaded!==n||this.waitForCdnTuneIn(a))this.state=Qr.WAITING_TRACK;else{var o=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&o&&(this.bufferFlushed=!1,this.afterBufferFlushed(o,V.AUDIO,Qe.AUDIO));var l=this.getFwdBufferInfo(o,Qe.AUDIO);if(null!==l){var h=this.bufferedTrack,d=this.switchingTrack;if(!d&&this._streamEnded(l,a))return t.trigger(D.BUFFER_EOS,{type:"audio"}),void(this.state=Qr.ENDED);var u=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,Qe.MAIN),c=l.len,f=this.getMaxBufferLength(null==u?void 0:u.len),g=a.fragments,m=g[0].start,p=this.flushing?this.getLoadPosition():l.end;if(d&&i){var v=this.getLoadPosition();h&&!Fn(d.attrs,h.attrs)&&(p=v),a.PTSKnown&&v<m&&(l.end>m||l.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=m+.05)}if(!(c>=f&&!d&&p<g[g.length-1].start)){var y=this.getNextFragment(p,a),E=!1;if(y&&this.isLoopLoading(y,p)&&(E=!!y.gap,y=this.getNextFragmentLoopLoading(y,a,l,Qe.MAIN,f)),y){var T=u&&y.start>u.end+a.targetduration;if(T||(null==u||!u.len)&&l.len){var S=this.getAppendedFrag(y.start,Qe.MAIN);if(null===S)return;if(E||(E=!!S.gap||!!T&&0===u.len),T&&!E||E&&l.nextStart&&l.nextStart<S.end)return}this.loadFragment(y,n,p)}else this.bufferFlushed=!0}}}}},i.getMaxBufferLength=function(e){var i=t.prototype.getMaxBufferLength.call(this);return e?Math.min(Math.max(i,e),this.config.maxMaxBufferLength):i},i.onMediaDetaching=function(){this.videoBuffer=null,this.bufferFlushed=this.flushing=!1,t.prototype.onMediaDetaching.call(this)},i.onAudioTracksUpdated=function(t,e){var i=e.audioTracks;this.resetTransmuxer(),this.levels=i.map((function(t){return new Ri(t)}))},i.onAudioTrackSwitching=function(t,e){var i=!!e.url;this.trackId=e.id;var r=this.fragCurrent;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),i?this.setInterval(Un):this.resetTransmuxer(),i?(this.switchingTrack=e,this.state=Qr.IDLE,this.flushAudioIfNeeded(e)):(this.switchingTrack=null,this.bufferedTrack=e,this.state=Qr.STOPPED),this.tick()},i.onManifestLoading=function(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=this.flushing=!1,this.levels=this.mainDetails=this.waitingData=this.bufferedTrack=this.cachedTrackLoadedData=this.switchingTrack=null,this.startFragRequested=!1,this.trackId=this.videoTrackCC=this.waitingVideoCC=-1},i.onLevelLoaded=function(t,e){this.mainDetails=e.details,null!==this.cachedTrackLoadedData&&(this.hls.trigger(D.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)},i.onAudioTrackLoaded=function(t,e){var i;if(null!=this.mainDetails){var r=this.levels,s=e.details,n=e.id;if(r){this.log("Audio track "+n+" loaded ["+s.startSN+","+s.endSN+"]"+(s.lastPartSn?"[part-"+s.lastPartSn+"-"+s.lastPartIndex+"]":"")+",duration:"+s.totalduration);var a=r[n],o=0;if(s.live||null!=(i=a.details)&&i.live){this.checkLiveUpdate(s);var l,h=this.mainDetails;if(s.deltaUpdateFailed||!h)return;!a.details&&s.hasProgramDateTime&&h.hasProgramDateTime?(Ur(s,h),o=s.fragments[0].start):o=this.alignPlaylists(s,a.details,null==(l=this.levelLastLoaded)?void 0:l.details)}a.details=s,this.levelLastLoaded=a,this.startFragRequested||!this.mainDetails&&s.live||this.setStartPosition(this.mainDetails||s,o),this.state!==Qr.WAITING_TRACK||this.waitForCdnTuneIn(s)||(this.state=Qr.IDLE),this.tick()}else this.warn("Audio tracks were reset while loading level "+n)}else this.cachedTrackLoadedData=e},i._handleFragmentLoadProgress=function(t){var e,i=t.frag,r=t.part,s=t.payload,n=this.config,a=this.trackId,o=this.levels;if(o){var l=o[a];if(l){var h=l.details;if(!h)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(i.start);var d=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2",u=this.transmuxer;u||(u=this.transmuxer=new Mn(this.hls,Qe.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));var c=this.initPTS[i.cc],f=null==(e=i.initSegment)?void 0:e.data;if(void 0!==c){var g=!1,m=r?r.index:-1,p=-1!==m,v=new wr(i.level,i.sn,i.stats.chunkCount,s.byteLength,m,p);u.push(s,f,d,"",i,r,h.totalduration,g,v,c)}else this.log("Unknown video PTS for cc "+i.cc+", waiting for video PTS before demuxing audio frag "+i.sn+" of ["+h.startSN+" ,"+h.endSN+"],track "+a),(this.waitingData=this.waitingData||{frag:i,part:r,cache:new Zr,complete:!1}).cache.push(new Uint8Array(s)),this.waitingVideoCC=this.videoTrackCC,this.state=Qr.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 "+i.sn+" of level "+i.level+" will not be buffered")},i._handleFragmentLoadComplete=function(e){this.waitingData?this.waitingData.complete=!0:t.prototype._handleFragmentLoadComplete.call(this,e)},i.onBufferReset=function(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1},i.onBufferCreated=function(t,e){var i=e.tracks.audio;i&&(this.mediaBuffer=i.buffer||null),e.tracks.video&&(this.videoBuffer=e.tracks.video.buffer||null)},i.onFragBuffered=function(t,e){var i=e.frag,s=e.part;if(i.type===Qe.AUDIO)if(this.fragContextChanged(i))this.warn("Fragment "+i.sn+(s?" p: "+s.index:"")+" of level "+i.level+" finished buffering, but was aborted. state: "+this.state+", audioSwitch: "+(this.switchingTrack?this.switchingTrack.name:"false"));else{if("initSegment"!==i.sn){this.fragPrevious=i;var n=this.switchingTrack;n&&(this.bufferedTrack=n,this.switchingTrack=null,this.hls.trigger(D.AUDIO_TRACK_SWITCHED,r({},n)))}this.fragBufferedComplete(i,s)}else if(!this.loadedmetadata&&i.type===Qe.MAIN){var a=this.videoBuffer||this.media;a&&Ir.getBuffered(a).length&&(this.loadedmetadata=!0)}},i.onError=function(e,i){var r;if(i.fatal)this.state=Qr.ERROR;else switch(i.details){case w.FRAG_GAP:case w.FRAG_PARSING_ERROR:case w.FRAG_DECRYPT_ERROR:case w.FRAG_LOAD_ERROR:case w.FRAG_LOAD_TIMEOUT:case w.KEY_LOAD_ERROR:case w.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Qe.AUDIO,i);break;case w.AUDIO_TRACK_LOAD_ERROR:case w.AUDIO_TRACK_LOAD_TIMEOUT:case w.LEVEL_PARSING_ERROR:i.levelRetry||this.state!==Qr.WAITING_TRACK||(null==(r=i.context)?void 0:r.type)!==ze.AUDIO_TRACK||(this.state=Qr.IDLE);break;case w.BUFFER_APPEND_ERROR:case w.BUFFER_FULL_ERROR:if(!i.parent||"audio"!==i.parent)return;if(i.details===w.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(i)&&(this.bufferedTrack=null,t.prototype.flushMainBuffer.call(this,0,Number.POSITIVE_INFINITY,"audio"));break;case w.INTERNAL_EXCEPTION:this.recoverWorkerError(i)}},i.onBufferFlushing=function(t,e){e.type!==V.VIDEO&&(this.flushing=!0)},i.onBufferFlushed=function(t,e){var i=e.type;if(i!==V.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===Qr.ENDED&&(this.state=Qr.IDLE);var r=this.mediaBuffer||this.media;r&&(this.afterBufferFlushed(r,i,Qe.AUDIO),this.tick())}},i._handleTransmuxComplete=function(t){var e,i="audio",r=this.hls,s=t.remuxResult,n=t.chunkMeta,a=this.getCurrentContext(n);if(a){var o=a.frag,l=a.part,d=a.level,u=d.details,c=s.audio,f=s.text,g=s.id3,m=s.initSegment;if(!this.fragContextChanged(o)&&u){if(this.state=Qr.PARSING,this.switchingTrack&&c&&this.completeAudioSwitch(this.switchingTrack),null!=m&&m.tracks){var p=o.initSegment||o;this._bufferInitSegment(d,m.tracks,p,n),r.trigger(D.FRAG_PARSING_INIT_SEGMENT,{frag:p,id:i,tracks:m.tracks})}if(c){var v=c.startPTS,y=c.endPTS,E=c.startDTS,T=c.endDTS;l&&(l.elementaryStreams[V.AUDIO]={startPTS:v,endPTS:y,startDTS:E,endDTS:T}),o.setElementaryStreamInfo(V.AUDIO,v,y,E,T),this.bufferFragmentData(c,o,l,n)}if(null!=g&&null!=(e=g.samples)&&e.length){var S=h({id:i,frag:o,details:u},g);r.trigger(D.FRAG_PARSING_METADATA,S)}if(f){var A=h({id:i,frag:o,details:u},f);r.trigger(D.FRAG_PARSING_USERDATA,A)}}else this.fragmentTracker.removeFragment(o)}else this.resetWhenMissingContext(n)},i._bufferInitSegment=function(t,e,i,r){if(this.state===Qr.PARSING){e.video&&delete e.video;var s=e.audio;if(s){s.id="audio";var n=t.audioCodec;this.log("Init audio buffer, container:"+s.container+", codecs[level/parsed]=["+n+"/"+s.codec+"]"),n&&1===n.split(",").length&&(s.levelCodec=n),this.hls.trigger(D.BUFFER_CODECS,e);var a=s.initSegment;if(null!=a&&a.byteLength){var o={type:"audio",frag:i,part:null,chunkMeta:r,parent:i.type,data:a};this.hls.trigger(D.BUFFER_APPENDING,o)}this.tickImmediate()}}},i.loadFragment=function(e,i,r){var s,n=this.fragmentTracker.getState(e);if(this.fragCurrent=e,this.switchingTrack||n===Lr.NOT_LOADED||n===Lr.PARTIAL)if("initSegment"===e.sn)this._loadInitSegment(e,i);else if(null!=(s=i.details)&&s.live&&!this.initPTS[e.cc]){this.log("Waiting for video PTS in continuity counter "+e.cc+" of live stream before loading audio fragment "+e.sn+" of level "+this.trackId),this.state=Qr.WAITING_INIT_PTS;var a=this.mainDetails;a&&a.fragments[0].start!==i.details.fragments[0].start&&Ur(i.details,a)}else this.startFragRequested=!0,t.prototype.loadFragment.call(this,e,i,r);else this.clearTrackerIfNeeded(e)},i.flushAudioIfNeeded=function(e){var i=this.media,r=this.bufferedTrack,s=null==r?void 0:r.attrs,n=e.attrs;i&&s&&(s.CHANNELS!==n.CHANNELS||r.name!==e.name||r.lang!==e.lang)&&(this.log("Switching audio track : flushing all audio"),t.prototype.flushMainBuffer.call(this,0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null)},i.completeAudioSwitch=function(t){var e=this.hls;this.flushAudioIfNeeded(t),this.bufferedTrack=t,this.switchingTrack=null,e.trigger(D.AUDIO_TRACK_SWITCHED,r({},t))},e}(Jr),Gn=function(t){function e(e){var i;return(i=t.call(this,e,"[audio-track-controller]")||this).tracks=[],i.groupIds=null,i.tracksInGroup=[],i.trackId=-1,i.currentTrack=null,i.selectDefaultTrack=!0,i.registerListeners(),i}d(e,t);var i=e.prototype;return i.registerListeners=function(){var t=this.hls;t.on(D.MANIFEST_LOADING,this.onManifestLoading,this),t.on(D.MANIFEST_PARSED,this.onManifestParsed,this),t.on(D.LEVEL_LOADING,this.onLevelLoading,this),t.on(D.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(D.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(D.ERROR,this.onError,this)},i.unregisterListeners=function(){var t=this.hls;t.off(D.MANIFEST_LOADING,this.onManifestLoading,this),t.off(D.MANIFEST_PARSED,this.onManifestParsed,this),t.off(D.LEVEL_LOADING,this.onLevelLoading,this),t.off(D.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(D.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(D.ERROR,this.onError,this)},i.destroy=function(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,t.prototype.destroy.call(this)},i.onManifestLoading=function(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0},i.onManifestParsed=function(t,e){this.tracks=e.audioTracks||[]},i.onAudioTrackLoaded=function(t,e){var i=e.id,r=e.groupId,s=e.details,n=this.tracksInGroup[i];if(n&&n.groupId===r){var a=n.details;n.details=e.details,this.log("Audio track "+i+' "'+n.name+'" lang:'+n.lang+" group:"+r+" loaded ["+s.startSN+"-"+s.endSN+"]"),i===this.trackId&&this.playlistLoaded(i,e,a)}else this.warn("Audio track with id:"+i+" and group:"+r+" not found in active group "+(null==n?void 0:n.groupId))},i.onLevelLoading=function(t,e){this.switchLevel(e.level)},i.onLevelSwitching=function(t,e){this.switchLevel(e.level)},i.switchLevel=function(t){var e=this.hls.levels[t];if(e){var i=e.audioGroups||null,r=this.groupIds,s=this.currentTrack;if(!i||(null==r?void 0:r.length)!==(null==i?void 0:i.length)||null!=i&&i.some((function(t){return-1===(null==r?void 0:r.indexOf(t))}))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;var n=this.tracks.filter((function(t){return!i||-1!==i.indexOf(t.groupId)}));if(n.length)this.selectDefaultTrack&&!n.some((function(t){return t.default}))&&(this.selectDefaultTrack=!1),n.forEach((function(t,e){t.id=e}));else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=n;var a=this.hls.config.audioPreference;if(!s&&a){var o=mr(a,n,yr);if(o>-1)s=n[o];else{var l=mr(a,this.tracks);s=this.tracks[l]}}var h=this.findTrackId(s);-1===h&&s&&(h=this.findTrackId(null));var d={audioTracks:n};this.log("Updating audio tracks, "+n.length+" track(s) found in group(s): "+(null==i?void 0:i.join(","))),this.hls.trigger(D.AUDIO_TRACKS_UPDATED,d);var u=this.trackId;if(-1!==h&&-1===u)this.setAudioTrack(h);else if(n.length&&-1===u){var c,f=new Error("No audio track selected for current audio group-ID(s): "+(null==(c=this.groupIds)?void 0:c.join(","))+" track count: "+n.length);this.warn(f.message),this.hls.trigger(D.ERROR,{type:I.MEDIA_ERROR,details:w.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:f})}}else this.shouldReloadPlaylist(s)&&this.setAudioTrack(this.trackId)}},i.onError=function(t,e){!e.fatal&&e.context&&(e.context.type!==ze.AUDIO_TRACK||e.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(e.context.groupId)||(this.requestScheduled=-1,this.checkRetry(e)))},i.setAudioOption=function(t){var e=this.hls;if(e.config.audioPreference=t,t){var i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){var r=this.currentTrack;if(r&&pr(t,r,yr))return r;var s=mr(t,this.tracksInGroup,yr);if(s>-1){var n=this.tracksInGroup[s];return this.setAudioTrack(s),n}if(r){var a=e.loadLevel;-1===a&&(a=e.firstAutoLevel);var o=Er(t,e.levels,i,a,yr);if(-1===o)return null;e.nextLoadLevel=o}if(t.channels||t.audioCodec){var l=mr(t,i);if(l>-1)return i[l]}}}return null},i.setAudioTrack=function(t){var e=this.tracksInGroup;if(t<0||t>=e.length)this.warn("Invalid audio track id: "+t);else{this.clearTimer(),this.selectDefaultTrack=!1;var i=this.currentTrack,s=e[t],n=s.details&&!s.details.live;if(!(t===this.trackId&&s===i&&n||(this.log("Switching to audio-track "+t+' "'+s.name+'" lang:'+s.lang+" group:"+s.groupId+" channels:"+s.channels),this.trackId=t,this.currentTrack=s,this.hls.trigger(D.AUDIO_TRACK_SWITCHING,r({},s)),n))){var a=this.switchParams(s.url,null==i?void 0:i.details,s.details);this.loadPlaylist(a)}}},i.findTrackId=function(t){for(var e=this.tracksInGroup,i=0;i<e.length;i++){var r=e[i];if((!this.selectDefaultTrack||r.default)&&(!t||pr(t,r,yr)))return i}if(t){for(var s=t.name,n=t.lang,a=t.assocLang,o=t.characteristics,l=t.audioCodec,h=t.channels,d=0;d<e.length;d++)if(pr({name:s,lang:n,assocLang:a,characteristics:o,audioCodec:l,channels:h},e[d],yr))return d;for(var u=0;u<e.length;u++){var c=e[u];if(Fn(t.attrs,c.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return u}for(var f=0;f<e.length;f++){var g=e[f];if(Fn(t.attrs,g.attrs,["LANGUAGE"]))return f}}return-1},i.loadPlaylist=function(e){var i=this.currentTrack;if(this.shouldLoadPlaylist(i)&&i){t.prototype.loadPlaylist.call(this);var r=i.id,s=i.groupId,n=i.url;if(e)try{n=e.addDirectives(n)}catch(t){this.warn("Could not construct new URL with HLS Delivery Directives: "+t)}this.log("loading audio-track playlist "+r+' "'+i.name+'" lang:'+i.lang+" group:"+s),this.clearTimer(),this.hls.trigger(D.AUDIO_TRACK_LOADING,{url:n,id:r,groupId:s,deliveryDirectives:e||null})}},o(e,[{key:"allAudioTracks",get:function(){return this.tracks}},{key:"audioTracks",get:function(){return this.tracksInGroup}},{key:"audioTrack",get:function(){return this.trackId},set:function(t){this.selectDefaultTrack=!1,this.setAudioTrack(t)}}]),e}(er),Kn=500,Hn=function(t){function e(e,i,r){var s;return(s=t.call(this,e,i,r,"[subtitle-stream-controller]",Qe.SUBTITLE)||this).currentTrackId=-1,s.tracksBuffered=[],s.mainDetails=null,s._registerListeners(),s}d(e,t);var i=e.prototype;return i.onHandlerDestroying=function(){this._unregisterListeners(),t.prototype.onHandlerDestroying.call(this),this.mainDetails=null},i._registerListeners=function(){var t=this.hls;t.on(D.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(D.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(D.MANIFEST_LOADING,this.onManifestLoading,this),t.on(D.LEVEL_LOADED,this.onLevelLoaded,this),t.on(D.ERROR,this.onError,this),t.on(D.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(D.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(D.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(D.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(D.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(D.FRAG_BUFFERED,this.onFragBuffered,this)},i._unregisterListeners=function(){var t=this.hls;t.off(D.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(D.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(D.MANIFEST_LOADING,this.onManifestLoading,this),t.off(D.LEVEL_LOADED,this.onLevelLoaded,this),t.off(D.ERROR,this.onError,this),t.off(D.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(D.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(D.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(D.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(D.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(D.FRAG_BUFFERED,this.onFragBuffered,this)},i.startLoad=function(t){this.stopLoad(),this.state=Qr.IDLE,this.setInterval(Kn),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()},i.onManifestLoading=function(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()},i.onMediaDetaching=function(){this.tracksBuffered=[],t.prototype.onMediaDetaching.call(this)},i.onLevelLoaded=function(t,e){this.mainDetails=e.details},i.onSubtitleFragProcessed=function(t,e){var i=e.frag,r=e.success;if(this.fragPrevious=i,this.state=Qr.IDLE,r){var s=this.tracksBuffered[this.currentTrackId];if(s){for(var n,a=i.start,o=0;o<s.length;o++)if(a>=s[o].start&&a<=s[o].end){n=s[o];break}var l=i.start+i.duration;n?n.end=l:(n={start:a,end:l},s.push(n)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null)}}},i.onBufferFlushing=function(t,e){var i=e.startOffset,r=e.endOffset;if(0===i&&r!==Number.POSITIVE_INFINITY){var s=r-1;if(s<=0)return;e.endOffsetSubtitles=Math.max(0,s),this.tracksBuffered.forEach((function(t){for(var e=0;e<t.length;)if(t[e].end<=s)t.shift();else{if(!(t[e].start<s))break;t[e].start=s,e++}})),this.fragmentTracker.removeFragmentsInRange(i,s,Qe.SUBTITLE)}},i.onFragBuffered=function(t,e){var i;this.loadedmetadata||e.frag.type!==Qe.MAIN||null!=(i=this.media)&&i.buffered.length&&(this.loadedmetadata=!0)},i.onError=function(t,e){var i=e.frag;(null==i?void 0:i.type)===Qe.SUBTITLE&&(e.details===w.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==Qr.STOPPED&&(this.state=Qr.IDLE))},i.onSubtitleTracksUpdated=function(t,e){var i=this,r=e.subtitleTracks;this.levels&&On(this.levels,r)?this.levels=r.map((function(t){return new Ri(t)})):(this.tracksBuffered=[],this.levels=r.map((function(t){var e=new Ri(t);return i.tracksBuffered[e.id]=[],e})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,Qe.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null)},i.onSubtitleTrackSwitch=function(t,e){var i;if(this.currentTrackId=e.id,null!=(i=this.levels)&&i.length&&-1!==this.currentTrackId){var r=this.levels[this.currentTrackId];null!=r&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.setInterval(Kn)}else this.clearInterval()},i.onSubtitleTrackLoaded=function(t,e){var i,r=this.currentTrackId,s=this.levels,n=e.details,a=e.id;if(s){var o=s[a];if(!(a>=s.length)&&o){this.log("Subtitle track "+a+" loaded ["+n.startSN+","+n.endSN+"]"+(n.lastPartSn?"[part-"+n.lastPartSn+"-"+n.lastPartIndex+"]":"")+",duration:"+n.totalduration),this.mediaBuffer=this.mediaBufferTimeRanges;var l=0;if(n.live||null!=(i=o.details)&&i.live){var h=this.mainDetails;if(n.deltaUpdateFailed||!h)return;var d,u=h.fragments[0];o.details?0===(l=this.alignPlaylists(n,o.details,null==(d=this.levelLastLoaded)?void 0:d.details))&&u&&xi(n,l=u.start):n.hasProgramDateTime&&h.hasProgramDateTime?(Ur(n,h),l=n.fragments[0].start):u&&xi(n,l=u.start)}o.details=n,this.levelLastLoaded=o,a===r&&(this.startFragRequested||!this.mainDetails&&n.live||this.setStartPosition(this.mainDetails||n,l),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===Qr.IDLE&&(ji(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)))}}else this.warn("Subtitle tracks were reset while loading level "+a)},i._handleFragmentLoadComplete=function(t){var e=this,i=t.frag,r=t.payload,s=i.decryptdata,n=this.hls;if(!this.fragContextChanged(i)&&r&&r.byteLength>0&&null!=s&&s.key&&s.iv&&"AES-128"===s.method){var a=performance.now();this.decrypter.decrypt(new Uint8Array(r),s.key.buffer,s.iv.buffer).catch((function(t){throw n.trigger(D.ERROR,{type:I.MEDIA_ERROR,details:w.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:i}),t})).then((function(t){var e=performance.now();n.trigger(D.FRAG_DECRYPTED,{frag:i,payload:t,stats:{tstart:a,tdecrypt:e}})})).catch((function(t){e.warn(t.name+": "+t.message),e.state=Qr.IDLE}))}},i.doTick=function(){if(this.media){if(this.state===Qr.IDLE){var t=this.currentTrackId,e=this.levels,i=null==e?void 0:e[t];if(!i||!e.length||!i.details)return;var r=this.config,s=this.getLoadPosition(),n=Ir.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],s,r.maxBufferHole),a=n.end,o=n.len,l=this.getFwdBufferInfo(this.media,Qe.MAIN),h=i.details;if(o>this.getMaxBufferLength(null==l?void 0:l.len)+h.levelTargetDuration)return;var d=h.fragments,u=d.length,c=h.edge,f=null,g=this.fragPrevious;if(a<c){var m=r.maxFragLookUpTolerance,p=a>c-m?0:m;!(f=ji(g,d,Math.max(d[0].start,a),p))&&g&&g.start<d[0].start&&(f=d[0])}else f=d[u-1];if(!f)return;if("initSegment"!==(f=this.mapToInitFragWhenRequired(f)).sn){var v=d[f.sn-h.startSN-1];v&&v.cc===f.cc&&this.fragmentTracker.getState(v)===Lr.NOT_LOADED&&(f=v)}this.fragmentTracker.getState(f)===Lr.NOT_LOADED&&this.loadFragment(f,i,a)}}else this.state=Qr.IDLE},i.getMaxBufferLength=function(e){var i=t.prototype.getMaxBufferLength.call(this);return e?Math.max(i,e):i},i.loadFragment=function(e,i,r){this.fragCurrent=e,"initSegment"===e.sn?this._loadInitSegment(e,i):(this.startFragRequested=!0,t.prototype.loadFragment.call(this,e,i,r))},o(e,[{key:"mediaBufferTimeRanges",get:function(){return new $n(this.tracksBuffered[this.currentTrackId]||[])}}]),e}(Jr),$n=function(t){this.buffered=void 0;var e=function(e,i,r){if((i>>>=0)>r-1)throw new DOMException("Failed to execute '"+e+"' on 'TimeRanges': The index provided ("+i+") is greater than the maximum bound ("+r+")");return t[i][e]};this.buffered={get length(){return t.length},end:function(i){return e("end",i,t.length)},start:function(i){return e("start",i,t.length)}}},Vn=function(t){function e(e){var i;return(i=t.call(this,e,"[subtitle-track-controller]")||this).media=null,i.tracks=[],i.groupIds=null,i.tracksInGroup=[],i.trackId=-1,i.currentTrack=null,i.selectDefaultTrack=!0,i.queuedDefaultTrack=-1,i.asyncPollTrackChange=function(){return i.pollTrackChange(0)},i.useTextTrackPolling=!1,i.subtitlePollingInterval=-1,i._subtitleDisplay=!0,i.onTextTracksChanged=function(){if(i.useTextTrackPolling||self.clearInterval(i.subtitlePollingInterval),i.media&&i.hls.config.renderTextTracksNatively){for(var t=null,e=oi(i.media.textTracks),r=0;r<e.length;r++)if("hidden"===e[r].mode)t=e[r];else if("showing"===e[r].mode){t=e[r];break}var s=i.findTrackForTextTrack(t);i.subtitleTrack!==s&&i.setSubtitleTrack(s)}},i.registerListeners(),i}d(e,t);var i=e.prototype;return i.destroy=function(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,t.prototype.destroy.call(this)},i.registerListeners=function(){var t=this.hls;t.on(D.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(D.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(D.MANIFEST_LOADING,this.onManifestLoading,this),t.on(D.MANIFEST_PARSED,this.onManifestParsed,this),t.on(D.LEVEL_LOADING,this.onLevelLoading,this),t.on(D.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(D.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(D.ERROR,this.onError,this)},i.unregisterListeners=function(){var t=this.hls;t.off(D.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(D.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(D.MANIFEST_LOADING,this.onManifestLoading,this),t.off(D.MANIFEST_PARSED,this.onManifestParsed,this),t.off(D.LEVEL_LOADING,this.onLevelLoading,this),t.off(D.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(D.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(D.ERROR,this.onError,this)},i.onMediaAttached=function(t,e){this.media=e.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))},i.pollTrackChange=function(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,t)},i.onMediaDetaching=function(){this.media&&(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),oi(this.media.textTracks).forEach((function(t){ri(t)})),this.subtitleTrack=-1,this.media=null)},i.onManifestLoading=function(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0},i.onManifestParsed=function(t,e){this.tracks=e.subtitleTracks},i.onSubtitleTrackLoaded=function(t,e){var i=e.id,r=e.groupId,s=e.details,n=this.tracksInGroup[i];if(n&&n.groupId===r){var a=n.details;n.details=e.details,this.log("Subtitle track "+i+' "'+n.name+'" lang:'+n.lang+" group:"+r+" loaded ["+s.startSN+"-"+s.endSN+"]"),i===this.trackId&&this.playlistLoaded(i,e,a)}else this.warn("Subtitle track with id:"+i+" and group:"+r+" not found in active group "+(null==n?void 0:n.groupId))},i.onLevelLoading=function(t,e){this.switchLevel(e.level)},i.onLevelSwitching=function(t,e){this.switchLevel(e.level)},i.switchLevel=function(t){var e=this.hls.levels[t];if(e){var i=e.subtitleGroups||null,r=this.groupIds,s=this.currentTrack;if(!i||(null==r?void 0:r.length)!==(null==i?void 0:i.length)||null!=i&&i.some((function(t){return-1===(null==r?void 0:r.indexOf(t))}))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;var n=this.tracks.filter((function(t){return!i||-1!==i.indexOf(t.groupId)}));if(n.length)this.selectDefaultTrack&&!n.some((function(t){return t.default}))&&(this.selectDefaultTrack=!1),n.forEach((function(t,e){t.id=e}));else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=n;var a=this.hls.config.subtitlePreference;if(!s&&a){this.selectDefaultTrack=!1;var o=mr(a,n);if(o>-1)s=n[o];else{var l=mr(a,this.tracks);s=this.tracks[l]}}var h=this.findTrackId(s);-1===h&&s&&(h=this.findTrackId(null));var d={subtitleTracks:n};this.log("Updating subtitle tracks, "+n.length+' track(s) found in "'+(null==i?void 0:i.join(","))+'" group-id'),this.hls.trigger(D.SUBTITLE_TRACKS_UPDATED,d),-1!==h&&-1===this.trackId&&this.setSubtitleTrack(h)}else this.shouldReloadPlaylist(s)&&this.setSubtitleTrack(this.trackId)}},i.findTrackId=function(t){for(var e=this.tracksInGroup,i=this.selectDefaultTrack,r=0;r<e.length;r++){var s=e[r];if((!i||s.default)&&(i||t)&&(!t||pr(s,t)))return r}if(t){for(var n=0;n<e.length;n++){var a=e[n];if(Fn(t.attrs,a.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return n}for(var o=0;o<e.length;o++){var l=e[o];if(Fn(t.attrs,l.attrs,["LANGUAGE"]))return o}}return-1},i.findTrackForTextTrack=function(t){if(t)for(var e=this.tracksInGroup,i=0;i<e.length;i++)if(Nn(e[i],t))return i;return-1},i.onError=function(t,e){!e.fatal&&e.context&&(e.context.type!==ze.SUBTITLE_TRACK||e.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(e.context.groupId)||this.checkRetry(e))},i.setSubtitleOption=function(t){if(this.hls.config.subtitlePreference=t,t){var e=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,e.length){var i=this.currentTrack;if(i&&pr(t,i))return i;var r=mr(t,this.tracksInGroup);if(r>-1){var s=this.tracksInGroup[r];return this.setSubtitleTrack(r),s}if(i)return null;var n=mr(t,e);if(n>-1)return e[n]}}return null},i.loadPlaylist=function(e){t.prototype.loadPlaylist.call(this);var i=this.currentTrack;if(this.shouldLoadPlaylist(i)&&i){var r=i.id,s=i.groupId,n=i.url;if(e)try{n=e.addDirectives(n)}catch(t){this.warn("Could not construct new URL with HLS Delivery Directives: "+t)}this.log("Loading subtitle playlist for id "+r),this.hls.trigger(D.SUBTITLE_TRACK_LOADING,{url:n,id:r,groupId:s,deliveryDirectives:e||null})}},i.toggleTrackModes=function(){var t=this.media;if(t){var e,i=oi(t.textTracks),r=this.currentTrack;if(r&&((e=i.filter((function(t){return Nn(r,t)}))[0])||this.warn('Unable to find subtitle TextTrack with name "'+r.name+'" and language "'+r.lang+'"')),[].slice.call(i).forEach((function(t){"disabled"!==t.mode&&t!==e&&(t.mode="disabled")})),e){var s=this.subtitleDisplay?"showing":"hidden";e.mode!==s&&(e.mode=s)}}},i.setSubtitleTrack=function(t){var e=this.tracksInGroup;if(this.media)if(t<-1||t>=e.length||!R(t))this.warn("Invalid subtitle track id: "+t);else{this.clearTimer(),this.selectDefaultTrack=!1;var i=this.currentTrack,r=e[t]||null;if(this.trackId=t,this.currentTrack=r,this.toggleTrackModes(),r){var s=!!r.details&&!r.details.live;if(t!==this.trackId||r!==i||!s){this.log("Switching to subtitle-track "+t+(r?' "'+r.name+'" lang:'+r.lang+" group:"+r.groupId:""));var n=r.id,a=r.groupId,o=void 0===a?"":a,l=r.name,h=r.type,d=r.url;this.hls.trigger(D.SUBTITLE_TRACK_SWITCH,{id:n,groupId:o,name:l,type:h,url:d});var u=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(u)}}else this.hls.trigger(D.SUBTITLE_TRACK_SWITCH,{id:t})}else this.queuedDefaultTrack=t},o(e,[{key:"subtitleDisplay",get:function(){return this._subtitleDisplay},set:function(t){this._subtitleDisplay=t,this.trackId>-1&&this.toggleTrackModes()}},{key:"allSubtitleTracks",get:function(){return this.tracks}},{key:"subtitleTracks",get:function(){return this.tracksInGroup}},{key:"subtitleTrack",get:function(){return this.trackId},set:function(t){this.selectDefaultTrack=!1,this.setSubtitleTrack(t)}}]),e}(er),Yn=function(){function t(t){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=t}var e=t.prototype;return e.append=function(t,e,i){var r=this.queues[e];r.push(t),1!==r.length||i||this.executeNext(e)},e.insertAbort=function(t,e){this.queues[e].unshift(t),this.executeNext(e)},e.appendBlocker=function(t){var e,i=new Promise((function(t){e=t})),r={execute:e,onStart:function(){},onComplete:function(){},onError:function(){}};return this.append(r,t),i},e.executeNext=function(t){var e=this.queues[t];if(e.length){var i=e[0];try{i.execute()}catch(e){F.warn('[buffer-operation-queue]: Exception executing "'+t+'" SourceBuffer operation: '+e),i.onError(e);var r=this.buffers[t];null!=r&&r.updating||this.shiftAndExecuteNext(t)}}},e.shiftAndExecuteNext=function(t){this.queues[t].shift(),this.executeNext(t)},e.current=function(t){return this.queues[t][0]},t}(),Wn=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,jn=function(){function t(t){var e=this;this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.appendSource=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this.log=void 0,this.warn=void 0,this.error=void 0,this._onEndStreaming=function(t){e.hls&&e.hls.pauseBuffering()},this._onStartStreaming=function(t){e.hls&&e.hls.resumeBuffering()},this._onMediaSourceOpen=function(){var t=e.media,i=e.mediaSource;e.log("Media source opened"),t&&(t.removeEventListener("emptied",e._onMediaEmptied),e.updateMediaElementDuration(),e.hls.trigger(D.MEDIA_ATTACHED,{media:t,mediaSource:i})),i&&i.removeEventListener("sourceopen",e._onMediaSourceOpen),e.checkPendingTracks()},this._onMediaSourceClose=function(){e.log("Media source closed")},this._onMediaSourceEnded=function(){e.log("Media source ended")},this._onMediaEmptied=function(){var t=e.mediaSrc,i=e._objectUrl;t!==i&&F.error("Media element src was set while attaching MediaSource ("+i+" > "+t+")")},this.hls=t;var i="[buffer-controller]";this.appendSource=Ae(Se(t.config.preferManagedMediaSource)),this.log=F.log.bind(F,i),this.warn=F.warn.bind(F,i),this.error=F.error.bind(F,i),this._initSourceBuffer(),this.registerListeners()}var e=t.prototype;return e.hasSourceTypes=function(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0},e.destroy=function(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.hls=null},e.registerListeners=function(){var t=this.hls;t.on(D.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(D.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(D.MANIFEST_LOADING,this.onManifestLoading,this),t.on(D.MANIFEST_PARSED,this.onManifestParsed,this),t.on(D.BUFFER_RESET,this.onBufferReset,this),t.on(D.BUFFER_APPENDING,this.onBufferAppending,this),t.on(D.BUFFER_CODECS,this.onBufferCodecs,this),t.on(D.BUFFER_EOS,this.onBufferEos,this),t.on(D.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(D.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(D.FRAG_PARSED,this.onFragParsed,this),t.on(D.FRAG_CHANGED,this.onFragChanged,this)},e.unregisterListeners=function(){var t=this.hls;t.off(D.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(D.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(D.MANIFEST_LOADING,this.onManifestLoading,this),t.off(D.MANIFEST_PARSED,this.onManifestParsed,this),t.off(D.BUFFER_RESET,this.onBufferReset,this),t.off(D.BUFFER_APPENDING,this.onBufferAppending,this),t.off(D.BUFFER_CODECS,this.onBufferCodecs,this),t.off(D.BUFFER_EOS,this.onBufferEos,this),t.off(D.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(D.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(D.FRAG_PARSED,this.onFragParsed,this),t.off(D.FRAG_CHANGED,this.onFragChanged,this)},e._initSourceBuffer=function(){this.sourceBuffer={},this.operationQueue=new Yn(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.appendErrors={audio:0,video:0,audiovideo:0},this.lastMpegAudioChunk=null},e.onManifestLoading=function(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null},e.onManifestParsed=function(t,e){var i=2;(e.audio&&!e.video||!e.altAudio)&&(i=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=i,this.log(this.bufferCodecEventsExpected+" bufferCodec event(s) expected")},e.onMediaAttaching=function(t,e){var i=this.media=e.media,r=Se(this.appendSource);if(i&&r){var s,n=this.mediaSource=new r;this.log("created media source: "+(null==(s=n.constructor)?void 0:s.name)),n.addEventListener("sourceopen",this._onMediaSourceOpen),n.addEventListener("sourceended",this._onMediaSourceEnded),n.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(n.addEventListener("startstreaming",this._onStartStreaming),n.addEventListener("endstreaming",this._onEndStreaming));var a=this._objectUrl=self.URL.createObjectURL(n);if(this.appendSource)try{i.removeAttribute("src");var o=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||o&&n instanceof o,qn(i),Xn(i,a),i.load()}catch(t){i.src=a}else i.src=a;i.addEventListener("emptied",this._onMediaEmptied)}},e.onMediaDetaching=function(){var t=this.media,e=this.mediaSource,i=this._objectUrl;if(e){if(this.log("media source detaching"),"open"===e.readyState)try{e.endOfStream()}catch(t){this.warn("onMediaDetaching: "+t.message+" while calling endOfStream")}this.onBufferReset(),e.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("sourceended",this._onMediaSourceEnded),e.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.removeEventListener("startstreaming",this._onStartStreaming),e.removeEventListener("endstreaming",this._onEndStreaming)),t&&(t.removeEventListener("emptied",this._onMediaEmptied),i&&self.URL.revokeObjectURL(i),this.mediaSrc===i?(t.removeAttribute("src"),this.appendSource&&qn(t),t.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(D.MEDIA_DETACHED,void 0)},e.onBufferReset=function(){var t=this;this.getSourceBufferTypes().forEach((function(e){t.resetBuffer(e)})),this._initSourceBuffer()},e.resetBuffer=function(t){var e=this.sourceBuffer[t];try{var i;e&&(this.removeBufferListeners(t),this.sourceBuffer[t]=void 0,null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(e))}catch(e){this.warn("onBufferReset "+t,e)}},e.onBufferCodecs=function(t,e){var i=this,r=this.getSourceBufferTypes().length,s=Object.keys(e);if(s.forEach((function(t){if(r){var s=i.tracks[t];if(s&&"function"==typeof s.buffer.changeType){var n,a=e[t],o=a.id,l=a.codec,h=a.levelCodec,d=a.container,u=a.metadata,c=Me(s.codec,s.levelCodec),f=null==c?void 0:c.replace(Wn,"$1"),g=Me(l,h),m=null==(n=g)?void 0:n.replace(Wn,"$1");if(g&&f!==m){"audio"===t.slice(0,5)&&(g=xe(g,i.appendSource));var p=d+";codecs="+g;i.appendChangeType(t,p),i.log("switching codec "+c+" to "+g),i.tracks[t]={buffer:s.buffer,codec:l,container:d,levelCodec:h,metadata:u,id:o}}}}else i.pendingTracks[t]=e[t]})),!r){var n=Math.max(this.bufferCodecEventsExpected-1,0);this.bufferCodecEventsExpected!==n&&(this.log(n+" bufferCodec event(s) expected "+s.join(",")),this.bufferCodecEventsExpected=n),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks()}},e.appendChangeType=function(t,e){var i=this,r=this.operationQueue,s={execute:function(){var s=i.sourceBuffer[t];s&&(i.log("changing "+t+" sourceBuffer type to "+e),s.changeType(e)),r.shiftAndExecuteNext(t)},onStart:function(){},onComplete:function(){},onError:function(e){i.warn("Failed to change "+t+" SourceBuffer type",e)}};r.append(s,t,!!this.pendingTracks[t])},e.onBufferAppending=function(t,e){var i=this,r=this.hls,s=this.operationQueue,n=this.tracks,a=e.data,o=e.type,l=e.frag,h=e.part,d=e.chunkMeta,u=d.buffering[o],c=self.performance.now();u.start=c;var f=l.stats.buffering,g=h?h.stats.buffering:null;0===f.start&&(f.start=c),g&&0===g.start&&(g.start=c);var m=n.audio,p=!1;"audio"===o&&"audio/mpeg"===(null==m?void 0:m.container)&&(p=!this.lastMpegAudioChunk||1===d.id||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);var v=l.start,y={execute:function(){if(u.executeStart=self.performance.now(),p){var t=i.sourceBuffer[o];if(t){var e=v-t.timestampOffset;Math.abs(e)>=.1&&(i.log("Updating audio SourceBuffer timestampOffset to "+v+" (delta: "+e+") sn: "+l.sn+")"),t.timestampOffset=v)}}i.appendExecutor(a,o)},onStart:function(){},onComplete:function(){var t=self.performance.now();u.executeEnd=u.end=t,0===f.first&&(f.first=t),g&&0===g.first&&(g.first=t);var e=i.sourceBuffer,r={};for(var s in e)r[s]=Ir.getBuffered(e[s]);i.appendErrors[o]=0,"audio"===o||"video"===o?i.appendErrors.audiovideo=0:(i.appendErrors.audio=0,i.appendErrors.video=0),i.hls.trigger(D.BUFFER_APPENDED,{type:o,frag:l,part:h,chunkMeta:d,parent:l.type,timeRanges:r})},onError:function(t){var e={type:I.MEDIA_ERROR,parent:l.type,details:w.BUFFER_APPEND_ERROR,sourceBufferName:o,frag:l,part:h,chunkMeta:d,error:t,err:t,fatal:!1};if(t.code===DOMException.QUOTA_EXCEEDED_ERR)e.details=w.BUFFER_FULL_ERROR;else{var s=++i.appendErrors[o];e.details=w.BUFFER_APPEND_ERROR,i.warn("Failed "+s+"/"+r.config.appendErrorMaxRetry+' times to append segment in "'+o+'" sourceBuffer'),s>=r.config.appendErrorMaxRetry&&(e.fatal=!0)}r.trigger(D.ERROR,e)}};s.append(y,o,!!this.pendingTracks[o])},e.onBufferFlushing=function(t,e){var i=this,r=this.operationQueue,s=function(t){return{execute:i.removeExecutor.bind(i,t,e.startOffset,e.endOffset),onStart:function(){},onComplete:function(){i.hls.trigger(D.BUFFER_FLUSHED,{type:t})},onError:function(e){i.warn("Failed to remove from "+t+" SourceBuffer",e)}}};e.type?r.append(s(e.type),e.type):this.getSourceBufferTypes().forEach((function(t){r.append(s(t),t)}))},e.onFragParsed=function(t,e){var i=this,r=e.frag,s=e.part,n=[],a=s?s.elementaryStreams:r.elementaryStreams;a[V.AUDIOVIDEO]?n.push("audiovideo"):(a[V.AUDIO]&&n.push("audio"),a[V.VIDEO]&&n.push("video"));var o=function(){var t=self.performance.now();r.stats.buffering.end=t,s&&(s.stats.buffering.end=t);var e=s?s.stats:r.stats;i.hls.trigger(D.FRAG_BUFFERED,{frag:r,part:s,stats:e,id:r.type})};0===n.length&&this.warn("Fragments must have at least one ElementaryStreamType set. type: "+r.type+" level: "+r.level+" sn: "+r.sn),this.blockBuffers(o,n)},e.onFragChanged=function(t,e){this.trimBuffers()},e.onBufferEos=function(t,e){var i=this;this.getSourceBufferTypes().reduce((function(t,r){var s=i.sourceBuffer[r];return!s||e.type&&e.type!==r||(s.ending=!0,s.ended||(s.ended=!0,i.log(r+" sourceBuffer now EOS"))),t&&!(s&&!s.ended)}),!0)&&(this.log("Queueing mediaSource.endOfStream()"),this.blockBuffers((function(){i.getSourceBufferTypes().forEach((function(t){var e=i.sourceBuffer[t];e&&(e.ending=!1)}));var t=i.mediaSource;t&&"open"===t.readyState?(i.log("Calling mediaSource.endOfStream()"),t.endOfStream()):t&&i.log("Could not call mediaSource.endOfStream(). mediaSource.readyState: "+t.readyState)})))},e.onLevelUpdated=function(t,e){var i=e.details;i.fragments.length&&(this.details=i,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())},e.trimBuffers=function(){var t=this.hls,e=this.details,i=this.media;if(i&&null!==e&&this.getSourceBufferTypes().length){var r=t.config,s=i.currentTime,n=e.levelTargetDuration,a=e.live&&null!==r.liveBackBufferLength?r.liveBackBufferLength:r.backBufferLength;if(R(a)&&a>0){var o=Math.max(a,n),l=Math.floor(s/n)*n-o;this.flushBackBuffer(s,n,l)}if(R(r.frontBufferFlushThreshold)&&r.frontBufferFlushThreshold>0){var h=Math.max(r.maxBufferLength,r.frontBufferFlushThreshold),d=Math.max(h,n),u=Math.floor(s/n)*n+d;this.flushFrontBuffer(s,n,u)}}},e.flushBackBuffer=function(t,e,i){var r=this,s=this.details,n=this.sourceBuffer;this.getSourceBufferTypes().forEach((function(a){var o=n[a];if(o){var l=Ir.getBuffered(o);if(l.length>0&&i>l.start(0)){if(r.hls.trigger(D.BACK_BUFFER_REACHED,{bufferEnd:i}),null!=s&&s.live)r.hls.trigger(D.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(o.ended&&l.end(l.length-1)-t<2*e)return void r.log("Cannot flush "+a+" back buffer while SourceBuffer is in ended state");r.hls.trigger(D.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:a})}}}))},e.flushFrontBuffer=function(t,e,i){var r=this,s=this.sourceBuffer;this.getSourceBufferTypes().forEach((function(n){var a=s[n];if(a){var o=Ir.getBuffered(a),l=o.length;if(l<2)return;var h=o.start(l-1),d=o.end(l-1);if(i>h||t>=h&&t<=d)return;if(a.ended&&t-d<2*e)return void r.log("Cannot flush "+n+" front buffer while SourceBuffer is in ended state");r.hls.trigger(D.BUFFER_FLUSHING,{startOffset:h,endOffset:1/0,type:n})}}))},e.updateMediaElementDuration=function(){if(this.details&&this.media&&this.mediaSource&&"open"===this.mediaSource.readyState){var t=this.details,e=this.hls,i=this.media,r=this.mediaSource,s=t.fragments[0].start+t.totalduration,n=i.duration,a=R(r.duration)?r.duration:0;t.live&&e.config.liveDurationInfinity?(r.duration=1/0,this.updateSeekableRange(t)):(s>a&&s>n||!R(n))&&(this.log("Updating Media Source duration to "+s.toFixed(3)),r.duration=s)}},e.updateSeekableRange=function(t){var e=this.mediaSource,i=t.fragments;if(i.length&&t.live&&null!=e&&e.setLiveSeekableRange){var r=Math.max(0,i[0].start),s=Math.max(r,r+t.totalduration);this.log("Media Source duration is set to "+e.duration+". Setting seekable range to "+r+"-"+s+"."),e.setLiveSeekableRange(r,s)}},e.checkPendingTracks=function(){var t=this.bufferCodecEventsExpected,e=this.operationQueue,i=this.pendingTracks,r=Object.keys(i).length;if(r&&(!t||2===r||"audiovideo"in i)){this.createSourceBuffers(i),this.pendingTracks={};var s=this.getSourceBufferTypes();if(s.length)this.hls.trigger(D.BUFFER_CREATED,{tracks:this.tracks}),s.forEach((function(t){e.executeNext(t)}));else{var n=new Error("could not create source buffer for media codec(s)");this.hls.trigger(D.ERROR,{type:I.MEDIA_ERROR,details:w.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:n,reason:n.message})}}},e.createSourceBuffers=function(t){var e=this,i=this.sourceBuffer,r=this.mediaSource;if(!r)throw Error("createSourceBuffers called when mediaSource was null");var s=function(s){if(!i[s]){var n,a=t[s];if(!a)throw Error("source buffer exists for track "+s+", however track does not");var o=-1===(null==(n=a.levelCodec)?void 0:n.indexOf(","))?a.levelCodec:a.codec;o&&"audio"===s.slice(0,5)&&(o=xe(o,e.appendSource));var l=a.container+";codecs="+o;e.log("creating sourceBuffer("+l+")");try{var h=i[s]=r.addSourceBuffer(l),d=s;e.addBufferListener(d,"updatestart",e._onSBUpdateStart),e.addBufferListener(d,"updateend",e._onSBUpdateEnd),e.addBufferListener(d,"error",e._onSBUpdateError),e.appendSource&&e.addBufferListener(d,"bufferedchange",(function(t,i){var r=i.removedRanges;null!=r&&r.length&&e.hls.trigger(D.BUFFER_FLUSHED,{type:s})})),e.tracks[s]={buffer:h,codec:o,container:a.container,levelCodec:a.levelCodec,metadata:a.metadata,id:a.id}}catch(t){e.error("error while trying to add sourceBuffer: "+t.message),e.hls.trigger(D.ERROR,{type:I.MEDIA_ERROR,details:w.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,sourceBufferName:s,mimeType:l})}}};for(var n in t)s(n)},e._onSBUpdateStart=function(t){this.operationQueue.current(t).onStart()},e._onSBUpdateEnd=function(t){var e;if("closed"!==(null==(e=this.mediaSource)?void 0:e.readyState)){var i=this.operationQueue;i.current(t).onComplete(),i.shiftAndExecuteNext(t)}else this.resetBuffer(t)},e._onSBUpdateError=function(t,e){var i,r=new Error(t+" SourceBuffer error. MediaSource readyState: "+(null==(i=this.mediaSource)?void 0:i.readyState));this.error(""+r,e),this.hls.trigger(D.ERROR,{type:I.MEDIA_ERROR,details:w.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:r,fatal:!1});var s=this.operationQueue.current(t);s&&s.onError(r)},e.removeExecutor=function(t,e,i){var r=this.media,s=this.mediaSource,n=this.operationQueue,a=this.sourceBuffer[t];if(!r||!s||!a)return this.warn("Attempting to remove from the "+t+" SourceBuffer, but it does not exist"),void n.shiftAndExecuteNext(t);var o=R(r.duration)?r.duration:1/0,l=R(s.duration)?s.duration:1/0,h=Math.max(0,e),d=Math.min(i,o,l);d>h&&(!a.ending||a.ended)?(a.ended=!1,this.log("Removing ["+h+","+d+"] from the "+t+" SourceBuffer"),a.remove(h,d)):n.shiftAndExecuteNext(t)},e.appendExecutor=function(t,e){var i=this.sourceBuffer[e];if(i)i.ended=!1,i.appendBuffer(t);else if(!this.pendingTracks[e])throw new Error("Attempting to append to the "+e+" SourceBuffer, but it does not exist")},e.blockBuffers=function(t,e){var i=this;if(void 0===e&&(e=this.getSourceBufferTypes()),!e.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),void Promise.resolve().then(t);var r=this.operationQueue,s=e.map((function(t){return r.appendBlocker(t)}));Promise.all(s).then((function(){t(),e.forEach((function(t){var e=i.sourceBuffer[t];null!=e&&e.updating||r.shiftAndExecuteNext(t)}))}))},e.getSourceBufferTypes=function(){return Object.keys(this.sourceBuffer)},e.addBufferListener=function(t,e,i){var r=this.sourceBuffer[t];if(r){var s=i.bind(this,t);this.listeners[t].push({event:e,listener:s}),r.addEventListener(e,s)}},e.removeBufferListeners=function(t){var e=this.sourceBuffer[t];e&&this.listeners[t].forEach((function(t){e.removeEventListener(t.event,t.listener)}))},o(t,[{key:"mediaSrc",get:function(){var t,e,i=(null==(t=this.media)||null==(e=t.querySelector)?void 0:e.call(t,"source"))||this.media;return null==i?void 0:i.src}}]),t}();function qn(t){var e=t.querySelectorAll("source");[].slice.call(e).forEach((function(e){t.removeChild(e)}))}function Xn(t,e){var i=self.document.createElement("source");i.type="video/mp4",i.src=e,t.appendChild(i)}var zn={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},Qn=function(t){return String.fromCharCode(zn[t]||t)},Jn=15,Zn=100,ta={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},ea={17:2,18:4,21:6,22:8,23:10,19:13,20:15},ia={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},ra={25:2,26:4,29:6,30:8,31:10,27:13,28:15},sa=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],na=function(){function t(){this.time=null,this.verboseLevel=0}return t.prototype.log=function(t,e){if(this.verboseLevel>=t){var i="function"==typeof e?e():e;F.log(this.time+" ["+t+"] "+i)}},t}(),aa=function(t){for(var e=[],i=0;i<t.length;i++)e.push(t[i].toString(16));return e},oa=function(){function t(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}var e=t.prototype;return e.reset=function(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1},e.setStyles=function(t){for(var e=["foreground","underline","italics","background","flash"],i=0;i<e.length;i++){var r=e[i];t.hasOwnProperty(r)&&(this[r]=t[r])}},e.isDefault=function(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash},e.equals=function(t){return this.foreground===t.foreground&&this.underline===t.underline&&this.italics===t.italics&&this.background===t.background&&this.flash===t.flash},e.copy=function(t){this.foreground=t.foreground,this.underline=t.underline,this.italics=t.italics,this.background=t.background,this.flash=t.flash},e.toString=function(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash},t}(),la=function(){function t(){this.uchar=" ",this.penState=new oa}var e=t.prototype;return e.reset=function(){this.uchar=" ",this.penState.reset()},e.setChar=function(t,e){this.uchar=t,this.penState.copy(e)},e.setPenState=function(t){this.penState.copy(t)},e.equals=function(t){return this.uchar===t.uchar&&this.penState.equals(t.penState)},e.copy=function(t){this.uchar=t.uchar,this.penState.copy(t.penState)},e.isEmpty=function(){return" "===this.uchar&&this.penState.isDefault()},t}(),ha=function(){function t(t){this.chars=[],this.pos=0,this.currPenState=new oa,this.cueStartTime=null,this.logger=void 0;for(var e=0;e<Zn;e++)this.chars.push(new la);this.logger=t}var e=t.prototype;return e.equals=function(t){for(var e=0;e<Zn;e++)if(!this.chars[e].equals(t.chars[e]))return!1;return!0},e.copy=function(t){for(var e=0;e<Zn;e++)this.chars[e].copy(t.chars[e])},e.isEmpty=function(){for(var t=!0,e=0;e<Zn;e++)if(!this.chars[e].isEmpty()){t=!1;break}return t},e.setCursor=function(t){this.pos!==t&&(this.pos=t),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>Zn&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Zn)},e.moveCursor=function(t){var e=this.pos+t;if(t>1)for(var i=this.pos+1;i<e+1;i++)this.chars[i].setPenState(this.currPenState);this.setCursor(e)},e.backSpace=function(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)},e.insertChar=function(t){var e=this;t>=144&&this.backSpace();var i=Qn(t);this.pos>=Zn?this.logger.log(0,(function(){return"Cannot insert "+t.toString(16)+" ("+i+") at position "+e.pos+". Skipping it!"})):(this.chars[this.pos].setChar(i,this.currPenState),this.moveCursor(1))},e.clearFromPos=function(t){var e;for(e=t;e<Zn;e++)this.chars[e].reset()},e.clear=function(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()},e.clearToEndOfRow=function(){this.clearFromPos(this.pos)},e.getTextString=function(){for(var t=[],e=!0,i=0;i<Zn;i++){var r=this.chars[i].uchar;" "!==r&&(e=!1),t.push(r)}return e?"":t.join("")},e.setPenStyles=function(t){this.currPenState.setStyles(t),this.chars[this.pos].setPenState(this.currPenState)},t}(),da=function(){function t(t){this.rows=[],this.currRow=Jn-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(var e=0;e<Jn;e++)this.rows.push(new ha(t));this.logger=t}var e=t.prototype;return e.reset=function(){for(var t=0;t<Jn;t++)this.rows[t].clear();this.currRow=Jn-1},e.equals=function(t){for(var e=!0,i=0;i<Jn;i++)if(!this.rows[i].equals(t.rows[i])){e=!1;break}return e},e.copy=function(t){for(var e=0;e<Jn;e++)this.rows[e].copy(t.rows[e])},e.isEmpty=function(){for(var t=!0,e=0;e<Jn;e++)if(!this.rows[e].isEmpty()){t=!1;break}return t},e.backSpace=function(){this.rows[this.currRow].backSpace()},e.clearToEndOfRow=function(){this.rows[this.currRow].clearToEndOfRow()},e.insertChar=function(t){this.rows[this.currRow].insertChar(t)},e.setPen=function(t){this.rows[this.currRow].setPenStyles(t)},e.moveCursor=function(t){this.rows[this.currRow].moveCursor(t)},e.setCursor=function(t){this.logger.log(2,"setCursor: "+t),this.rows[this.currRow].setCursor(t)},e.setPAC=function(t){this.logger.log(2,(function(){return"pacData = "+JSON.stringify(t)}));var e=t.row-1;if(this.nrRollUpRows&&e<this.nrRollUpRows-1&&(e=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==e){for(var i=0;i<Jn;i++)this.rows[i].clear();var r=this.currRow+1-this.nrRollUpRows,s=this.lastOutputScreen;if(s){var n=s.rows[r].cueStartTime,a=this.logger.time;if(null!==n&&null!==a&&n<a)for(var o=0;o<this.nrRollUpRows;o++)this.rows[e-this.nrRollUpRows+o+1].copy(s.rows[r+o])}}this.currRow=e;var l=this.rows[this.currRow];if(null!==t.indent){var h=t.indent,d=Math.max(h-1,0);l.setCursor(t.indent),t.color=l.chars[d].penState.foreground}var u={foreground:t.color,underline:t.underline,italics:t.italics,background:"black",flash:!1};this.setPen(u)},e.setBkgData=function(t){this.logger.log(2,(function(){return"bkgData = "+JSON.stringify(t)})),this.backSpace(),this.setPen(t),this.insertChar(32)},e.setRollUpRows=function(t){this.nrRollUpRows=t},e.rollUp=function(){var t=this;if(null!==this.nrRollUpRows){this.logger.log(1,(function(){return t.getDisplayText()}));var e=this.currRow+1-this.nrRollUpRows,i=this.rows.splice(e,1)[0];i.clear(),this.rows.splice(this.currRow,0,i),this.logger.log(2,"Rolling up")}else this.logger.log(3,"roll_up but nrRollUpRows not set yet")},e.getDisplayText=function(t){t=t||!1;for(var e=[],i="",r=-1,s=0;s<Jn;s++){var n=this.rows[s].getTextString();n&&(r=s+1,t?e.push("Row "+r+": '"+n+"'"):e.push(n.trim()))}return e.length>0&&(i=t?"["+e.join(" | ")+"]":e.join("\n")),i},e.getTextAndFormat=function(){return this.rows},t}(),ua=function(){function t(t,e,i){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=t,this.outputFilter=e,this.mode=null,this.verbose=0,this.displayedMemory=new da(i),this.nonDisplayedMemory=new da(i),this.lastOutputScreen=new da(i),this.currRollUpRow=this.displayedMemory.rows[Jn-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}var e=t.prototype;return e.reset=function(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[Jn-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null},e.getHandler=function(){return this.outputFilter},e.setHandler=function(t){this.outputFilter=t},e.setPAC=function(t){this.writeScreen.setPAC(t)},e.setBkgData=function(t){this.writeScreen.setBkgData(t)},e.setMode=function(t){t!==this.mode&&(this.mode=t,this.logger.log(2,(function(){return"MODE="+t})),"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=t)},e.insertChars=function(t){for(var e=this,i=0;i<t.length;i++)this.writeScreen.insertChar(t[i]);var r=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,(function(){return r+": "+e.writeScreen.getDisplayText(!0)})),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,(function(){return"DISPLAYED: "+e.displayedMemory.getDisplayText(!0)})),this.outputDataUpdate())},e.ccRCL=function(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")},e.ccBS=function(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())},e.ccAOF=function(){},e.ccAON=function(){},e.ccDER=function(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()},e.ccRU=function(t){this.logger.log(2,"RU("+t+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(t)},e.ccFON=function(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})},e.ccRDC=function(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")},e.ccTR=function(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")},e.ccRTD=function(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")},e.ccEDM=function(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)},e.ccCR=function(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)},e.ccENM=function(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()},e.ccEOC=function(){var t=this;if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){var e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,(function(){return"DISP: "+t.displayedMemory.getDisplayText()}))}this.outputDataUpdate(!0)},e.ccTO=function(t){this.logger.log(2,"TO("+t+") - Tab Offset"),this.writeScreen.moveCursor(t)},e.ccMIDROW=function(t){var e={flash:!1};if(e.underline=t%2==1,e.italics=t>=46,e.italics)e.foreground="white";else{var i=Math.floor(t/2)-16,r=["white","green","blue","cyan","red","yellow","magenta"];e.foreground=r[i]}this.logger.log(2,"MIDROW: "+JSON.stringify(e)),this.writeScreen.setPen(e)},e.outputDataUpdate=function(t){void 0===t&&(t=!1);var e=this.logger.time;null!==e&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,e,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:e):this.cueStartTime=e,this.lastOutputScreen.copy(this.displayedMemory))},e.cueSplitAtTime=function(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))},t}(),ca=function(){function t(t,e,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=ma(),this.logger=void 0;var r=this.logger=new na;this.channels=[null,new ua(t,e,r),new ua(t+1,i,r)]}var e=t.prototype;return e.getHandler=function(t){return this.channels[t].getHandler()},e.setHandler=function(t,e){this.channels[t].setHandler(e)},e.addData=function(t,e){var i=this;this.logger.time=t;for(var r=function(t){var r=127&e[t],s=127&e[t+1],n=!1,a=null;if(0===r&&0===s)return 0;i.logger.log(3,(function(){return"["+aa([e[t],e[t+1]])+"] -> ("+aa([r,s])+")"}));var o=i.cmdHistory;if(r>=16&&r<=31){if(ga(r,s,o))return fa(null,null,o),i.logger.log(3,(function(){return"Repeated command ("+aa([r,s])+") is dropped"})),0;fa(r,s,i.cmdHistory),(n=i.parseCmd(r,s))||(n=i.parseMidrow(r,s)),n||(n=i.parsePAC(r,s)),n||(n=i.parseBackgroundAttributes(r,s))}else fa(null,null,o);if(!n&&(a=i.parseChars(r,s))){var l=i.currentChannel;l&&l>0?i.channels[l].insertChars(a):i.logger.log(2,"No channel found yet. TEXT-MODE?")}n||a||i.logger.log(2,(function(){return"Couldn't parse cleaned data "+aa([r,s])+" orig: "+aa([e[t],e[t+1]])}))},s=0;s<e.length;s+=2)r(s)},e.parseCmd=function(t,e){if(!((20===t||28===t||21===t||29===t)&&e>=32&&e<=47||(23===t||31===t)&&e>=33&&e<=35))return!1;var i=20===t||21===t||23===t?1:2,r=this.channels[i];return 20===t||21===t||28===t||29===t?32===e?r.ccRCL():33===e?r.ccBS():34===e?r.ccAOF():35===e?r.ccAON():36===e?r.ccDER():37===e?r.ccRU(2):38===e?r.ccRU(3):39===e?r.ccRU(4):40===e?r.ccFON():41===e?r.ccRDC():42===e?r.ccTR():43===e?r.ccRTD():44===e?r.ccEDM():45===e?r.ccCR():46===e?r.ccENM():47===e&&r.ccEOC():r.ccTO(e-32),this.currentChannel=i,!0},e.parseMidrow=function(t,e){var i=0;if((17===t||25===t)&&e>=32&&e<=47){if((i=17===t?1:2)!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;var r=this.channels[i];return!!r&&(r.ccMIDROW(e),this.logger.log(3,(function(){return"MIDROW ("+aa([t,e])+")"})),!0)}return!1},e.parsePAC=function(t,e){var i;if(!((t>=17&&t<=23||t>=25&&t<=31)&&e>=64&&e<=127||(16===t||24===t)&&e>=64&&e<=95))return!1;var r=t<=23?1:2;i=e>=64&&e<=95?1===r?ta[t]:ia[t]:1===r?ea[t]:ra[t];var s=this.channels[r];return!!s&&(s.setPAC(this.interpretPAC(i,e)),this.currentChannel=r,!0)},e.interpretPAC=function(t,e){var i,r={color:null,italics:!1,indent:null,underline:!1,row:t};return i=e>95?e-96:e-64,r.underline=!(1&~i),i<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(r.italics=!0,r.color="white"):r.indent=4*Math.floor((i-16)/2),r},e.parseChars=function(t,e){var i,r,s=null,n=null;return t>=25?(i=2,n=t-8):(i=1,n=t),n>=17&&n<=19?(r=17===n?e+80:18===n?e+112:e+144,this.logger.log(2,(function(){return"Special char '"+Qn(r)+"' in channel "+i})),s=[r]):t>=32&&t<=127&&(s=0===e?[t]:[t,e]),s&&this.logger.log(3,(function(){return"Char codes = "+aa(s).join(",")})),s},e.parseBackgroundAttributes=function(t,e){var i;if(!((16===t||24===t)&&e>=32&&e<=47||(23===t||31===t)&&e>=45&&e<=47))return!1;var r={};16===t||24===t?(i=Math.floor((e-32)/2),r.background=sa[i],e%2==1&&(r.background=r.background+"_semi")):45===e?r.background="transparent":(r.foreground="black",47===e&&(r.underline=!0));var s=t<=23?1:2;return this.channels[s].setBkgData(r),!0},e.reset=function(){for(var t=0;t<Object.keys(this.channels).length;t++){var e=this.channels[t];e&&e.reset()}fa(null,null,this.cmdHistory)},e.cueSplitAtTime=function(t){for(var e=0;e<this.channels.length;e++){var i=this.channels[e];i&&i.cueSplitAtTime(t)}},t}();function fa(t,e,i){i.a=t,i.b=e}function ga(t,e,i){return i.a===t&&i.b===e}function ma(){return{a:null,b:null}}var pa=function(){function t(t,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=e}var e=t.prototype;return e.dispatchCue=function(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)},e.newCue=function(t,e,i){(null===this.startTime||this.startTime>t)&&(this.startTime=t),this.endTime=e,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)},e.reset=function(){this.cueRanges=[],this.startTime=null},t}(),va=function(){if(null!=et&&et.VTTCue)return self.VTTCue;var t=["","lr","rl"],e=["start","middle","end","left","right"];function i(t,e){if("string"!=typeof e)return!1;if(!Array.isArray(t))return!1;var i=e.toLowerCase();return!!~t.indexOf(i)&&i}function r(e){return i(t,e)}function s(t){return i(e,t)}function n(t){for(var e=arguments.length,i=new Array(e>1?e-1:0),r=1;r<e;r++)i[r-1]=arguments[r];for(var s=1;s<arguments.length;s++){var n=arguments[s];for(var a in n)t[a]=n[a]}return t}function a(t,e,i){var a=this,o={enumerable:!0};a.hasBeenReset=!1;var l="",h=!1,d=t,u=e,c=i,f=null,g="",m=!0,p="auto",v="start",y=50,E="middle",T=50,S="middle";Object.defineProperty(a,"id",n({},o,{get:function(){return l},set:function(t){l=""+t}})),Object.defineProperty(a,"pauseOnExit",n({},o,{get:function(){return h},set:function(t){h=!!t}})),Object.defineProperty(a,"startTime",n({},o,{get:function(){return d},set:function(t){if("number"!=typeof t)throw new TypeError("Start time must be set to a number.");d=t,this.hasBeenReset=!0}})),Object.defineProperty(a,"endTime",n({},o,{get:function(){return u},set:function(t){if("number"!=typeof t)throw new TypeError("End time must be set to a number.");u=t,this.hasBeenReset=!0}})),Object.defineProperty(a,"text",n({},o,{get:function(){return c},set:function(t){c=""+t,this.hasBeenReset=!0}})),Object.defineProperty(a,"region",n({},o,{get:function(){return f},set:function(t){f=t,this.hasBeenReset=!0}})),Object.defineProperty(a,"vertical",n({},o,{get:function(){return g},set:function(t){var e=r(t);if(!1===e)throw new SyntaxError("An invalid or illegal string was specified.");g=e,this.hasBeenReset=!0}})),Object.defineProperty(a,"snapToLines",n({},o,{get:function(){return m},set:function(t){m=!!t,this.hasBeenReset=!0}})),Object.defineProperty(a,"line",n({},o,{get:function(){return p},set:function(t){if("number"!=typeof t&&"auto"!==t)throw new SyntaxError("An invalid number or illegal string was specified.");p=t,this.hasBeenReset=!0}})),Object.defineProperty(a,"lineAlign",n({},o,{get:function(){return v},set:function(t){var e=s(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");v=e,this.hasBeenReset=!0}})),Object.defineProperty(a,"position",n({},o,{get:function(){return y},set:function(t){if(t<0||t>100)throw new Error("Position must be between 0 and 100.");y=t,this.hasBeenReset=!0}})),Object.defineProperty(a,"positionAlign",n({},o,{get:function(){return E},set:function(t){var e=s(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");E=e,this.hasBeenReset=!0}})),Object.defineProperty(a,"size",n({},o,{get:function(){return T},set:function(t){if(t<0||t>100)throw new Error("Size must be between 0 and 100.");T=t,this.hasBeenReset=!0}})),Object.defineProperty(a,"align",n({},o,{get:function(){return S},set:function(t){var e=s(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");S=e,this.hasBeenReset=!0}})),a.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}(),ya=function(){function t(){}return t.prototype.decode=function(t,e){if(!t)return"";if("string"!=typeof t)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))},t}();function Ea(t){function e(t,e,i,r){return 3600*(0|t)+60*(0|e)+(0|i)+parseFloat(r||0)}var i=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return i?parseFloat(i[2])>59?e(i[2],i[3],0,i[4]):e(i[1],i[2],i[3],i[4]):null}var Ta=function(){function t(){this.values=Object.create(null)}var e=t.prototype;return e.set=function(t,e){this.get(t)||""===e||(this.values[t]=e)},e.get=function(t,e,i){return i?this.has(t)?this.values[t]:e[i]:this.has(t)?this.values[t]:e},e.has=function(t){return t in this.values},e.alt=function(t,e,i){for(var r=0;r<i.length;++r)if(e===i[r]){this.set(t,e);break}},e.integer=function(t,e){/^-?\d+$/.test(e)&&this.set(t,parseInt(e,10))},e.percent=function(t,e){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(e)){var i=parseFloat(e);if(i>=0&&i<=100)return this.set(t,i),!0}return!1},t}();function Sa(t,e,i,r){var s=r?t.split(r):[t];for(var n in s)if("string"==typeof s[n]){var a=s[n].split(i);2===a.length&&e(a[0],a[1])}}var Aa=new va(0,0,""),La="middle"===Aa.align?"middle":"center";function Ra(t,e,i){var r=t;function s(){var e=Ea(t);if(null===e)throw new Error("Malformed timestamp: "+r);return t=t.replace(/^[^\sa-zA-Z-]+/,""),e}function n(t,e){var r=new Ta;Sa(t,(function(t,e){var s;switch(t){case"region":for(var n=i.length-1;n>=0;n--)if(i[n].id===e){r.set(t,i[n].region);break}break;case"vertical":r.alt(t,e,["rl","lr"]);break;case"line":s=e.split(","),r.integer(t,s[0]),r.percent(t,s[0])&&r.set("snapToLines",!1),r.alt(t,s[0],["auto"]),2===s.length&&r.alt("lineAlign",s[1],["start",La,"end"]);break;case"position":s=e.split(","),r.percent(t,s[0]),2===s.length&&r.alt("positionAlign",s[1],["start",La,"end","line-left","line-right","auto"]);break;case"size":r.percent(t,e);break;case"align":r.alt(t,e,["start",La,"end","left","right"])}}),/:/,/\s/),e.region=r.get("region",null),e.vertical=r.get("vertical","");var s=r.get("line","auto");"auto"===s&&-1===Aa.line&&(s=-1),e.line=s,e.lineAlign=r.get("lineAlign","start"),e.snapToLines=r.get("snapToLines",!0),e.size=r.get("size",100),e.align=r.get("align",La);var n=r.get("position","auto");"auto"===n&&50===Aa.position&&(n="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=n}function a(){t=t.replace(/^\s+/,"")}if(a(),e.startTime=s(),a(),"--\x3e"!==t.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+r);t=t.slice(3),a(),e.endTime=s(),a(),n(t,e)}function ba(t){return t.replace(/<br(?: \/)?>/gi,"\n")}var ka=function(){function t(){this.state="INITIAL",this.buffer="",this.decoder=new ya,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}var e=t.prototype;return e.parse=function(t){var e=this;function i(){var t=e.buffer,i=0;for(t=ba(t);i<t.length&&"\r"!==t[i]&&"\n"!==t[i];)++i;var r=t.slice(0,i);return"\r"===t[i]&&++i,"\n"===t[i]&&++i,e.buffer=t.slice(i),r}function r(t){Sa(t,(function(t,e){}),/:/)}t&&(e.buffer+=e.decoder.decode(t,{stream:!0}));try{var s="";if("INITIAL"===e.state){if(!/\r\n|\n/.test(e.buffer))return this;var n=(s=i()).match(/^()?WEBVTT([ \t].*)?$/);if(null==n||!n[0])throw new Error("Malformed WebVTT signature.");e.state="HEADER"}for(var a=!1;e.buffer;){if(!/\r\n|\n/.test(e.buffer))return this;switch(a?a=!1:s=i(),e.state){case"HEADER":/:/.test(s)?r(s):s||(e.state="ID");continue;case"NOTE":s||(e.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(s)){e.state="NOTE";break}if(!s)continue;if(e.cue=new va(0,0,""),e.state="CUE",-1===s.indexOf("--\x3e")){e.cue.id=s;continue}case"CUE":if(!e.cue){e.state="BADCUE";continue}try{Ra(s,e.cue,e.regionList)}catch(t){e.cue=null,e.state="BADCUE";continue}e.state="CUETEXT";continue;case"CUETEXT":var o=-1!==s.indexOf("--\x3e");if(!s||o&&(a=!0)){e.oncue&&e.cue&&e.oncue(e.cue),e.cue=null,e.state="ID";continue}if(null===e.cue)continue;e.cue.text&&(e.cue.text+="\n"),e.cue.text+=s;continue;case"BADCUE":s||(e.state="ID")}}}catch(t){"CUETEXT"===e.state&&e.cue&&e.oncue&&e.oncue(e.cue),e.cue=null,e.state="INITIAL"===e.state?"BADWEBVTT":"BADCUE"}return this},e.flush=function(){var t=this;try{if((t.cue||"HEADER"===t.state)&&(t.buffer+="\n\n",t.parse()),"INITIAL"===t.state||"BADWEBVTT"===t.state)throw new Error("Malformed WebVTT signature.")}catch(e){t.onparsingerror&&t.onparsingerror(e)}return t.onflush&&t.onflush(),this},t}(),Da=/\r\n|\n\r|\n|\r/g,Ia=function(t,e,i){return void 0===i&&(i=0),t.slice(i,i+e.length)===e},wa=function(t){var e=parseInt(t.slice(-3)),i=parseInt(t.slice(-6,-4)),r=parseInt(t.slice(-9,-7)),s=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!(R(e)&&R(i)&&R(r)&&R(s)))throw Error("Malformed X-TIMESTAMP-MAP: Local:"+t);return e+=1e3*i,e+=6e4*r,e+=36e5*s},Ca=function(t){for(var e=5381,i=t.length;i;)e=33*e^t.charCodeAt(--i);return(e>>>0).toString()};function _a(t,e,i){return Ca(t.toString())+Ca(e.toString())+Ca(i)}var Pa=function(t,e,i){var r=t[e],s=t[r.prevCC];if(!s||!s.new&&r.new)return t.ccOffset=t.presentationOffset=r.start,void(r.new=!1);for(;null!=(n=s)&&n.new;){var n;t.ccOffset+=r.start-s.start,r.new=!1,s=t[(r=s).prevCC]}t.presentationOffset=i};function xa(t,e,i,r,s,n,a){var o,l=new ka,h=wt(new Uint8Array(t)).trim().replace(Da,"\n").split("\n"),d=[],u=e?Zs(e.baseTime,e.timescale):0,c="00:00.000",f=0,g=0,m=!0;l.oncue=function(t){var n=i[r],a=i.ccOffset,l=(f-u)/9e4;if(null!=n&&n.new&&(void 0!==g?a=i.ccOffset=n.start:Pa(i,r,l)),l){if(!e)return void(o=new Error("Missing initPTS for VTT MPEGTS"));a=l-i.presentationOffset}var h=t.endTime-t.startTime,c=ln(9e4*(t.startTime+a-g),9e4*s)/9e4;t.startTime=Math.max(c,0),t.endTime=Math.max(c+h,0);var m=t.text.trim();t.text=decodeURIComponent(encodeURIComponent(m)),t.id||(t.id=_a(t.startTime,t.endTime,m)),t.endTime>0&&d.push(t)},l.onparsingerror=function(t){o=t},l.onflush=function(){o?a(o):n(d)},h.forEach((function(t){if(m){if(Ia(t,"X-TIMESTAMP-MAP=")){m=!1,t.slice(16).split(",").forEach((function(t){Ia(t,"LOCAL:")?c=t.slice(6):Ia(t,"MPEGTS:")&&(f=parseInt(t.slice(7)))}));try{g=wa(c)/1e3}catch(t){o=t}return}""===t&&(m=!1)}l.parse(t+"\n")})),l.flush()}var Ma="stpp.ttml.im1t",Oa=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Fa=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Na={left:"start",center:"center",right:"end",start:"start",end:"end"};function Ua(t,e,i,r){var s=Ht(new Uint8Array(t),["mdat"]);if(0!==s.length){var n=s.map((function(t){return wt(t)})),a=Qs(e.baseTime,1,e.timescale);try{n.forEach((function(t){return i(Ba(t,a))}))}catch(t){r(t)}}else r(new Error("Could not parse IMSC1 mdat"))}function Ba(t,e){var i=(new DOMParser).parseFromString(t,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");var r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},s=Object.keys(r).reduce((function(t,e){return t[e]=i.getAttribute("ttp:"+e)||r[e],t}),{}),n="preserve"!==i.getAttribute("xml:space"),a=Ka(Ga(i,"styling","style")),o=Ka(Ga(i,"layout","region")),l=Ga(i,"body","[begin]");return[].map.call(l,(function(t){var i=Ha(t,n);if(!i||!t.hasAttribute("begin"))return null;var r=Wa(t.getAttribute("begin"),s),l=Wa(t.getAttribute("dur"),s),d=Wa(t.getAttribute("end"),s);if(null===r)throw Ya(t);if(null===d){if(null===l)throw Ya(t);d=r+l}var u=new va(r-e,d-e,i);u.id=_a(u.startTime,u.endTime,u.text);var c=$a(o[t.getAttribute("region")],a[t.getAttribute("style")],a),f=c.textAlign;if(f){var g=Na[f];g&&(u.lineAlign=g),u.align=f}return h(u,c),u})).filter((function(t){return null!==t}))}function Ga(t,e,i){var r=t.getElementsByTagName(e)[0];return r?[].slice.call(r.querySelectorAll(i)):[]}function Ka(t){return t.reduce((function(t,e){var i=e.getAttribute("xml:id");return i&&(t[i]=e),t}),{})}function Ha(t,e){return[].slice.call(t.childNodes).reduce((function(t,i,r){var s;return"br"===i.nodeName&&r?t+"\n":null!=(s=i.childNodes)&&s.length?Ha(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent}),"")}function $a(t,e,i){var r="http://www.w3.org/ns/ttml#styling",s=null,n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=t&&t.hasAttribute("style")?t.getAttribute("style"):null;return a&&i.hasOwnProperty(a)&&(s=i[a]),n.reduce((function(i,n){var a=Va(e,r,n)||Va(t,r,n)||Va(s,r,n);return a&&(i[n]=a),i}),{})}function Va(t,e,i){return t&&t.hasAttributeNS(e,i)?t.getAttributeNS(e,i):null}function Ya(t){return new Error("Could not parse ttml timestamp "+t)}function Wa(t,e){if(!t)return null;var i=Ea(t);return null===i&&(Oa.test(t)?i=ja(t,e):Fa.test(t)&&(i=qa(t,e))),i}function ja(t,e){var i=Oa.exec(t),r=(0|i[4])+(0|i[5])/e.subFrameRate;return 3600*(0|i[1])+60*(0|i[2])+(0|i[3])+r/e.frameRate}function qa(t,e){var i=Fa.exec(t),r=Number(i[1]);switch(i[2]){case"h":return 3600*r;case"m":return 60*r;case"ms":return 1e3*r;case"f":return r/e.frameRate;case"t":return r/e.tickRate}return r}var Xa=function(){function t(t){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Za(),this.captionsProperties=void 0,this.hls=t,this.config=t.config,this.Cues=t.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},t.on(D.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(D.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(D.MANIFEST_LOADING,this.onManifestLoading,this),t.on(D.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(D.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(D.FRAG_LOADING,this.onFragLoading,this),t.on(D.FRAG_LOADED,this.onFragLoaded,this),t.on(D.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(D.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(D.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(D.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(D.BUFFER_FLUSHING,this.onBufferFlushing,this)}var e=t.prototype;return e.destroy=function(){var t=this.hls;t.off(D.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(D.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(D.MANIFEST_LOADING,this.onManifestLoading,this),t.off(D.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(D.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(D.FRAG_LOADING,this.onFragLoading,this),t.off(D.FRAG_LOADED,this.onFragLoaded,this),t.off(D.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(D.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(D.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(D.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(D.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=null,this.cea608Parser1=this.cea608Parser2=void 0},e.initCea608Parsers=function(){if(this.config.enableCEA708Captions&&(!this.cea608Parser1||!this.cea608Parser2)){var t=new pa(this,"textTrack1"),e=new pa(this,"textTrack2"),i=new pa(this,"textTrack3"),r=new pa(this,"textTrack4");this.cea608Parser1=new ca(1,t,e),this.cea608Parser2=new ca(3,i,r)}},e.addCues=function(t,e,i,r,s){for(var n=!1,a=s.length;a--;){var o=s[a],l=Ja(o[0],o[1],e,i);if(l>=0&&(o[0]=Math.min(o[0],e),o[1]=Math.max(o[1],i),n=!0,l/(i-e)>.5))return}if(n||s.push([e,i]),this.config.renderTextTracksNatively){var h=this.captionsTracks[t];this.Cues.newCue(h,e,i,r)}else{var d=this.Cues.newCue(null,e,i,r);this.hls.trigger(D.CUES_PARSED,{type:"captions",cues:d,track:t})}},e.onInitPtsFound=function(t,e){var i=this,r=e.frag,s=e.id,n=e.initPTS,a=e.timescale,o=this.unparsedVttFrags;"main"===s&&(this.initPTS[r.cc]={baseTime:n,timescale:a}),o.length&&(this.unparsedVttFrags=[],o.forEach((function(t){i.onFragLoaded(D.FRAG_LOADED,t)})))},e.getExistingTrack=function(t,e){var i=this.media;if(i)for(var r=0;r<i.textTracks.length;r++){var s=i.textTracks[r];if(Qa(s,{name:t,lang:e,attrs:{}}))return s}return null},e.createCaptionsTrack=function(t){this.config.renderTextTracksNatively?this.createNativeTrack(t):this.createNonNativeTrack(t)},e.createNativeTrack=function(t){if(!this.captionsTracks[t]){var e=this.captionsProperties,i=this.captionsTracks,r=this.media,s=e[t],n=s.label,a=s.languageCode,o=this.getExistingTrack(n,a);if(o)i[t]=o,ri(i[t]),ei(i[t],r);else{var l=this.createTextTrack("captions",n,a);l&&(l[t]=!0,i[t]=l)}}},e.createNonNativeTrack=function(t){if(!this.nonNativeCaptionsTracks[t]){var e=this.captionsProperties[t];if(e){var i={_id:t,label:e.label,kind:"captions",default:!!e.media&&!!e.media.default,closedCaptions:e.media};this.nonNativeCaptionsTracks[t]=i,this.hls.trigger(D.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}}},e.createTextTrack=function(t,e,i){var r=this.media;if(r)return r.addTextTrack(t,e,i)},e.onMediaAttaching=function(t,e){this.media=e.media,this._cleanTracks()},e.onMediaDetaching=function(){var t=this.captionsTracks;Object.keys(t).forEach((function(e){ri(t[e]),delete t[e]})),this.nonNativeCaptionsTracks={}},e.onManifestLoading=function(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Za(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())},e._cleanTracks=function(){var t=this.media;if(t){var e=t.textTracks;if(e)for(var i=0;i<e.length;i++)ri(e[i])}},e.onSubtitleTracksUpdated=function(t,e){var i=this,r=e.subtitleTracks||[],s=r.some((function(t){return t.textCodec===Ma}));if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(On(this.tracks,r))return void(this.tracks=r);if(this.textTracks=[],this.tracks=r,this.config.renderTextTracksNatively){var n=this.media,a=n?oi(n.textTracks):null;if(this.tracks.forEach((function(t,e){var r;if(a){for(var s=null,n=0;n<a.length;n++)if(a[n]&&Qa(a[n],t)){s=a[n],a[n]=null;break}s&&(r=s)}if(r)ri(r);else{var o=za(t);(r=i.createTextTrack(o,t.name,t.lang))&&(r.mode="disabled")}r&&i.textTracks.push(r)})),null!=a&&a.length){var o=a.filter((function(t){return null!==t})).map((function(t){return t.label}));o.length&&F.warn("Media element contains unused subtitle tracks: "+o.join(", ")+". Replace media element for each source to clear TextTracks and captions menu.")}}else if(this.tracks.length){var l=this.tracks.map((function(t){return{label:t.name,kind:t.type.toLowerCase(),default:t.default,subtitleTrack:t}}));this.hls.trigger(D.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:l})}}},e.onManifestLoaded=function(t,e){var i=this;this.config.enableCEA708Captions&&e.captions&&e.captions.forEach((function(t){var e=/(?:CC|SERVICE)([1-4])/.exec(t.instreamId);if(e){var r="textTrack"+e[1],s=i.captionsProperties[r];s&&(s.label=t.name,t.lang&&(s.languageCode=t.lang),s.media=t)}}))},e.closedCaptionsForLevel=function(t){var e=this.hls.levels[t.level];return null==e?void 0:e.attrs["CLOSED-CAPTIONS"]},e.onFragLoading=function(t,e){if(this.enabled&&e.frag.type===Qe.MAIN){var i,r,s=this.cea608Parser1,n=this.cea608Parser2,a=this.lastSn,o=e.frag,l=o.cc,h=o.sn,d=null!=(i=null==(r=e.part)?void 0:r.index)?i:-1;s&&n&&(h!==a+1||h===a&&d!==this.lastPartIndex+1||l!==this.lastCc)&&(s.reset(),n.reset()),this.lastCc=l,this.lastSn=h,this.lastPartIndex=d}},e.onFragLoaded=function(t,e){var i=e.frag,r=e.payload;if(i.type===Qe.SUBTITLE)if(r.byteLength){var s=i.decryptdata,n="stats"in e;if(null==s||!s.encrypted||n){var a=this.tracks[i.level],o=this.vttCCs;o[i.cc]||(o[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),a&&a.textCodec===Ma?this._parseIMSC1(i,r):this._parseVTTs(e)}}else this.hls.trigger(D.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})},e._parseIMSC1=function(t,e){var i=this,r=this.hls;Ua(e,this.initPTS[t.cc],(function(e){i._appendCues(e,t.level),r.trigger(D.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})}),(function(e){F.log("Failed to parse IMSC1: "+e),r.trigger(D.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:e})}))},e._parseVTTs=function(t){var e,i=this,r=t.frag,s=t.payload,n=this.initPTS,a=this.unparsedVttFrags,o=n.length-1;if(n[r.cc]||-1!==o){var l=this.hls;xa(null!=(e=r.initSegment)&&e.data?ie(r.initSegment.data,new Uint8Array(s)):s,this.initPTS[r.cc],this.vttCCs,r.cc,r.start,(function(t){i._appendCues(t,r.level),l.trigger(D.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:r})}),(function(e){var n="Missing initPTS for VTT MPEGTS"===e.message;n?a.push(t):i._fallbackToIMSC1(r,s),F.log("Failed to parse VTT cue: "+e),n&&o>r.cc||l.trigger(D.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:e})}))}else a.push(t)},e._fallbackToIMSC1=function(t,e){var i=this,r=this.tracks[t.level];r.textCodec||Ua(e,this.initPTS[t.cc],(function(){r.textCodec=Ma,i._parseIMSC1(t,e)}),(function(){r.textCodec="wvtt"}))},e._appendCues=function(t,e){var i=this.hls;if(this.config.renderTextTracksNatively){var r=this.textTracks[e];if(!r||"disabled"===r.mode)return;t.forEach((function(t){return ii(r,t)}))}else{var s=this.tracks[e];if(!s)return;var n=s.default?"default":"subtitles"+e;i.trigger(D.CUES_PARSED,{type:"subtitles",cues:t,track:n})}},e.onFragDecrypted=function(t,e){e.frag.type===Qe.SUBTITLE&&this.onFragLoaded(D.FRAG_LOADED,e)},e.onSubtitleTracksCleared=function(){this.tracks=[],this.captionsTracks={}},e.onFragParsingUserdata=function(t,e){this.initCea608Parsers();var i=this.cea608Parser1,r=this.cea608Parser2;if(this.enabled&&i&&r){var s=e.frag,n=e.samples;if(s.type!==Qe.MAIN||"NONE"!==this.closedCaptionsForLevel(s))for(var a=0;a<n.length;a++){var o=n[a].bytes;if(o){var l=this.extractCea608Data(o);i.addData(n[a].pts,l[0]),r.addData(n[a].pts,l[1])}}}},e.onBufferFlushing=function(t,e){var i=e.startOffset,r=e.endOffset,s=e.endOffsetSubtitles,n=e.type,a=this.media;if(a&&!(a.currentTime<r)){if(!n||"video"===n){var o=this.captionsTracks;Object.keys(o).forEach((function(t){return si(o[t],i,r)}))}if(this.config.renderTextTracksNatively&&0===i&&void 0!==s){var l=this.textTracks;Object.keys(l).forEach((function(t){return si(l[t],i,s)}))}}},e.extractCea608Data=function(t){for(var e=[[],[]],i=31&t[0],r=2,s=0;s<i;s++){var n=t[r++],a=127&t[r++],o=127&t[r++];if((0!==a||0!==o)&&4&n){var l=3&n;0!==l&&1!==l||(e[l].push(a),e[l].push(o))}}return e},t}();function za(t){return t.characteristics&&/transcribes-spoken-dialog/gi.test(t.characteristics)&&/describes-music-and-sound/gi.test(t.characteristics)?"captions":"subtitles"}function Qa(t,e){return!!t&&t.kind===za(e)&&Nn(e,t)}function Ja(t,e,i,r){return Math.min(e,r)-Math.max(t,i)}function Za(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}var to=function(){function t(t){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}var e=t.prototype;return e.setStreamController=function(t){this.streamController=t},e.destroy=function(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null},e.registerListeners=function(){var t=this.hls;t.on(D.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(D.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(D.MANIFEST_PARSED,this.onManifestParsed,this),t.on(D.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(D.BUFFER_CODECS,this.onBufferCodecs,this),t.on(D.MEDIA_DETACHING,this.onMediaDetaching,this)},e.unregisterListener=function(){var t=this.hls;t.off(D.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(D.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(D.MANIFEST_PARSED,this.onManifestParsed,this),t.off(D.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(D.BUFFER_CODECS,this.onBufferCodecs,this),t.off(D.MEDIA_DETACHING,this.onMediaDetaching,this)},e.onFpsDropLevelCapping=function(t,e){var i=this.hls.levels[e.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})},e.onMediaAttaching=function(t,e){this.media=e.media instanceof HTMLVideoElement?e.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()},e.onManifestParsed=function(t,e){var i=this.hls;this.restrictedLevels=[],this.firstLevel=e.firstLevel,i.config.capLevelToPlayerSize&&e.video&&this.startCapping()},e.onLevelsUpdated=function(t,e){this.timer&&R(this.autoLevelCapping)&&this.detectPlayerSize()},e.onBufferCodecs=function(t,e){this.hls.config.capLevelToPlayerSize&&e.video&&this.startCapping()},e.onMediaDetaching=function(){this.stopCapping()},e.detectPlayerSize=function(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);var t=this.hls.levels;if(t.length){var e=this.hls,i=this.getMaxLevel(t.length-1);i!==this.autoLevelCapping&&F.log("Setting autoLevelCapping to "+i+": "+t[i].height+"p@"+t[i].bitrate+" for media "+this.mediaWidth+"x"+this.mediaHeight),e.autoLevelCapping=i,e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}}},e.getMaxLevel=function(e){var i=this,r=this.hls.levels;if(!r.length)return-1;var s=r.filter((function(t,r){return i.isLevelAllowed(t)&&r<=e}));return this.clientRect=null,t.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)},e.startCapping=function(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())},e.stopCapping=function(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)},e.getDimensions=function(){if(this.clientRect)return this.clientRect;var t=this.media,e={width:0,height:0};if(t){var i=t.getBoundingClientRect();e.width=i.width,e.height=i.height,e.width||e.height||(e.width=i.right-i.left||t.width||0,e.height=i.bottom-i.top||t.height||0)}return this.clientRect=e,e},e.isLevelAllowed=function(t){return!this.restrictedLevels.some((function(e){return t.bitrate===e.bitrate&&t.width===e.width&&t.height===e.height}))},t.getMaxLevelByMediaSize=function(t,e,i){if(null==t||!t.length)return-1;for(var r=function(t,e){return!e||t.width!==e.width||t.height!==e.height},s=t.length-1,n=Math.max(e,i),a=0;a<t.length;a+=1){var o=t[a];if((o.width>=n||o.height>=n)&&r(o,t[a+1])){s=a;break}}return s},o(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 t=1;if(!this.hls.config.ignoreDevicePixelRatio)try{t=self.devicePixelRatio}catch(t){}return t}}]),t}(),eo=function(){function t(t){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()}var e=t.prototype;return e.setStreamController=function(t){this.streamController=t},e.registerListeners=function(){this.hls.on(D.MEDIA_ATTACHING,this.onMediaAttaching,this)},e.unregisterListeners=function(){this.hls.off(D.MEDIA_ATTACHING,this.onMediaAttaching,this)},e.destroy=function(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null},e.onMediaAttaching=function(t,e){var i=this.hls.config;if(i.capLevelOnFPSDrop){var r=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=r,r&&"function"==typeof r.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}},e.checkFPS=function(t,e,i){var r=performance.now();if(e){if(this.lastTime){var s=r-this.lastTime,n=i-this.lastDroppedFrames,a=e-this.lastDecodedFrames,o=1e3*n/s,l=this.hls;if(l.trigger(D.FPS_DROP,{currentDropped:n,currentDecoded:a,totalDroppedFrames:i}),o>0&&n>l.config.fpsDroppedMonitoringThreshold*a){var h=l.currentLevel;F.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(-1===l.autoLevelCapping||l.autoLevelCapping>=h)&&(h-=1,l.trigger(D.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:l.currentLevel}),l.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=i,this.lastDecodedFrames=e}},e.checkFPSInterval=function(){var t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){var e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)},t}(),io="[eme]",ro=function(){function t(e){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=t.CDMCleanupPromise?[t.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=F.debug.bind(F,io),this.log=F.log.bind(F,io),this.warn=F.warn.bind(F,io),this.error=F.error.bind(F,io),this.hls=e,this.config=e.config,this.registerListeners()}var e=t.prototype;return e.destroy=function(){this.unregisterListeners(),this.onMediaDetached();var t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null},e.registerListeners=function(){this.hls.on(D.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(D.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(D.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(D.MANIFEST_LOADED,this.onManifestLoaded,this)},e.unregisterListeners=function(){this.hls.off(D.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(D.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(D.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(D.MANIFEST_LOADED,this.onManifestLoaded,this)},e.getLicenseServerUrl=function(t){var e=this.config,i=e.drmSystems,r=e.widevineLicenseUrl,s=i[t];if(s)return s.licenseUrl;if(t===it.WIDEVINE&&r)return r;throw new Error('no license server URL configured for key-system "'+t+'"')},e.getServerCertificateUrl=function(t){var e=this.config.drmSystems[t];if(e)return e.serverCertificateUrl;this.log('No Server Certificate in config.drmSystems["'+t+'"]')},e.attemptKeySystemAccess=function(t){var e=this,i=this.hls.levels,r=function(t,e,i){return!!t&&i.indexOf(t)===e},s=i.map((function(t){return t.audioCodec})).filter(r),n=i.map((function(t){return t.videoCodec})).filter(r);return s.length+n.length===0&&n.push("avc1.42e01e"),new Promise((function(i,r){!function t(a){var o=a.shift();e.getMediaKeysPromise(o,s,n).then((function(t){return i({keySystem:o,mediaKeys:t})})).catch((function(e){a.length?t(a):r(e instanceof lo?e:new lo({type:I.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_ACCESS,error:e,fatal:!0},e.message))}))}(t)}))},e.requestMediaKeySystemAccess=function(t,e){var i=this.config.requestMediaKeySystemAccessFunc;if("function"!=typeof i){var r="Configured requestMediaKeySystemAccess is not a function "+i;return null===dt&&"http:"===self.location.protocol&&(r="navigator.requestMediaKeySystemAccess is not available over insecure protocol "+location.protocol),Promise.reject(new Error(r))}return i(t,e)},e.getMediaKeysPromise=function(t,e,i){var r=this,s=ut(t,e,i,this.config.drmSystemOptions),n=this.keySystemAccessPromises[t],a=null==n?void 0:n.keySystemAccess;if(!a){this.log('Requesting encrypted media "'+t+'" key-system access with config: '+JSON.stringify(s)),a=this.requestMediaKeySystemAccess(t,s);var o=this.keySystemAccessPromises[t]={keySystemAccess:a};return a.catch((function(e){r.log('Failed to obtain access to key-system "'+t+'": '+e)})),a.then((function(e){r.log('Access for key-system "'+e.keySystem+'" obtained');var i=r.fetchServerCertificate(t);return r.log('Create media-keys for "'+t+'"'),o.mediaKeys=e.createMediaKeys().then((function(e){return r.log('Media-keys created for "'+t+'"'),i.then((function(i){return i?r.setMediaKeysServerCertificate(e,t,i):e}))})),o.mediaKeys.catch((function(e){r.error('Failed to create media-keys for "'+t+'"}: '+e)})),o.mediaKeys}))}return a.then((function(){return n.mediaKeys}))},e.createMediaKeySessionContext=function(t){var e=t.decryptdata,i=t.keySystem,r=t.mediaKeys;this.log('Creating key-system session "'+i+'" keyId: '+_t.hexDump(e.keyId||[]));var s=r.createSession(),n={decryptdata:e,keySystem:i,mediaKeys:r,mediaKeysSession:s,keyStatus:"status-pending"};return this.mediaKeySessions.push(n),n},e.renewKeySession=function(t){var e=t.decryptdata;if(e.pssh){var i=this.createMediaKeySessionContext(t),r=this.getKeyIdString(e),s="cenc";this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(i,s,e.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)},e.getKeyIdString=function(t){if(!t)throw new Error("Could not read keyId of undefined decryptdata");if(null===t.keyId)throw new Error("keyId is null");return _t.hexDump(t.keyId)},e.updateKeySession=function(t,e){var i,r=t.mediaKeysSession;return this.log('Updating key-session "'+r.sessionId+'" for keyID '+_t.hexDump((null==(i=t.decryptdata)?void 0:i.keyId)||[])+"\n } (data length: "+(e?e.byteLength:e)+")"),r.update(e)},e.selectKeySystemFormat=function(t){var e=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log("Selecting key-system from fragment (sn: "+t.sn+" "+t.type+": "+t.level+") key formats "+e.join(", ")),this.keyFormatPromise=this.getKeyFormatPromise(e)),this.keyFormatPromise},e.getKeyFormatPromise=function(t){var e=this;return new Promise((function(i,r){var s=lt(e.config),n=t.map(st).filter((function(t){return!!t&&-1!==s.indexOf(t)}));return e.getKeySystemSelectionPromise(n).then((function(t){var e=t.keySystem,s=ot(e);s?i(s):r(new Error('Unable to find format for key-system "'+e+'"'))})).catch(r)}))},e.loadKey=function(t){var e=this,i=t.keyInfo.decryptdata,r=this.getKeyIdString(i),s="(keyId: "+r+' format: "'+i.keyFormat+'" method: '+i.method+" uri: "+i.uri+")";this.log("Starting session for key "+s);var n=this.keyIdToKeySessionPromise[r];return n||(n=this.keyIdToKeySessionPromise[r]=this.getKeySystemForKeyPromise(i).then((function(r){var n=r.keySystem,a=r.mediaKeys;return e.throwIfDestroyed(),e.log("Handle encrypted media sn: "+t.frag.sn+" "+t.frag.type+": "+t.frag.level+" using key "+s),e.attemptSetMediaKeys(n,a).then((function(){e.throwIfDestroyed();var t=e.createMediaKeySessionContext({keySystem:n,mediaKeys:a,decryptdata:i}),r="cenc";return e.generateRequestWithPreferredKeySession(t,r,i.pssh,"playlist-key")}))}))).catch((function(t){return e.handleError(t)})),n},e.throwIfDestroyed=function(t){if(!this.hls)throw new Error("invalid state")},e.handleError=function(t){this.hls&&(this.error(t.message),t instanceof lo?this.hls.trigger(D.ERROR,t.data):this.hls.trigger(D.ERROR,{type:I.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0}))},e.getKeySystemForKeyPromise=function(t){var e=this.getKeyIdString(t),i=this.keyIdToKeySessionPromise[e];if(!i){var r=st(t.keyFormat),s=r?[r]:lt(this.config);return this.attemptKeySystemAccess(s)}return i},e.getKeySystemSelectionPromise=function(t){if(t.length||(t=lt(this.config)),0===t.length)throw new lo({type:I.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},"Missing key-system license configuration options "+JSON.stringify({drmSystems:this.config.drmSystems}));return this.attemptKeySystemAccess(t)},e._onMediaEncrypted=function(t){var e=this,i=t.initDataType,r=t.initData;if(this.debug('"'+t.type+'" event: init data type: "'+i+'"'),null!==r){var s,n;if("sinf"===i&&this.config.drmSystems[it.FAIRPLAY]){var a=Ot(new Uint8Array(r));try{var o=z(JSON.parse(a).sinf),l=zt(new Uint8Array(o));if(!l)return;s=l.subarray(8,24),n=it.FAIRPLAY}catch(t){return void this.warn('Failed to parse sinf "encrypted" event message initData')}}else{var h=ue(r);if(null===h)return;0===h.version&&h.systemId===nt.WIDEVINE&&h.data&&(s=h.data.subarray(8,24)),n=at(h.systemId)}if(n&&s){for(var d,u=_t.hexDump(s),c=this.keyIdToKeySessionPromise,f=this.mediaKeySessions,g=c[u],m=function(){var t=f[p],n=t.decryptdata;if(n.pssh||!n.keyId)return 0;var a=_t.hexDump(n.keyId);return u===a||-1!==n.uri.replace(/-/g,"").indexOf(u)?(g=c[a],delete c[a],n.pssh=new Uint8Array(r),n.keyId=s,g=c[u]=g.then((function(){return e.generateRequestWithPreferredKeySession(t,i,r,"encrypted-event-key-match")})),1):void 0},p=0;p<f.length&&(0===(d=m())||1!==d);p++);g||(g=c[u]=this.getKeySystemSelectionPromise([n]).then((function(t){var n,a=t.keySystem,o=t.mediaKeys;e.throwIfDestroyed();var l=new fe("ISO-23001-7",u,null!=(n=ot(a))?n:"");return l.pssh=new Uint8Array(r),l.keyId=s,e.attemptSetMediaKeys(a,o).then((function(){e.throwIfDestroyed();var t=e.createMediaKeySessionContext({decryptdata:l,keySystem:a,mediaKeys:o});return e.generateRequestWithPreferredKeySession(t,i,r,"encrypted-event-no-match")}))}))),g.catch((function(t){return e.handleError(t)}))}}},e._onWaitingForKey=function(t){this.log('"'+t.type+'" event')},e.attemptSetMediaKeys=function(t,e){var i=this,r=this.setMediaKeysQueue.slice();this.log('Setting media-keys for "'+t+'"');var s=Promise.all(r).then((function(){if(!i.media)throw new Error("Attempted to set mediaKeys without media element attached");return i.media.setMediaKeys(e)}));return this.setMediaKeysQueue.push(s),s.then((function(){i.log('Media-keys set for "'+t+'"'),r.push(s),i.setMediaKeysQueue=i.setMediaKeysQueue.filter((function(t){return-1===r.indexOf(t)}))}))},e.generateRequestWithPreferredKeySession=function(t,e,i,r){var s,n,a=this,o=null==(s=this.config.drmSystems)||null==(n=s[t.keySystem])?void 0:n.generateRequest;if(o)try{var l=o.call(this.hls,e,i,t);if(!l)throw new Error("Invalid response from configured generateRequest filter");e=l.initDataType,i=t.decryptdata.pssh=l.initData?new Uint8Array(l.initData):null}catch(t){var h;if(this.warn(t.message),null!=(h=this.hls)&&h.config.debug)throw t}if(null===i)return this.log('Skipping key-session request for "'+r+'" (no initData)'),Promise.resolve(t);var d=this.getKeyIdString(t.decryptdata);this.log('Generating key-session request for "'+r+'": '+d+" (init data type: "+e+" length: "+(i?i.byteLength:null)+")");var u=new bn,c=t._onmessage=function(e){var i=t.mediaKeysSession;if(i){var r=e.messageType,s=e.message;a.log('"'+r+'" message event for session "'+i.sessionId+'" message size: '+s.byteLength),"license-request"===r||"license-renewal"===r?a.renewLicense(t,s).catch((function(t){a.handleError(t),u.emit("error",t)})):"license-release"===r?t.keySystem===it.FAIRPLAY&&(a.updateKeySession(t,tt("acknowledged")),a.removeSession(t)):a.warn('unhandled media key message type "'+r+'"')}else u.emit("error",new Error("invalid state"))},f=t._onkeystatuseschange=function(e){if(t.mediaKeysSession){a.onKeyStatusChange(t);var i=t.keyStatus;u.emit("keyStatus",i),"expired"===i&&(a.warn(t.keySystem+" expired for key "+d),a.renewKeySession(t))}else u.emit("error",new Error("invalid state"))};t.mediaKeysSession.addEventListener("message",c),t.mediaKeysSession.addEventListener("keystatuseschange",f);var g=new Promise((function(t,e){u.on("error",e),u.on("keyStatus",(function(i){i.startsWith("usable")?t():"output-restricted"===i?e(new lo({type:I.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===i?e(new lo({type:I.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},'key status changed to "'+i+'"')):"expired"===i?e(new Error("key expired while generating request")):a.warn('unhandled key status change "'+i+'"')}))}));return t.mediaKeysSession.generateRequest(e,i).then((function(){var e;a.log('Request generated for key-session "'+(null==(e=t.mediaKeysSession)?void 0:e.sessionId)+'" keyId: '+d)})).catch((function(t){throw new lo({type:I.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_SESSION,error:t,fatal:!1},"Error generating key-session request: "+t)})).then((function(){return g})).catch((function(e){throw u.removeAllListeners(),a.removeSession(t),e})).then((function(){return u.removeAllListeners(),t}))},e.onKeyStatusChange=function(t){var e=this;t.mediaKeysSession.keyStatuses.forEach((function(i,r){e.log('key status change "'+i+'" for keyStatuses keyId: '+_t.hexDump("buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r))+" session keyId: "+_t.hexDump(new Uint8Array(t.decryptdata.keyId||[]))+" uri: "+t.decryptdata.uri),t.keyStatus=i}))},e.fetchServerCertificate=function(t){var e=this.config,i=new(0,e.loader)(e),s=this.getServerCertificateUrl(t);return s?(this.log('Fetching server certificate for "'+t+'"'),new Promise((function(n,a){var o={responseType:"arraybuffer",url:s},l=e.certLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:function(t,e,i,r){n(t.data)},onError:function(e,i,n,l){a(new lo({type:I.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:n,response:r({url:o.url,data:void 0},e)},'"'+t+'" certificate request failed ('+s+"). Status: "+e.code+" ("+e.text+")"))},onTimeout:function(e,i,r){a(new lo({type:I.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:{url:o.url,data:void 0}},'"'+t+'" certificate request timed out ('+s+")"))},onAbort:function(t,e,i){a(new Error("aborted"))}};i.load(o,h,d)}))):Promise.resolve()},e.setMediaKeysServerCertificate=function(t,e,i){var r=this;return new Promise((function(s,n){t.setServerCertificate(i).then((function(n){r.log("setServerCertificate "+(n?"success":"not supported by CDM")+" ("+(null==i?void 0:i.byteLength)+') on "'+e+'"'),s(t)})).catch((function(t){n(new lo({type:I.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:t,fatal:!0},t.message))}))}))},e.renewLicense=function(t,e){var i=this;return this.requestLicense(t,new Uint8Array(e)).then((function(e){return i.updateKeySession(t,new Uint8Array(e)).catch((function(t){throw new lo({type:I.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:t,fatal:!0},t.message)}))}))},e.unpackPlayReadyKeyMessage=function(t,e){var i=String.fromCharCode.apply(null,new Uint16Array(e.buffer));if(!i.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),e;var r=(new DOMParser).parseFromString(i,"application/xml"),s=r.querySelectorAll("HttpHeader");if(s.length>0)for(var n,a=0,o=s.length;a<o;a++){var l,h,d=null==(l=(n=s[a]).querySelector("name"))?void 0:l.textContent,u=null==(h=n.querySelector("value"))?void 0:h.textContent;d&&u&&t.setRequestHeader(d,u)}var c=r.querySelector("Challenge"),f=null==c?void 0:c.textContent;if(!f)throw new Error("Cannot find <Challenge> in key message");return tt(atob(f))},e.setupLicenseXHR=function(t,e,i,r){var s=this,n=this.config.licenseXhrSetup;return n?Promise.resolve().then((function(){if(!i.decryptdata)throw new Error("Key removed");return n.call(s.hls,t,e,i,r)})).catch((function(a){if(!i.decryptdata)throw a;return t.open("POST",e,!0),n.call(s.hls,t,e,i,r)})).then((function(i){return t.readyState||t.open("POST",e,!0),{xhr:t,licenseChallenge:i||r}})):(t.open("POST",e,!0),Promise.resolve({xhr:t,licenseChallenge:r}))},e.requestLicense=function(t,e){var i=this,r=this.config.keyLoadPolicy.default;return new Promise((function(s,n){var a=i.getLicenseServerUrl(t.keySystem);i.log("Sending license request to URL: "+a);var o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=function(){if(!i.hls||!t.mediaKeysSession)return n(new Error("invalid state"));if(4===o.readyState)if(200===o.status){i._requestLicenseFailureCount=0;var l=o.response;i.log("License received "+(l instanceof ArrayBuffer?l.byteLength:l));var h=i.config.licenseResponseCallback;if(h)try{l=h.call(i.hls,o,a,t)}catch(t){i.error(t)}s(l)}else{var d=r.errorRetry,u=d?d.maxNumRetry:0;if(i._requestLicenseFailureCount++,i._requestLicenseFailureCount>u||o.status>=400&&o.status<500)n(new lo({type:I.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},"License Request XHR failed ("+a+"). Status: "+o.status+" ("+o.statusText+")"));else{var c=u-i._requestLicenseFailureCount+1;i.warn("Retrying license request, "+c+" attempts left"),i.requestLicense(t,e).then(s,n)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=o,i.setupLicenseXHR(o,a,t,e).then((function(e){var r=e.xhr,s=e.licenseChallenge;t.keySystem==it.PLAYREADY&&(s=i.unpackPlayReadyKeyMessage(r,s)),r.send(s)}))}))},e.onMediaAttached=function(t,e){if(this.config.emeEnabled){var i=e.media;this.media=i,i.addEventListener("encrypted",this.onMediaEncrypted),i.addEventListener("waitingforkey",this.onWaitingForKey)}},e.onMediaDetached=function(){var e=this,i=this.media,r=this.mediaKeySessions;i&&(i.removeEventListener("encrypted",this.onMediaEncrypted),i.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},fe.clearKeyUriToKeyIdMap();var s=r.length;t.CDMCleanupPromise=Promise.all(r.map((function(t){return e.removeSession(t)})).concat(null==i?void 0:i.setMediaKeys(null).catch((function(t){e.log("Could not clear media keys: "+t)})))).then((function(){s&&(e.log("finished closing key sessions and clearing media keys"),r.length=0)})).catch((function(t){e.log("Could not close sessions and clear media keys: "+t)}))},e.onManifestLoading=function(){this.keyFormatPromise=null},e.onManifestLoaded=function(t,e){var i=e.sessionKeys;if(i&&this.config.emeEnabled&&!this.keyFormatPromise){var r=i.reduce((function(t,e){return-1===t.indexOf(e.keyFormat)&&t.push(e.keyFormat),t}),[]);this.log("Selecting key-system from session-keys "+r.join(", ")),this.keyFormatPromise=this.getKeyFormatPromise(r)}},e.removeSession=function(t){var e=this,i=t.mediaKeysSession,r=t.licenseXhr;if(i){this.log("Remove licenses and keys and close session "+i.sessionId),t._onmessage&&(i.removeEventListener("message",t._onmessage),t._onmessage=void 0),t._onkeystatuseschange&&(i.removeEventListener("keystatuseschange",t._onkeystatuseschange),t._onkeystatuseschange=void 0),r&&r.readyState!==XMLHttpRequest.DONE&&r.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;var s=this.mediaKeySessions.indexOf(t);return s>-1&&this.mediaKeySessions.splice(s,1),i.remove().catch((function(t){e.log("Could not remove session: "+t)})).then((function(){return i.close()})).catch((function(t){e.log("Could not close session: "+t)}))}},t}();ro.CDMCleanupPromise=void 0;var so,no,ao,oo,lo=function(t){function e(e,i){var r;return(r=t.call(this,i)||this).data=void 0,e.error||(e.error=new Error(i)),r.data=e,e.err=e.error,r}return d(e,t),e}(p(Error));(function(t){t.MANIFEST="m",t.AUDIO="a",t.VIDEO="v",t.MUXED="av",t.INIT="i",t.CAPTION="c",t.TIMED_TEXT="tt",t.KEY="k",t.OTHER="o"})(so||(so={})),function(t){t.DASH="d",t.HLS="h",t.SMOOTH="s",t.OTHER="o"}(no||(no={})),function(t){t.OBJECT="CMCD-Object",t.REQUEST="CMCD-Request",t.SESSION="CMCD-Session",t.STATUS="CMCD-Status"}(ao||(ao={}));var ho=((oo={})[ao.OBJECT]=["br","d","ot","tb"],oo[ao.REQUEST]=["bl","dl","mtp","nor","nrr","su"],oo[ao.SESSION]=["cid","pr","sf","sid","st","v"],oo[ao.STATUS]=["bs","rtp"],oo),uo=function t(e,i){this.value=void 0,this.params=void 0,Array.isArray(e)&&(e=e.map((function(e){return e instanceof t?e:new t(e)}))),this.value=e,this.params=i},co=function(t){this.description=void 0,this.description=t},fo="Dict";function go(t){return Array.isArray(t)?JSON.stringify(t):t instanceof Map?"Map{}":t instanceof Set?"Set{}":"object"==typeof t?JSON.stringify(t):String(t)}function mo(t,e,i,r){return new Error("failed to "+t+' "'+go(e)+'" as '+i,{cause:r})}var po="Bare Item",vo="Boolean",yo="Byte Sequence",Eo="Decimal",To="Integer";function So(t){return t<-999999999999999||999999999999999<t}var Ao=/[\x00-\x1f\x7f]+/,Lo="Token",Ro="Key";function bo(t,e,i){return mo("serialize",t,e,i)}function ko(t){if("boolean"!=typeof t)throw bo(t,vo);return t?"?1":"?0"}function Do(t){return btoa(String.fromCharCode.apply(String,t))}function Io(t){if(!1===ArrayBuffer.isView(t))throw bo(t,yo);return":"+Do(t)+":"}function wo(t){if(So(t))throw bo(t,To);return t.toString()}function Co(t){return"@"+wo(t.getTime()/1e3)}function _o(t,e){if(t<0)return-_o(-t,e);var i=Math.pow(10,e);if(Math.abs(t*i%1-.5)<Number.EPSILON){var r=Math.floor(t*i);return(r%2==0?r:r+1)/i}return Math.round(t*i)/i}function Po(t){var e=_o(t,3);if(Math.floor(Math.abs(e)).toString().length>12)throw bo(t,Eo);var i=e.toString();return i.includes(".")?i:i+".0"}var xo="String";function Mo(t){if(Ao.test(t))throw bo(t,xo);return'"'+t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'}function Oo(t){return t.description||t.toString().slice(7,-1)}function Fo(t){var e=Oo(t);if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e))throw bo(e,Lo);return e}function No(t){switch(typeof t){case"number":if(!R(t))throw bo(t,po);return Number.isInteger(t)?wo(t):Po(t);case"string":return Mo(t);case"symbol":return Fo(t);case"boolean":return ko(t);case"object":if(t instanceof Date)return Co(t);if(t instanceof Uint8Array)return Io(t);if(t instanceof co)return Fo(t);default:throw bo(t,po)}}function Uo(t){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(t))throw bo(t,Ro);return t}function Bo(t){return null==t?"":Object.entries(t).map((function(t){var e=t[0],i=t[1];return!0===i?";"+Uo(e):";"+Uo(e)+"="+No(i)})).join("")}function Go(t){return t instanceof uo?""+No(t.value)+Bo(t.params):No(t)}function Ko(t){return"("+t.value.map(Go).join(" ")+")"+Bo(t.params)}function Ho(t,e){var i;if(void 0===e&&(e={whitespace:!0}),"object"!=typeof t)throw bo(t,fo);var r=t instanceof Map?t.entries():Object.entries(t),s=null!=(i=e)&&i.whitespace?" ":"";return Array.from(r).map((function(t){var e=t[0],i=t[1];i instanceof uo==0&&(i=new uo(i));var r=Uo(e);return!0===i.value?r+=Bo(i.params):(r+="=",Array.isArray(i.value)?r+=Ko(i):r+=Go(i)),r})).join(","+s)}function $o(t,e){return Ho(t,e)}var Vo=function(t){return"ot"===t||"sf"===t||"st"===t},Yo=function(t){return"number"==typeof t?R(t):null!=t&&""!==t&&!1!==t};function Wo(t,e){var i=new URL(t),r=new URL(e);if(i.origin!==r.origin)return t;for(var s=i.pathname.split("/").slice(1),n=r.pathname.split("/").slice(1,-1);s[0]===n[0];)s.shift(),n.shift();for(;n.length;)n.shift(),s.unshift("..");return s.join("/")}function jo(){try{return crypto.randomUUID()}catch(r){try{var t=URL.createObjectURL(new Blob),e=t.toString();return URL.revokeObjectURL(t),e.slice(e.lastIndexOf("/")+1)}catch(t){var i=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(t){var e=(i+16*Math.random())%16|0;return i=Math.floor(i/16),("x"==t?e:3&e|8).toString(16)}))}}}var qo=function(t){return Math.round(t)},Xo=function(t){return 100*qo(t/100)},zo={br:qo,d:qo,bl:Xo,dl:Xo,mtp:Xo,nor:function(t,e){return null!=e&&e.baseUrl&&(t=Wo(t,e.baseUrl)),encodeURIComponent(t)},rtp:Xo,tb:qo};function Qo(t,e){var i={};if(null==t||"object"!=typeof t)return i;var r=Object.keys(t).sort(),s=h({},zo,null==e?void 0:e.formatters),n=null==e?void 0:e.filter;return r.forEach((function(r){if(null==n||!n(r)){var a=t[r],o=s[r];o&&(a=o(a,e)),"v"===r&&1===a||"pr"==r&&1===a||Yo(a)&&(Vo(r)&&"string"==typeof a&&(a=new co(a)),i[r]=a)}})),i}function Jo(t,e){return void 0===e&&(e={}),t?$o(Qo(t,e),h({whitespace:!1},e)):""}function Zo(t,e){var i;if(void 0===e&&(e={}),!t)return{};var r=Object.entries(t),s=Object.entries(ho).concat(Object.entries((null==(i=e)?void 0:i.customHeaderMap)||{})),n=r.reduce((function(t,e){var i,r=e[0],n=e[1],a=(null==(i=s.find((function(t){return t[1].includes(r)})))?void 0:i[0])||ao.REQUEST;return null!=t[a]||(t[a]={}),t[a][r]=n,t}),{});return Object.entries(n).reduce((function(t,i){var r=i[0],s=i[1];return t[r]=Jo(s,e),t}),{})}function tl(t,e,i){return h(t,Zo(e,i))}var el="CMCD";function il(t,e){if(void 0===e&&(e={}),!t)return"";var i=Jo(t,e);return el+"="+encodeURIComponent(i)}var rl=/CMCD=[^&#]+/;function sl(t,e,i){var r=il(e,i);if(!r)return t;if(rl.test(t))return t.replace(rl,r);var s=t.includes("?")?"&":"?";return""+t+s+r}var nl=function(){function t(t){var e=this;this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=function(){e.initialized&&(e.starved=!0),e.buffering=!0},this.onPlaying=function(){e.initialized||(e.initialized=!0),e.buffering=!1},this.applyPlaylistData=function(t){try{e.apply(t,{ot:so.MANIFEST,su:!e.initialized})}catch(t){F.warn("Could not generate manifest CMCD data.",t)}},this.applyFragmentData=function(t){try{var i=t.frag,r=e.hls.levels[i.level],s=e.getObjectType(i),n={d:1e3*i.duration,ot:s};s!==so.VIDEO&&s!==so.AUDIO&&s!=so.MUXED||(n.br=r.bitrate/1e3,n.tb=e.getTopBandwidth(s)/1e3,n.bl=e.getBufferLength(s)),e.apply(t,n)}catch(t){F.warn("Could not generate segment CMCD data.",t)}},this.hls=t;var i=this.config=t.config,r=i.cmcd;null!=r&&(i.pLoader=this.createPlaylistLoader(),i.fLoader=this.createFragmentLoader(),this.sid=r.sessionId||jo(),this.cid=r.contentId,this.useHeaders=!0===r.useHeaders,this.includeKeys=r.includeKeys,this.registerListeners())}var e=t.prototype;return e.registerListeners=function(){var t=this.hls;t.on(D.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(D.MEDIA_DETACHED,this.onMediaDetached,this),t.on(D.BUFFER_CREATED,this.onBufferCreated,this)},e.unregisterListeners=function(){var t=this.hls;t.off(D.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(D.MEDIA_DETACHED,this.onMediaDetached,this),t.off(D.BUFFER_CREATED,this.onBufferCreated,this)},e.destroy=function(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=null},e.onMediaAttached=function(t,e){this.media=e.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)},e.onMediaDetached=function(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)},e.onBufferCreated=function(t,e){var i,r;this.audioBuffer=null==(i=e.tracks.audio)?void 0:i.buffer,this.videoBuffer=null==(r=e.tracks.video)?void 0:r.buffer},e.createData=function(){var t;return{v:1,sf:no.HLS,sid:this.sid,cid:this.cid,pr:null==(t=this.media)?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}},e.apply=function(t,e){void 0===e&&(e={}),h(e,this.createData());var i=e.ot===so.INIT||e.ot===so.VIDEO||e.ot===so.MUXED;this.starved&&i&&(e.bs=!0,e.su=!0,this.starved=!1),null==e.su&&(e.su=this.buffering);var r=this.includeKeys;r&&(e=Object.keys(e).reduce((function(t,i){return r.includes(i)&&(t[i]=e[i]),t}),{})),this.useHeaders?(t.headers||(t.headers={}),tl(t.headers,e)):t.url=sl(t.url,e)},e.getObjectType=function(t){var e=t.type;return"subtitle"===e?so.TIMED_TEXT:"initSegment"===t.sn?so.INIT:"audio"===e?so.AUDIO:"main"===e?this.hls.audioTracks.length?so.VIDEO:so.MUXED:void 0},e.getTopBandwidth=function(t){var e,i=0,r=this.hls;if(t===so.AUDIO)e=r.audioTracks;else{var s=r.maxAutoLevel,n=s>-1?s+1:r.levels.length;e=r.levels.slice(0,n)}for(var a,o=T(e);!(a=o()).done;){var l=a.value;l.bitrate>i&&(i=l.bitrate)}return i>0?i:NaN},e.getBufferLength=function(t){var e=this.hls.media,i=t===so.AUDIO?this.audioBuffer:this.videoBuffer;return i&&e?1e3*Ir.bufferInfo(i,e.currentTime,this.config.maxBufferHole).len:NaN},e.createPlaylistLoader=function(){var t=this.config.pLoader,e=this.applyPlaylistData,i=t||this.config.loader;return function(){function t(t){this.loader=void 0,this.loader=new i(t)}var r=t.prototype;return r.destroy=function(){this.loader.destroy()},r.abort=function(){this.loader.abort()},r.load=function(t,i,r){e(t),this.loader.load(t,i,r)},o(t,[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}}]),t}()},e.createFragmentLoader=function(){var t=this.config.fLoader,e=this.applyFragmentData,i=t||this.config.loader;return function(){function t(t){this.loader=void 0,this.loader=new i(t)}var r=t.prototype;return r.destroy=function(){this.loader.destroy()},r.abort=function(){this.loader.abort()},r.load=function(t,i,r){e(t),this.loader.load(t,i,r)},o(t,[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}}]),t}()},t}(),al=3e5,ol=function(){function t(t){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=t,this.log=F.log.bind(F,"[content-steering]:"),this.registerListeners()}var e=t.prototype;return e.registerListeners=function(){var t=this.hls;t.on(D.MANIFEST_LOADING,this.onManifestLoading,this),t.on(D.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(D.MANIFEST_PARSED,this.onManifestParsed,this),t.on(D.ERROR,this.onError,this)},e.unregisterListeners=function(){var t=this.hls;t&&(t.off(D.MANIFEST_LOADING,this.onManifestLoading,this),t.off(D.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(D.MANIFEST_PARSED,this.onManifestParsed,this),t.off(D.ERROR,this.onError,this))},e.startLoad=function(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){var t=1e3*this.timeToLoad-(performance.now()-this.updated);if(t>0)return void this.scheduleRefresh(this.uri,t)}this.loadSteeringManifest(this.uri)}},e.stopLoad=function(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()},e.clearTimeout=function(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)},e.destroy=function(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null},e.removeLevel=function(t){var e=this.levels;e&&(this.levels=e.filter((function(e){return e!==t})))},e.onManifestLoading=function(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null},e.onManifestLoaded=function(t,e){var i=e.contentSteering;null!==i&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())},e.onManifestParsed=function(t,e){this.audioTracks=e.audioTracks,this.subtitleTracks=e.subtitleTracks},e.onError=function(t,e){var i=e.errorAction;if((null==i?void 0:i.action)===Ji.SendAlternateToPenaltyBox&&i.flags===Zi.MoveAllAlternatesMatchingHost){var r=this.levels,s=this.pathwayPriority,n=this.pathwayId;if(e.context){var a=e.context,o=a.groupId,l=a.pathwayId,h=a.type;o&&r?n=this.getPathwayForGroupId(o,h,n):l&&(n=l)}n in this.penalizedPathways||(this.penalizedPathways[n]=performance.now()),!s&&r&&(s=r.reduce((function(t,e){return-1===t.indexOf(e.pathwayId)&&t.push(e.pathwayId),t}),[])),s&&s.length>1&&(this.updatePathwayPriority(s),i.resolved=this.pathwayId!==n),i.resolved||F.warn("Could not resolve "+e.details+' ("'+e.error.message+'") with content-steering for Pathway: '+n+" levels: "+(r?r.length:r)+" priorities: "+JSON.stringify(s)+" penalized: "+JSON.stringify(this.penalizedPathways))}},e.filterParsedLevels=function(t){this.levels=t;var e=this.getLevelsForPathway(this.pathwayId);if(0===e.length){var i=t[0].pathwayId;this.log("No levels found in Pathway "+this.pathwayId+'. Setting initial Pathway to "'+i+'"'),e=this.getLevelsForPathway(i),this.pathwayId=i}return e.length!==t.length?(this.log("Found "+e.length+"/"+t.length+' levels in Pathway "'+this.pathwayId+'"'),e):t},e.getLevelsForPathway=function(t){return null===this.levels?[]:this.levels.filter((function(e){return t===e.pathwayId}))},e.updatePathwayPriority=function(t){var e;this.pathwayPriority=t;var i=this.penalizedPathways,r=performance.now();Object.keys(i).forEach((function(t){r-i[t]>al&&delete i[t]}));for(var s=0;s<t.length;s++){var n=t[s];if(!(n in i)){if(n===this.pathwayId)return;var a=this.hls.nextLoadLevel,o=this.hls.levels[a];if((e=this.getLevelsForPathway(n)).length>0){this.log('Setting Pathway to "'+n+'"'),this.pathwayId=n,Ui(e),this.hls.trigger(D.LEVELS_UPDATED,{levels:e});var l=this.hls.levels[a];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 "+o.bitrate+" to "+l.bitrate),this.hls.nextLoadLevel=a);break}}}},e.getPathwayForGroupId=function(t,e,i){for(var r=this.getLevelsForPathway(i).concat(this.levels||[]),s=0;s<r.length;s++)if(e===ze.AUDIO_TRACK&&r[s].hasAudioGroup(t)||e===ze.SUBTITLE_TRACK&&r[s].hasSubtitleGroup(t))return r[s].pathwayId;return i},e.clonePathways=function(t){var e=this,i=this.levels;if(i){var r={},s={};t.forEach((function(t){var n=t.ID,a=t["BASE-ID"],o=t["URI-REPLACEMENT"];if(!i.some((function(t){return t.pathwayId===n}))){var l=e.getLevelsForPathway(a).map((function(t){var e=new B(t.attrs);e["PATHWAY-ID"]=n;var i=e.AUDIO&&e.AUDIO+"_clone_"+n,a=e.SUBTITLES&&e.SUBTITLES+"_clone_"+n;i&&(r[e.AUDIO]=i,e.AUDIO=i),a&&(s[e.SUBTITLES]=a,e.SUBTITLES=a);var l=hl(t.uri,e["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",o),h=new Ri({attrs:e,audioCodec:t.audioCodec,bitrate:t.bitrate,height:t.height,name:t.name,url:l,videoCodec:t.videoCodec,width:t.width});if(t.audioGroups)for(var d=1;d<t.audioGroups.length;d++)h.addGroupId("audio",t.audioGroups[d]+"_clone_"+n);if(t.subtitleGroups)for(var u=1;u<t.subtitleGroups.length;u++)h.addGroupId("text",t.subtitleGroups[u]+"_clone_"+n);return h}));i.push.apply(i,l),ll(e.audioTracks,r,o,n),ll(e.subtitleTracks,s,o,n)}}))}},e.loadSteeringManifest=function(t){var e,i=this,r=this.hls.config,s=r.loader;this.loader&&this.loader.destroy(),this.loader=new s(r);try{e=new self.URL(t)}catch(e){return this.enabled=!1,void this.log("Failed to parse Steering Manifest URI: "+t)}if("data:"!==e.protocol){var n=0|(this.hls.bandwidthEstimate||r.abrEwmaDefaultEstimate);e.searchParams.set("_HLS_pathway",this.pathwayId),e.searchParams.set("_HLS_throughput",""+n)}var a={responseType:"json",url:e.href},o=r.steeringManifestLoadPolicy.default,l=o.errorRetry||o.timeoutRetry||{},h={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:l.maxNumRetry||0,retryDelay:l.retryDelayMs||0,maxRetryDelay:l.maxRetryDelayMs||0},d={onSuccess:function(t,r,s,n){i.log('Loaded steering manifest: "'+e+'"');var a=t.data;if(1===a.VERSION){i.updated=performance.now(),i.timeToLoad=a.TTL;var o=a["RELOAD-URI"],l=a["PATHWAY-CLONES"],h=a["PATHWAY-PRIORITY"];if(o)try{i.uri=new self.URL(o,e).href}catch(t){return i.enabled=!1,void i.log("Failed to parse Steering Manifest RELOAD-URI: "+o)}i.scheduleRefresh(i.uri||s.url),l&&i.clonePathways(l);var d={steeringManifest:a,url:e.toString()};i.hls.trigger(D.STEERING_MANIFEST_LOADED,d),h&&i.updatePathwayPriority(h)}else i.log("Steering VERSION "+a.VERSION+" not supported!")},onError:function(t,e,r,s){if(i.log("Error loading steering manifest: "+t.code+" "+t.text+" ("+e.url+")"),i.stopLoad(),410===t.code)return i.enabled=!1,void i.log("Steering manifest "+e.url+" no longer available");var n=1e3*i.timeToLoad;if(429!==t.code)i.scheduleRefresh(i.uri||e.url,n);else{var a=i.loader;if("function"==typeof(null==a?void 0:a.getResponseHeader)){var o=a.getResponseHeader("Retry-After");o&&(n=1e3*parseFloat(o))}i.log("Steering manifest "+e.url+" rate limited")}},onTimeout:function(t,e,r){i.log("Timeout loading steering manifest ("+e.url+")"),i.scheduleRefresh(i.uri||e.url)}};this.log("Requesting steering manifest: "+e),this.loader.load(a,h,d)},e.scheduleRefresh=function(t,e){var i=this;void 0===e&&(e=1e3*this.timeToLoad),this.clearTimeout(),this.reloadTimer=self.setTimeout((function(){var e,r=null==(e=i.hls)?void 0:e.media;!r||r.ended?i.scheduleRefresh(t,1e3*i.timeToLoad):i.loadSteeringManifest(t)}),e)},t}();function ll(t,e,i,r){t&&Object.keys(e).forEach((function(s){var n=t.filter((function(t){return t.groupId===s})).map((function(t){var n=h({},t);return n.details=void 0,n.attrs=new B(n.attrs),n.url=n.attrs.URI=hl(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),n.groupId=n.attrs["GROUP-ID"]=e[s],n.attrs["PATHWAY-ID"]=r,n}));t.push.apply(t,n)}))}function hl(t,e,i,r){var s,n=r.HOST,a=r.PARAMS,o=r[i];e&&(s=null==o?void 0:o[e])&&(t=s);var l=new self.URL(t);return n&&!s&&(l.host=n),a&&Object.keys(a).sort().forEach((function(t){t&&l.searchParams.set(t,a[t])})),l.href}var dl=/^age:\s*[\d.]+\s*$/im,ul=function(){function t(t){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=t&&t.xhrSetup||null,this.stats=new $,this.retryDelay=0}var e=t.prototype;return e.destroy=function(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null},e.abortInternal=function(){var t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,4!==t.readyState&&(this.stats.aborted=!0,t.abort()))},e.abort=function(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)},e.load=function(t,e,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=t,this.config=e,this.callbacks=i,this.loadInternal()},e.loadInternal=function(){var t=this,e=this.config,i=this.context;if(e&&i){var r=this.loader=new self.XMLHttpRequest,s=this.stats;s.loading.first=0,s.loaded=0,s.aborted=!1;var n=this.xhrSetup;n?Promise.resolve().then((function(){if(t.loader===r&&!t.stats.aborted)return n(r,i.url)})).catch((function(e){if(t.loader===r&&!t.stats.aborted)return r.open("GET",i.url,!0),n(r,i.url)})).then((function(){t.loader!==r||t.stats.aborted||t.openAndSendXhr(r,i,e)})).catch((function(e){t.callbacks.onError({code:r.status,text:e.message},i,r,s)})):this.openAndSendXhr(r,i,e)}},e.openAndSendXhr=function(t,e,i){t.readyState||t.open("GET",e.url,!0);var r=e.headers,s=i.loadPolicy,n=s.maxTimeToFirstByteMs,a=s.maxLoadTimeMs;if(r)for(var o in r)t.setRequestHeader(o,r[o]);e.rangeEnd&&t.setRequestHeader("Range","bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=e.responseType,self.clearTimeout(this.requestTimeout),i.timeout=n&&R(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),t.send()},e.readystatechange=function(){var t=this.context,e=this.loader,i=this.stats;if(t&&e){var r=e.readyState,s=this.config;if(!i.aborted&&r>=2&&(0===i.loading.first&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),s.timeout!==s.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),s.timeout=s.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),4===r)){self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;var n=e.status,a="text"!==e.responseType;if(n>=200&&n<300&&(a&&e.response||null!==e.responseText)){i.loading.end=Math.max(self.performance.now(),i.loading.first);var o=a?e.response:e.responseText,l="arraybuffer"===e.responseType?o.byteLength:o.length;if(i.loaded=i.total=l,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first),!this.callbacks)return;var h=this.callbacks.onProgress;if(h&&h(i,t,o,e),!this.callbacks)return;var d={url:e.responseURL,data:o,code:n};this.callbacks.onSuccess(d,i,t,e)}else{var u=s.loadPolicy.errorRetry;$i(u,i.retry,!1,{url:t.url,data:void 0,code:n})?this.retry(u):(F.error(n+" while loading "+t.url),this.callbacks.onError({code:n,text:e.statusText},t,e,i))}}}},e.loadtimeout=function(){if(this.config){var t=this.config.loadPolicy.timeoutRetry;if($i(t,this.stats.retry,!0))this.retry(t);else{var e;F.warn("timeout while loading "+(null==(e=this.context)?void 0:e.url));var i=this.callbacks;i&&(this.abortInternal(),i.onTimeout(this.stats,this.context,this.loader))}}},e.retry=function(t){var e=this.context,i=this.stats;this.retryDelay=Ki(t,i.retry),i.retry++,F.warn((status?"HTTP Status "+status:"Timeout")+" while loading "+(null==e?void 0:e.url)+", retrying "+i.retry+"/"+t.maxNumRetry+" in "+this.retryDelay+"ms"),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)},e.loadprogress=function(t){var e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)},e.getCacheAge=function(){var t=null;if(this.loader&&dl.test(this.loader.getAllResponseHeaders())){var e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null}return t},e.getResponseHeader=function(t){return this.loader&&new RegExp("^"+t+":\\s*[\\d.]+\\s*$","im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(t):null},t}();function cl(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(t){}return!1}var fl=/(\d+)-(\d+)\/(\d+)/,gl=function(){function t(t){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=t.fetchSetup||yl,this.controller=new self.AbortController,this.stats=new $}var e=t.prototype;return e.destroy=function(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null},e.abortInternal=function(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())},e.abort=function(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)},e.load=function(t,e,i){var r=this,s=this.stats;if(s.loading.start)throw new Error("Loader can only be used once.");s.loading.start=self.performance.now();var n=ml(t,this.controller.signal),a=i.onProgress,o="arraybuffer"===t.responseType,l=o?"byteLength":"length",h=e.loadPolicy,d=h.maxTimeToFirstByteMs,u=h.maxLoadTimeMs;this.context=t,this.config=e,this.callbacks=i,this.request=this.fetchSetup(t,n),self.clearTimeout(this.requestTimeout),e.timeout=d&&R(d)?d:u,this.requestTimeout=self.setTimeout((function(){r.abortInternal(),i.onTimeout(s,t,r.response)}),e.timeout),self.fetch(this.request).then((function(n){r.response=r.loader=n;var l=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(r.requestTimeout),e.timeout=u,r.requestTimeout=self.setTimeout((function(){r.abortInternal(),i.onTimeout(s,t,r.response)}),u-(l-s.loading.start)),!n.ok){var h=n.status,d=n.statusText;throw new Tl(d||"fetch, bad network response",h,n)}return s.loading.first=l,s.total=vl(n.headers)||s.total,a&&R(e.highWaterMark)?r.loadProgressively(n,s,t,e.highWaterMark,a):o?n.arrayBuffer():"json"===t.responseType?n.json():n.text()})).then((function(n){var o=r.response;if(!o)throw new Error("loader destroyed");self.clearTimeout(r.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);var h=n[l];h&&(s.loaded=s.total=h);var d={url:o.url,data:n,code:o.status};a&&!R(e.highWaterMark)&&a(s,t,n,o),i.onSuccess(d,s,t,o)})).catch((function(e){if(self.clearTimeout(r.requestTimeout),!s.aborted){var n=e&&e.code||0,a=e?e.message:null;i.onError({code:n,text:a},t,e?e.details:null,s)}}))},e.getCacheAge=function(){var t=null;if(this.response){var e=this.response.headers.get("age");t=e?parseFloat(e):null}return t},e.getResponseHeader=function(t){return this.response?this.response.headers.get(t):null},e.loadProgressively=function(t,e,i,r,s){void 0===r&&(r=0);var n=new Zr,a=t.body.getReader();return function o(){return a.read().then((function(a){if(a.done)return n.dataLength&&s(e,i,n.flush(),t),Promise.resolve(new ArrayBuffer(0));var l=a.value,h=l.length;return e.loaded+=h,h<r||n.dataLength?(n.push(l),n.dataLength>=r&&s(e,i,n.flush(),t)):s(e,i,l,t),o()})).catch((function(){return Promise.reject()}))}()},t}();function ml(t,e){var i={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(h({},t.headers))};return t.rangeEnd&&i.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1)),i}function pl(t){var e=fl.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}function vl(t){var e=t.get("Content-Range");if(e){var i=pl(e);if(R(i))return i}var r=t.get("Content-Length");if(r)return parseInt(r)}function yl(t,e){return new self.Request(t.url,e)}var El,Tl=function(t){function e(e,i,r){var s;return(s=t.call(this,e)||this).code=void 0,s.details=void 0,s.code=i,s.details=r,s}return d(e,t),e}(p(Error)),Sl=/\s/,Al={newCue:function(t,e,i,r){for(var s,n,a,o,l,h=[],d=self.VTTCue||self.TextTrackCue,u=0;u<r.rows.length;u++)if(a=!0,o=0,l="",!(s=r.rows[u]).isEmpty()){for(var c,f=0;f<s.chars.length;f++)Sl.test(s.chars[f].uchar)&&a?o++:(l+=s.chars[f].uchar,a=!1);s.cueStartTime=e,e===i&&(i+=1e-4),o>=16?o--:o++;var g=ba(l.trim()),m=_a(e,i,g);null!=t&&null!=(c=t.cues)&&c.getCueById(m)||((n=new d(e,i,g)).id=m,n.line=u+1,n.align="left",n.position=10+Math.min(80,10*Math.floor(8*o/32)),h.push(n))}return t&&h.length&&(h.sort((function(t,e){return"auto"===t.line||"auto"===e.line?0:t.line>8&&e.line>8?e.line-t.line:t.line-e.line})),h.forEach((function(e){return ii(t,e)}))),h}},Ll=r(r({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:6e7,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:ul,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Sr,bufferController:jn,capLevelController:to,errorController:tr,fpsController:eo,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:dt,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!0,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},Rl()),{},{subtitleStreamController:Hn,subtitleTrackController:Vn,timelineController:Xa,audioStreamController:Bn,audioTrackController:Gn,emeController:ro,cmcdController:nl,contentSteeringController:ol});function Rl(){return{cueHandler:Al,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 bl(t,e){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==e.liveMaxLatencyDurationCount&&(void 0===e.liveSyncDurationCount||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==e.liveMaxLatencyDuration&&(void 0===e.liveSyncDuration||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');var i=kl(t),s=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((function(t){var r=("level"===t?"playlist":t)+"LoadPolicy",n=void 0===e[r],a=[];s.forEach((function(s){var o=t+"Loading"+s,l=e[o];if(void 0!==l&&n){a.push(o);var h=i[r].default;switch(e[r]={default:h},s){case"TimeOut":h.maxLoadTimeMs=l,h.maxTimeToFirstByteMs=l;break;case"MaxRetry":h.errorRetry.maxNumRetry=l,h.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":h.errorRetry.retryDelayMs=l,h.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":h.errorRetry.maxRetryDelayMs=l,h.timeoutRetry.maxRetryDelayMs=l}}})),a.length&&F.warn('hls.js config: "'+a.join('", "')+'" setting(s) are deprecated, use "'+r+'": '+JSON.stringify(e[r]))})),r(r({},i),e)}function kl(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(kl):Object.keys(t).reduce((function(e,i){return e[i]=kl(t[i]),e}),{}):t}function Dl(t){var e=t.loader;e!==gl&&e!==ul?(F.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1):cl()&&(t.loader=gl,t.progressive=!0,t.enableSoftwareAES=!0,F.log("[config]: Progressive streaming enabled, using FetchLoader"))}var Il=function(t){function e(e,i){var r;return(r=t.call(this,e,"[level-controller]")||this)._levels=[],r._firstLevel=-1,r._maxAutoLevel=-1,r._startLevel=void 0,r.currentLevel=null,r.currentLevelIndex=-1,r.manualLevelIndex=-1,r.steering=void 0,r.onParsedComplete=void 0,r.steering=i,r._registerListeners(),r}d(e,t);var i=e.prototype;return i._registerListeners=function(){var t=this.hls;t.on(D.MANIFEST_LOADING,this.onManifestLoading,this),t.on(D.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(D.LEVEL_LOADED,this.onLevelLoaded,this),t.on(D.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(D.FRAG_BUFFERED,this.onFragBuffered,this),t.on(D.ERROR,this.onError,this)},i._unregisterListeners=function(){var t=this.hls;t.off(D.MANIFEST_LOADING,this.onManifestLoading,this),t.off(D.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(D.LEVEL_LOADED,this.onLevelLoaded,this),t.off(D.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(D.FRAG_BUFFERED,this.onFragBuffered,this),t.off(D.ERROR,this.onError,this)},i.destroy=function(){this._unregisterListeners(),this.steering=null,this.resetLevels(),t.prototype.destroy.call(this)},i.stopLoad=function(){this._levels.forEach((function(t){t.loadError=0,t.fragmentError=0})),t.prototype.stopLoad.call(this)},i.resetLevels=function(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1},i.onManifestLoading=function(t,e){this.resetLevels()},i.onManifestLoaded=function(t,e){var i=this.hls.config.preferManagedMediaSource,r=[],s={},n={},a=!1,o=!1,l=!1;e.levels.forEach((function(t){var e,h,d=t.attrs,u=t.audioCodec,c=t.videoCodec;-1!==(null==(e=u)?void 0:e.indexOf("mp4a.40.34"))&&(El||(El=/chrome|firefox/i.test(navigator.userAgent)),El&&(t.audioCodec=u=void 0)),u&&(t.audioCodec=u=xe(u,i)),0===(null==(h=c)?void 0:h.indexOf("avc1"))&&(c=t.videoCodec=Oe(c));var f=t.width,g=t.height,m=t.unknownCodecs;if(a||(a=!(!f||!g)),o||(o=!!c),l||(l=!!u),!(null!=m&&m.length||u&&!be(u,"audio",i)||c&&!be(c,"video",i))){var p=d.CODECS,v=d["FRAME-RATE"],y=d["HDCP-LEVEL"],E=d["PATHWAY-ID"],T=d.RESOLUTION,S=d["VIDEO-RANGE"],A=(E||".")+"-"+t.bitrate+"-"+T+"-"+v+"-"+p+"-"+S+"-"+y;if(s[A])if(s[A].uri===t.url||t.attrs["PATHWAY-ID"])s[A].addGroupId("audio",d.AUDIO),s[A].addGroupId("text",d.SUBTITLES);else{var L=n[A]+=1;t.attrs["PATHWAY-ID"]=new Array(L+1).join(".");var R=new Ri(t);s[A]=R,r.push(R)}else{var b=new Ri(t);s[A]=b,n[A]=1,r.push(b)}}})),this.filterAndSortMediaOptions(r,e,a,o,l)},i.filterAndSortMediaOptions=function(t,e,i,r,s){var n=this,a=[],o=[],l=t;if((i||r)&&s&&(l=l.filter((function(t){var e=t.videoCodec,i=t.videoRange,r=t.width,s=t.height;return(!!e||!(!r||!s))&&Ti(i)}))),0!==l.length){if(e.audioTracks){var h=this.hls.config.preferManagedMediaSource;wl(a=e.audioTracks.filter((function(t){return!t.audioCodec||be(t.audioCodec,"audio",h)})))}e.subtitles&&wl(o=e.subtitles);var d=l.slice(0);l.sort((function(t,e){if(t.attrs["HDCP-LEVEL"]!==e.attrs["HDCP-LEVEL"])return(t.attrs["HDCP-LEVEL"]||"")>(e.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&t.height!==e.height)return t.height-e.height;if(t.frameRate!==e.frameRate)return t.frameRate-e.frameRate;if(t.videoRange!==e.videoRange)return Ei.indexOf(t.videoRange)-Ei.indexOf(e.videoRange);if(t.videoCodec!==e.videoCodec){var r=Ie(t.videoCodec),s=Ie(e.videoCodec);if(r!==s)return s-r}if(t.uri===e.uri&&t.codecSet!==e.codecSet){var n=we(t.codecSet),a=we(e.codecSet);if(n!==a)return a-n}return t.averageBitrate!==e.averageBitrate?t.averageBitrate-e.averageBitrate:0}));var u=d[0];if(this.steering&&(l=this.steering.filterParsedLevels(l)).length!==d.length)for(var c=0;c<d.length;c++)if(d[c].pathwayId===l[0].pathwayId){u=d[c];break}this._levels=l;for(var f=0;f<l.length;f++)if(l[f]===u){var g;this._firstLevel=f;var m=u.bitrate,p=this.hls.bandwidthEstimate;if(this.log("manifest loaded, "+l.length+" level(s) found, first bitrate: "+m),void 0===(null==(g=this.hls.userConfig)?void 0:g.abrEwmaDefaultEstimate)){var v=Math.min(m,this.hls.config.abrEwmaDefaultEstimateMax);v>p&&p===Ll.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=v)}break}var y=s&&!r,E={levels:l,audioTracks:a,subtitleTracks:o,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:s,video:r,altAudio:!y&&a.some((function(t){return!!t.url}))};this.hls.trigger(D.MANIFEST_PARSED,E),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}else Promise.resolve().then((function(){if(n.hls){e.levels.length&&n.warn("One or more CODECS in variant not supported: "+JSON.stringify(e.levels[0].attrs));var t=new Error("no level with compatible codecs found in manifest");n.hls.trigger(D.ERROR,{type:I.MEDIA_ERROR,details:w.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:t,reason:t.message})}}))},i.onError=function(t,e){!e.fatal&&e.context&&e.context.type===ze.LEVEL&&e.context.level===this.level&&this.checkRetry(e)},i.onFragBuffered=function(t,e){var i=e.frag;if(void 0!==i&&i.type===Qe.MAIN){var r=i.elementaryStreams;if(!Object.keys(r).some((function(t){return!!r[t]})))return;var s=this._levels[i.level];null!=s&&s.loadError&&(this.log("Resetting level error count of "+s.loadError+" on frag buffered"),s.loadError=0)}},i.onLevelLoaded=function(t,e){var i,r,s=e.level,n=e.details,a=this._levels[s];if(!a)return this.warn("Invalid level index "+s),void(null!=(r=e.deliveryDirectives)&&r.skip&&(n.deltaUpdateFailed=!0));s===this.currentLevelIndex?(0===a.fragmentError&&(a.loadError=0),this.playlistLoaded(s,e,a.details)):null!=(i=e.deliveryDirectives)&&i.skip&&(n.deltaUpdateFailed=!0)},i.loadPlaylist=function(e){t.prototype.loadPlaylist.call(this);var i=this.currentLevelIndex,r=this.currentLevel;if(r&&this.shouldLoadPlaylist(r)){var s=r.uri;if(e)try{s=e.addDirectives(s)}catch(t){this.warn("Could not construct new URL with HLS Delivery Directives: "+t)}var n=r.attrs["PATHWAY-ID"];this.log("Loading level index "+i+(void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:"")+" with"+(n?" Pathway "+n:"")+" "+s),this.clearTimer(),this.hls.trigger(D.LEVEL_LOADING,{url:s,level:i,pathwayId:r.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}},i.removeLevel=function(t){var e,i=this,r=this._levels.filter((function(e,r){return r!==t||(i.steering&&i.steering.removeLevel(e),e===i.currentLevel&&(i.currentLevel=null,i.currentLevelIndex=-1,e.details&&e.details.fragments.forEach((function(t){return t.level=-1}))),!1)}));Ui(r),this._levels=r,this.currentLevelIndex>-1&&null!=(e=this.currentLevel)&&e.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(D.LEVELS_UPDATED,{levels:r})},i.onLevelsUpdated=function(t,e){var i=e.levels;this._levels=i},i.checkMaxAutoUpdated=function(){var t=this.hls,e=t.autoLevelCapping,i=t.maxAutoLevel,r=t.maxHdcpLevel;this._maxAutoLevel!==i&&(this._maxAutoLevel=i,this.hls.trigger(D.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:i,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:r}))},o(e,[{key:"levels",get:function(){return 0===this._levels.length?null:this._levels}},{key:"level",get:function(){return this.currentLevelIndex},set:function(t){var e=this._levels;if(0!==e.length){if(t<0||t>=e.length){var i=new Error("invalid level idx"),r=t<0;if(this.hls.trigger(D.ERROR,{type:I.OTHER_ERROR,details:w.LEVEL_SWITCH_ERROR,level:t,fatal:r,error:i,reason:i.message}),r)return;t=Math.min(t,e.length-1)}var s=this.currentLevelIndex,n=this.currentLevel,a=n?n.attrs["PATHWAY-ID"]:void 0,o=e[t],l=o.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=o,s!==t||!o.details||!n||a!==l){this.log("Switching to level "+t+" ("+(o.height?o.height+"p ":"")+(o.videoRange?o.videoRange+" ":"")+(o.codecSet?o.codecSet+" ":"")+"@"+o.bitrate+")"+(l?" with Pathway "+l:"")+" from level "+s+(a?" with Pathway "+a:""));var h={level:t,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(D.LEVEL_SWITCHING,h);var d=o.details;if(!d||d.live){var u=this.switchParams(o.uri,null==n?void 0:n.details,d);this.loadPlaylist(u)}}}}},{key:"manualLevel",get:function(){return this.manualLevelIndex},set:function(t){this.manualLevelIndex=t,void 0===this._startLevel&&(this._startLevel=t),-1!==t&&(this.level=t)}},{key:"firstLevel",get:function(){return this._firstLevel},set:function(t){this._firstLevel=t}},{key:"startLevel",get:function(){if(void 0===this._startLevel){var t=this.hls.config.startLevel;return void 0!==t?t:this.hls.firstAutoLevel}return this._startLevel},set:function(t){this._startLevel=t}},{key:"nextLoadLevel",get:function(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},set:function(t){this.level=t,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=t)}}]),e}(er);function wl(t){var e={};t.forEach((function(t){var i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++}))}var Cl=function(){function t(t){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=t}var e=t.prototype;return e.abort=function(t){for(var e in this.keyUriToKeyInfo){var i=this.keyUriToKeyInfo[e].loader;if(i){var r;if(t&&t!==(null==(r=i.context)?void 0:r.frag.type))return;i.abort()}}},e.detach=function(){for(var t in this.keyUriToKeyInfo){var e=this.keyUriToKeyInfo[t];(e.mediaKeySessionContext||e.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[t]}},e.destroy=function(){for(var t in this.detach(),this.keyUriToKeyInfo){var e=this.keyUriToKeyInfo[t].loader;e&&e.destroy()}this.keyUriToKeyInfo={}},e.createKeyLoadError=function(t,e,i,r,s){return void 0===e&&(e=w.KEY_LOAD_ERROR),new $r({type:I.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:s,error:i,networkDetails:r})},e.loadClear=function(t,e){var i=this;if(this.emeController&&this.config.emeEnabled)for(var r=t.sn,s=t.cc,n=function(){var t=e[a];if(s<=t.cc&&("initSegment"===r||"initSegment"===t.sn||r<t.sn))return i.emeController.selectKeySystemFormat(t).then((function(e){t.setKeyFormat(e)})),1},a=0;a<e.length&&!n();a++);},e.load=function(t){var e=this;return!t.decryptdata&&t.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(t).then((function(i){return e.loadInternal(t,i)})):this.loadInternal(t)},e.loadInternal=function(t,e){var i,r;e&&t.setKeyFormat(e);var s=t.decryptdata;if(!s){var n=new Error(e?"Expected frag.decryptdata to be defined after setting format "+e:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(t,w.KEY_LOAD_ERROR,n))}var a=s.uri;if(!a)return Promise.reject(this.createKeyLoadError(t,w.KEY_LOAD_ERROR,new Error('Invalid key URI: "'+a+'"')));var o,l=this.keyUriToKeyInfo[a];if(null!=(i=l)&&i.decryptdata.key)return s.key=l.decryptdata.key,Promise.resolve({frag:t,keyInfo:l});if(null!=(r=l)&&r.keyLoadPromise)switch(null==(o=l.mediaKeySessionContext)?void 0:o.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return l.keyLoadPromise.then((function(e){return s.key=e.keyInfo.decryptdata.key,{frag:t,keyInfo:l}}))}switch(l=this.keyUriToKeyInfo[a]={decryptdata:s,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},s.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===s.keyFormat?this.loadKeyHTTP(l,t):this.loadKeyEME(l,t);case"AES-128":return this.loadKeyHTTP(l,t);default:return Promise.reject(this.createKeyLoadError(t,w.KEY_LOAD_ERROR,new Error('Key supplied with unsupported METHOD: "'+s.method+'"')))}},e.loadKeyEME=function(t,e){var i={frag:e,keyInfo:t};if(this.emeController&&this.config.emeEnabled){var r=this.emeController.loadKey(i);if(r)return(t.keyLoadPromise=r.then((function(e){return t.mediaKeySessionContext=e,i}))).catch((function(e){throw t.keyLoadPromise=null,e}))}return Promise.resolve(i)},e.loadKeyHTTP=function(t,e){var i=this,s=this.config,n=new(0,s.loader)(s);return e.keyLoader=t.loader=n,t.keyLoadPromise=new Promise((function(a,o){var l={keyInfo:t,frag:e,responseType:"arraybuffer",url:t.decryptdata.uri},h=s.keyLoadPolicy.default,d={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:function(t,e,r,s){var n=r.frag,l=r.keyInfo,h=r.url;if(!n.decryptdata||l!==i.keyUriToKeyInfo[h])return o(i.createKeyLoadError(n,w.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),s));l.decryptdata.key=n.decryptdata.key=new Uint8Array(t.data),n.keyLoader=null,l.loader=null,a({frag:n,keyInfo:l})},onError:function(t,s,n,a){i.resetLoader(s),o(i.createKeyLoadError(e,w.KEY_LOAD_ERROR,new Error("HTTP Error "+t.code+" loading key "+t.text),n,r({url:l.url,data:void 0},t)))},onTimeout:function(t,r,s){i.resetLoader(r),o(i.createKeyLoadError(e,w.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),s))},onAbort:function(t,r,s){i.resetLoader(r),o(i.createKeyLoadError(e,w.INTERNAL_ABORTED,new Error("key loading aborted"),s))}};n.load(l,d,u)}))},e.resetLoader=function(t){var e=t.frag,i=t.keyInfo,r=t.url,s=i.loader;e.keyLoader===s&&(e.keyLoader=null,i.loader=null),delete this.keyUriToKeyInfo[r],s&&s.destroy()},t}();function _l(){return self.SourceBuffer||self.WebKitSourceBuffer}function Pl(){if(!Se())return!1;var t=_l();return!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove}function xl(){if(!Pl())return!1;var t=Se();return"function"==typeof(null==t?void 0:t.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some((function(e){return t.isTypeSupported(De(e,"video"))}))||["mp4a.40.2","fLaC"].some((function(e){return t.isTypeSupported(De(e,"audio"))})))}function Ml(){var t,e=_l();return"function"==typeof(null==e||null==(t=e.prototype)?void 0:t.changeType)}var Ol=250,Fl=2,Nl=.1,Ul=.05,Bl=function(){function t(t,e,i,r){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=t,this.media=e,this.fragmentTracker=i,this.hls=r}var e=t.prototype;return e.destroy=function(){this.media=null,this.hls=this.fragmentTracker=null},e.poll=function(t,e){var i=this.config,r=this.media,s=this.stalled;if(null!==r){var n=r.currentTime,a=r.seeking,o=this.seeking&&!a,l=!this.seeking&&a;if(this.seeking=a,n===t)if(l||o)this.stalled=null;else if(r.paused&&!a||r.ended||0===r.playbackRate||!Ir.getBuffered(r).length)this.nudgeRetry=0;else{var h=Ir.bufferInfo(r,n,0),d=h.nextStart||0;if(a){var u=h.len>Fl,c=!d||e&&e.start<=n||d-n>Fl&&!this.fragmentTracker.getPartialFragment(n);if(u||c)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var f;if(!(h.len>0||d))return;var g=Math.max(d,h.start||0)-n,m=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,p=(null==m||null==(f=m.details)?void 0:f.live)?2*m.details.targetduration:Fl,v=this.fragmentTracker.getPartialFragment(n);if(g>0&&(g<=p||v))return void(r.paused||this._trySkipBufferHole(v))}var y=self.performance.now();if(null!==s){var E=y-s;if(a||!(E>=Ol)||(this._reportStall(h),this.media)){var T=Ir.bufferInfo(r,n,i.maxBufferHole);this._tryFixBufferStall(T,E)}}else this.stalled=y}else if(this.moved=!0,a||(this.nudgeRetry=0),null!==s){if(this.stallReported){var S=self.performance.now()-s;F.warn("playback not stuck anymore @"+n+", after "+Math.round(S)+"ms"),this.stallReported=!1}this.stalled=null}}},e._tryFixBufferStall=function(t,e){var i=this.config,r=this.fragmentTracker,s=this.media;if(null!==s){var n=s.currentTime,a=r.getPartialFragment(n);if(a&&(this._trySkipBufferHole(a)||!this.media))return;(t.len>i.maxBufferHole||t.nextStart&&t.nextStart-n<i.maxBufferHole)&&e>1e3*i.highBufferWatchdogPeriod&&(F.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}},e._reportStall=function(t){var e=this.hls,i=this.media;if(!this.stallReported&&i){this.stallReported=!0;var r=new Error("Playback stalling at @"+i.currentTime+" due to low buffer ("+JSON.stringify(t)+")");F.warn(r.message),e.trigger(D.ERROR,{type:I.MEDIA_ERROR,details:w.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:t.len})}},e._trySkipBufferHole=function(t){var e=this.config,i=this.hls,r=this.media;if(null===r)return 0;var s=r.currentTime,n=Ir.bufferInfo(r,s,0),a=s<n.start?n.start:n.nextStart;if(a){var o=n.len<=e.maxBufferHole,l=n.len>0&&n.len<1&&r.readyState<3,h=a-s;if(h>0&&(o||l)){if(h>e.maxBufferHole){var d=this.fragmentTracker,u=!1;if(0===s){var c=d.getAppendedFrag(0,Qe.MAIN);c&&a<c.end&&(u=!0)}if(!u){var f=t||d.getAppendedFrag(s,Qe.MAIN);if(f){for(var g=!1,m=f.end;m<a;){var p=d.getPartialFragment(m);if(!p){g=!0;break}m+=p.duration}if(g)return 0}}}var v=Math.max(a+Ul,s+Nl);if(F.warn("skipping hole, adjusting currentTime from "+s+" to "+v),this.moved=!0,this.stalled=null,r.currentTime=v,t&&!t.gap){var y=new Error("fragment loaded with buffer holes, seeking from "+s+" to "+v);i.trigger(D.ERROR,{type:I.MEDIA_ERROR,details:w.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:y,reason:y.message,frag:t})}return v}}return 0},e._tryNudgeBuffer=function(){var t=this.config,e=this.hls,i=this.media,r=this.nudgeRetry;if(null!==i){var s=i.currentTime;if(this.nudgeRetry++,r<t.nudgeMaxRetry){var n=s+(r+1)*t.nudgeOffset,a=new Error("Nudging 'currentTime' from "+s+" to "+n);F.warn(a.message),i.currentTime=n,e.trigger(D.ERROR,{type:I.MEDIA_ERROR,details:w.BUFFER_NUDGE_ON_STALL,error:a,fatal:!1})}else{var o=new Error("Playhead still not moving while enough data buffered @"+s+" after "+t.nudgeMaxRetry+" nudges");F.error(o.message),e.trigger(D.ERROR,{type:I.MEDIA_ERROR,details:w.BUFFER_STALLED_ERROR,error:o,fatal:!0})}}},t}(),Gl=100,Kl=function(t){function e(e,i,r){var s;return(s=t.call(this,e,i,r,"[stream-controller]",Qe.MAIN)||this).audioCodecSwap=!1,s.gapController=null,s.level=-1,s._forceStartLoad=!1,s.altAudio=!1,s.audioOnly=!1,s.fragPlaying=null,s.onvplaying=null,s.onvseeked=null,s.fragLastKbps=0,s.couldBacktrack=!1,s.backtrackFragment=null,s.audioCodecSwitch=!1,s.videoBuffer=null,s._registerListeners(),s}d(e,t);var i=e.prototype;return i._registerListeners=function(){var t=this.hls;t.on(D.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(D.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(D.MANIFEST_LOADING,this.onManifestLoading,this),t.on(D.MANIFEST_PARSED,this.onManifestParsed,this),t.on(D.LEVEL_LOADING,this.onLevelLoading,this),t.on(D.LEVEL_LOADED,this.onLevelLoaded,this),t.on(D.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(D.ERROR,this.onError,this),t.on(D.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(D.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(D.BUFFER_CREATED,this.onBufferCreated,this),t.on(D.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(D.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(D.FRAG_BUFFERED,this.onFragBuffered,this)},i._unregisterListeners=function(){var t=this.hls;t.off(D.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(D.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(D.MANIFEST_LOADING,this.onManifestLoading,this),t.off(D.MANIFEST_PARSED,this.onManifestParsed,this),t.off(D.LEVEL_LOADED,this.onLevelLoaded,this),t.off(D.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(D.ERROR,this.onError,this),t.off(D.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(D.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(D.BUFFER_CREATED,this.onBufferCreated,this),t.off(D.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(D.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(D.FRAG_BUFFERED,this.onFragBuffered,this)},i.onHandlerDestroying=function(){this._unregisterListeners(),t.prototype.onHandlerDestroying.call(this)},i.startLoad=function(t){if(this.levels){var e=this.lastCurrentTime,i=this.hls;if(this.stopLoad(),this.setInterval(Gl),this.level=-1,!this.startFragRequested){var r=i.startLevel;-1===r&&(i.config.testBandwidth&&this.levels.length>1?(r=0,this.bitrateTest=!0):r=i.firstAutoLevel),i.nextLoadLevel=r,this.level=i.loadLevel,this.loadedmetadata=!1}e>0&&-1===t&&(this.log("Override startPosition with lastCurrentTime @"+e.toFixed(3)),t=e),this.state=Qr.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}else this._forceStartLoad=!0,this.state=Qr.STOPPED},i.stopLoad=function(){this._forceStartLoad=!1,t.prototype.stopLoad.call(this)},i.doTick=function(){switch(this.state){case Qr.WAITING_LEVEL:var t=this.levels,e=this.level,i=null==t?void 0:t[e],r=null==i?void 0:i.details;if(r&&(!r.live||this.levelLastLoaded===i)){if(this.waitForCdnTuneIn(r))break;this.state=Qr.IDLE;break}if(this.hls.nextLoadLevel!==this.level){this.state=Qr.IDLE;break}break;case Qr.FRAG_LOADING_WAITING_RETRY:var s,n=self.performance.now(),a=this.retryDate;if(!a||n>=a||null!=(s=this.media)&&s.seeking){var o=this.levels,l=this.level,h=null==o?void 0:o[l];this.resetStartWhenNotLoaded(h||null),this.state=Qr.IDLE}}this.state===Qr.IDLE&&this.doTickIdle(),this.onTickEnd()},i.onTickEnd=function(){t.prototype.onTickEnd.call(this),this.checkBuffer(),this.checkFragmentChanged()},i.doTickIdle=function(){var t=this.hls,e=this.levelLastLoaded,i=this.levels,r=this.media;if(null!==e&&(r||!this.startFragRequested&&t.config.startFragPrefetch)&&(!this.altAudio||!this.audioOnly)){var s=t.nextLoadLevel;if(null!=i&&i[s]){var n=i[s],a=this.getMainFwdBufferInfo();if(null!==a){var o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){var l={};return this.altAudio&&(l.type="video"),this.hls.trigger(D.BUFFER_EOS,l),void(this.state=Qr.ENDED)}t.loadLevel!==s&&-1===t.manualLevel&&this.log("Adapting to level "+s+" from level "+this.level),this.level=t.nextLoadLevel=s;var h=n.details;if(!h||this.state===Qr.WAITING_LEVEL||h.live&&this.levelLastLoaded!==n)return this.level=s,void(this.state=Qr.WAITING_LEVEL);var d=a.len,u=this.getMaxBufferLength(n.maxBitrate);if(!(d>=u)){this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);var c=this.backtrackFragment?this.backtrackFragment.start:a.end,f=this.getNextFragment(c,h);if(this.couldBacktrack&&!this.fragPrevious&&f&&"initSegment"!==f.sn&&this.fragmentTracker.getState(f)!==Lr.OK){var g,m=(null!=(g=this.backtrackFragment)?g:f).sn-h.startSN,p=h.fragments[m-1];p&&f.cc===p.cc&&(f=p,this.fragmentTracker.removeFragment(p))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,c)){if(!f.gap){var v=this.audioOnly&&!this.altAudio?V.AUDIO:V.VIDEO,y=(v===V.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;y&&this.afterBufferFlushed(y,v,Qe.MAIN)}f=this.getNextFragmentLoopLoading(f,h,a,Qe.MAIN,u)}f&&(!f.initSegment||f.initSegment.data||this.bitrateTest||(f=f.initSegment),this.loadFragment(f,n,c))}}}}},i.loadFragment=function(e,i,r){var s=this.fragmentTracker.getState(e);this.fragCurrent=e,s===Lr.NOT_LOADED||s===Lr.PARTIAL?"initSegment"===e.sn?this._loadInitSegment(e,i):this.bitrateTest?(this.log("Fragment "+e.sn+" of level "+e.level+" is being downloaded to test bitrate and will not be buffered"),this._loadBitrateTestFrag(e,i)):(this.startFragRequested=!0,t.prototype.loadFragment.call(this,e,i,r)):this.clearTrackerIfNeeded(e)},i.getBufferedFrag=function(t){return this.fragmentTracker.getBufferedFrag(t,Qe.MAIN)},i.followingBufferedFrag=function(t){return t?this.getBufferedFrag(t.end+.5):null},i.immediateLevelSwitch=function(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)},i.nextLevelSwitch=function(){var t=this.levels,e=this.media;if(null!=e&&e.readyState){var i,r=this.getAppendedFrag(e.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);var s=this.getLevelDetails();if(null!=s&&s.live){var n=this.getMainFwdBufferInfo();if(!n||n.len<2*s.targetduration)return}if(!e.paused&&t){var a=t[this.hls.nextLoadLevel],o=this.fragLastKbps;i=o&&this.fragCurrent?this.fragCurrent.duration*a.maxBitrate/(1e3*o)+1:0}else i=0;var l=this.getBufferedFrag(e.currentTime+i);if(l){var h=this.followingBufferedFrag(l);if(h){this.abortCurrentFrag();var d=h.maxStartPTS?h.maxStartPTS:h.start,u=h.duration,c=Math.max(l.end,d+Math.min(Math.max(u-this.config.maxFragLookUpTolerance,u*(this.couldBacktrack?.5:.125)),u*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(c,Number.POSITIVE_INFINITY)}}}},i.abortCurrentFrag=function(){var t=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,t&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.state){case Qr.KEY_LOADING:case Qr.FRAG_LOADING:case Qr.FRAG_LOADING_WAITING_RETRY:case Qr.PARSING:case Qr.PARSED:this.state=Qr.IDLE}this.nextLoadPosition=this.getLoadPosition()},i.flushMainBuffer=function(e,i){t.prototype.flushMainBuffer.call(this,e,i,this.altAudio?"video":null)},i.onMediaAttached=function(e,i){t.prototype.onMediaAttached.call(this,e,i);var r=i.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),r.addEventListener("playing",this.onvplaying),r.addEventListener("seeked",this.onvseeked),this.gapController=new Bl(this.config,r,this.fragmentTracker,this.hls)},i.onMediaDetaching=function(){var e=this.media;e&&this.onvplaying&&this.onvseeked&&(e.removeEventListener("playing",this.onvplaying),e.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),t.prototype.onMediaDetaching.call(this)},i.onMediaPlaying=function(){this.tick()},i.onMediaSeeked=function(){var t=this.media,e=t?t.currentTime:null;R(e)&&this.log("Media seeked to "+e.toFixed(3));var i=this.getMainFwdBufferInfo();null!==i&&0!==i.len?this.tick():this.warn('Main forward buffer length on "seeked" event '+(i?i.len:"empty")+")")},i.onManifestLoading=function(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(D.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=this.fragLastKbps=0,this.levels=this.fragPlaying=this.backtrackFragment=this.levelLastLoaded=null,this.altAudio=this.audioOnly=this.startFragRequested=!1},i.onManifestParsed=function(t,e){var i=!1,r=!1;e.levels.forEach((function(t){var e=t.audioCodec;e&&(i=i||-1!==e.indexOf("mp4a.40.2"),r=r||-1!==e.indexOf("mp4a.40.5"))})),this.audioCodecSwitch=i&&r&&!Ml(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startFragRequested=!1},i.onLevelLoading=function(t,e){var i=this.levels;if(i&&this.state===Qr.IDLE){var r=i[e.level];(!r.details||r.details.live&&this.levelLastLoaded!==r||this.waitForCdnTuneIn(r.details))&&(this.state=Qr.WAITING_LEVEL)}},i.onLevelLoaded=function(t,e){var i,r=this.levels,s=e.level,n=e.details,a=n.totalduration;if(r){this.log("Level "+s+" loaded ["+n.startSN+","+n.endSN+"]"+(n.lastPartSn?"[part-"+n.lastPartSn+"-"+n.lastPartIndex+"]":"")+", cc ["+n.startCC+", "+n.endCC+"] duration:"+a);var o=r[s],l=this.fragCurrent;!l||this.state!==Qr.FRAG_LOADING&&this.state!==Qr.FRAG_LOADING_WAITING_RETRY||l.level!==e.level&&l.loader&&this.abortCurrentFrag();var h=0;if(n.live||null!=(i=o.details)&&i.live){var d;if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;h=this.alignPlaylists(n,o.details,null==(d=this.levelLastLoaded)?void 0:d.details)}if(o.details=n,this.levelLastLoaded=o,this.hls.trigger(D.LEVEL_UPDATED,{details:n,level:s}),this.state===Qr.WAITING_LEVEL){if(this.waitForCdnTuneIn(n))return;this.state=Qr.IDLE}this.startFragRequested?n.live&&this.synchronizeToLiveEdge(n):this.setStartPosition(n,h),this.tick()}else this.warn("Levels were reset while loading level "+s)},i._handleFragmentLoadProgress=function(t){var e,i=t.frag,r=t.part,s=t.payload,n=this.levels;if(n){var a=n[i.level],o=a.details;if(!o)return this.warn("Dropping fragment "+i.sn+" of level "+i.level+" after level details were reset"),void this.fragmentTracker.removeFragment(i);var l=a.videoCodec,h=o.PTSKnown||!o.live,d=null==(e=i.initSegment)?void 0:e.data,u=this._getAudioCodec(a),c=this.transmuxer=this.transmuxer||new Mn(this.hls,Qe.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=r?r.index:-1,g=-1!==f,m=new wr(i.level,i.sn,i.stats.chunkCount,s.byteLength,f,g),p=this.initPTS[i.cc];c.push(s,d,u,l,i,r,o.totalduration,h,m,p)}else this.warn("Levels were reset while fragment load was in progress. Fragment "+i.sn+" of level "+i.level+" will not be buffered")},i.onAudioTrackSwitching=function(t,e){var i=this.altAudio;if(!e.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;var r=this.fragCurrent;r&&(this.log("Switching to main audio track, cancel main fragment load"),r.abortRequests(),this.fragmentTracker.removeFragment(r)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();var s=this.hls;i&&(s.trigger(D.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),s.trigger(D.AUDIO_TRACK_SWITCHED,e)}},i.onAudioTrackSwitched=function(t,e){var i=e.id,r=!!this.hls.audioTracks[i].url;if(r){var s=this.videoBuffer;s&&this.mediaBuffer!==s&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=s)}this.altAudio=r,this.tick()},i.onBufferCreated=function(t,e){var i,r,s=e.tracks,n=!1;for(var a in s){var o=s[a];if("main"===o.id){if(r=a,i=o,"video"===a){var l=s[a];l&&(this.videoBuffer=l.buffer)}}else n=!0}n&&i?(this.log("Alternate track found, use "+r+".buffered to schedule main fragment loading"),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media},i.onFragBuffered=function(t,e){var i=e.frag,r=e.part;if(!i||i.type===Qe.MAIN){if(this.fragContextChanged(i))return this.warn("Fragment "+i.sn+(r?" p: "+r.index:"")+" of level "+i.level+" finished buffering, but was aborted. state: "+this.state),void(this.state===Qr.PARSED&&(this.state=Qr.IDLE));var s=r?r.stats:i.stats;this.fragLastKbps=Math.round(8*s.total/(s.buffering.end-s.loading.first)),"initSegment"!==i.sn&&(this.fragPrevious=i),this.fragBufferedComplete(i,r)}},i.onError=function(t,e){var i;if(e.fatal)this.state=Qr.ERROR;else switch(e.details){case w.FRAG_GAP:case w.FRAG_PARSING_ERROR:case w.FRAG_DECRYPT_ERROR:case w.FRAG_LOAD_ERROR:case w.FRAG_LOAD_TIMEOUT:case w.KEY_LOAD_ERROR:case w.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Qe.MAIN,e);break;case w.LEVEL_LOAD_ERROR:case w.LEVEL_LOAD_TIMEOUT:case w.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==Qr.WAITING_LEVEL||(null==(i=e.context)?void 0:i.type)!==ze.LEVEL||(this.state=Qr.IDLE);break;case w.BUFFER_APPEND_ERROR:case w.BUFFER_FULL_ERROR:if(!e.parent||"main"!==e.parent)return;if(e.details===w.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(e)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case w.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}},i.checkBuffer=function(){var t=this.media,e=this.gapController;if(t&&e&&t.readyState){if(this.loadedmetadata||!Ir.getBuffered(t).length){var i=this.state!==Qr.IDLE?this.fragCurrent:null;e.poll(this.lastCurrentTime,i)}this.lastCurrentTime=t.currentTime}},i.onFragLoadEmergencyAborted=function(){this.state=Qr.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()},i.onBufferFlushed=function(t,e){var i=e.type;if(i!==V.AUDIO||this.audioOnly&&!this.altAudio){var r=(i===V.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(r,i,Qe.MAIN),this.tick()}},i.onLevelsUpdated=function(t,e){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=e.levels},i.swapAudioCodec=function(){this.audioCodecSwap=!this.audioCodecSwap},i.seekToStartPos=function(){var t=this.media;if(t){var e=t.currentTime,i=this.startPosition;if(i>=0&&e<i){if(t.seeking)return void this.log("could not seek to "+i+", already seeking at "+e);var r=Ir.getBuffered(t),s=(r.length?r.start(0):0)-i;s>0&&(s<this.config.maxBufferHole||s<this.config.maxFragLookUpTolerance)&&(this.log("adjusting start position by "+s+" to match buffer start"),i+=s,this.startPosition=i),this.log("seek to target start position "+i+" from current time "+e),t.currentTime=i}}},i._getAudioCodec=function(t){var e=this.config.defaultAudioCodec||t.audioCodec;return this.audioCodecSwap&&e&&(this.log("Swapping audio codec"),e=-1!==e.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),e},i._loadBitrateTestFrag=function(t,e){var i=this;t.bitrateTest=!0,this._doFragLoad(t,e).then((function(r){var s=i.hls;if(r&&!i.fragContextChanged(t)){e.fragmentError=0,i.state=Qr.IDLE,i.startFragRequested=!1,i.bitrateTest=!1;var n=t.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),s.trigger(D.FRAG_LOADED,r),t.bitrateTest=!1}}))},i._handleTransmuxComplete=function(t){var e,i="main",r=this.hls,s=t.remuxResult,n=t.chunkMeta,a=this.getCurrentContext(n);if(a){var o=a.frag,l=a.part,h=a.level,d=s.video,u=s.text,c=s.id3,f=s.initSegment,g=h.details,m=this.altAudio?void 0:s.audio;if(this.fragContextChanged(o))this.fragmentTracker.removeFragment(o);else{if(this.state=Qr.PARSING,f){if(null!=f&&f.tracks){var p=o.initSegment||o;this._bufferInitSegment(h,f.tracks,p,n),r.trigger(D.FRAG_PARSING_INIT_SEGMENT,{frag:p,id:i,tracks:f.tracks})}var v=f.initPTS,y=f.timescale;R(v)&&(this.initPTS[o.cc]={baseTime:v,timescale:y},r.trigger(D.INIT_PTS_FOUND,{frag:o,id:i,initPTS:v,timescale:y}))}if(d&&g&&"initSegment"!==o.sn){var E=g.fragments[o.sn-1-g.startSN],T=o.sn===g.startSN,S=!E||o.cc>E.cc;if(!1!==s.independent){var A=d.startPTS,L=d.endPTS,b=d.startDTS,k=d.endDTS;if(l)l.elementaryStreams[d.type]={startPTS:A,endPTS:L,startDTS:b,endDTS:k};else if(d.firstKeyFrame&&d.independent&&1===n.id&&!S&&(this.couldBacktrack=!0),d.dropped&&d.independent){var I=this.getMainFwdBufferInfo(),w=(I?I.end:this.getLoadPosition())+this.config.maxBufferHole,C=d.firstKeyFramePTS?d.firstKeyFramePTS:A;if(!T&&w<C-this.config.maxBufferHole&&!S)return void this.backtrack(o);S&&(o.gap=!0),o.setElementaryStreamInfo(d.type,o.start,L,o.start,k,!0)}else T&&A>Fl&&(o.gap=!0);o.setElementaryStreamInfo(d.type,A,L,b,k),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(d,o,l,n,T||S)}else{if(!T&&!S)return void this.backtrack(o);o.gap=!0}}if(m){var _=m.startPTS,P=m.endPTS,x=m.startDTS,M=m.endDTS;l&&(l.elementaryStreams[V.AUDIO]={startPTS:_,endPTS:P,startDTS:x,endDTS:M}),o.setElementaryStreamInfo(V.AUDIO,_,P,x,M),this.bufferFragmentData(m,o,l,n)}if(g&&null!=c&&null!=(e=c.samples)&&e.length){var O={id:i,frag:o,details:g,samples:c.samples};r.trigger(D.FRAG_PARSING_METADATA,O)}if(g&&u){var F={id:i,frag:o,details:g,samples:u.samples};r.trigger(D.FRAG_PARSING_USERDATA,F)}}}else this.resetWhenMissingContext(n)},i._bufferInitSegment=function(t,e,i,r){var s=this;if(this.state===Qr.PARSING){this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&delete e.audio;var n=e.audio,a=e.video,o=e.audiovideo;if(n){var l=t.audioCodec,h=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){l&&(l=-1!==l.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");var d=n.metadata;d&&"channelCount"in d&&1!==(d.channelCount||1)&&-1===h.indexOf("firefox")&&(l="mp4a.40.5")}l&&-1!==l.indexOf("mp4a.40.5")&&-1!==h.indexOf("android")&&"audio/mpeg"!==n.container&&(l="mp4a.40.2",this.log("Android: force audio codec to "+l)),t.audioCodec&&t.audioCodec!==l&&this.log('Swapping manifest audio codec "'+t.audioCodec+'" for "'+l+'"'),n.levelCodec=l,n.id="main",this.log("Init audio buffer, container:"+n.container+", codecs[selected/level/parsed]=["+(l||"")+"/"+(t.audioCodec||"")+"/"+n.codec+"]")}a&&(a.levelCodec=t.videoCodec,a.id="main",this.log("Init video buffer, container:"+a.container+", codecs[level/parsed]=["+(t.videoCodec||"")+"/"+a.codec+"]")),o&&this.log("Init audiovideo buffer, container:"+o.container+", codecs[level/parsed]=["+t.codecs+"/"+o.codec+"]"),this.hls.trigger(D.BUFFER_CODECS,e),Object.keys(e).forEach((function(t){var n=e[t].initSegment;null!=n&&n.byteLength&&s.hls.trigger(D.BUFFER_APPENDING,{type:t,data:n,frag:i,part:null,chunkMeta:r,parent:i.type})})),this.tickImmediate()}},i.getMainFwdBufferInfo=function(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,Qe.MAIN)},i.backtrack=function(t){this.couldBacktrack=!0,this.backtrackFragment=t,this.resetTransmuxer(),this.flushBufferGap(t),this.fragmentTracker.removeFragment(t),this.fragPrevious=null,this.nextLoadPosition=t.start,this.state=Qr.IDLE},i.checkFragmentChanged=function(){var t=this.media,e=null;if(t&&t.readyState>1&&!1===t.seeking){var i=t.currentTime;if(Ir.isBuffered(t,i)?e=this.getAppendedFrag(i):Ir.isBuffered(t,i+.1)&&(e=this.getAppendedFrag(i+.1)),e){this.backtrackFragment=null;var r=this.fragPlaying,s=e.level;r&&e.sn===r.sn&&r.level===s||(this.fragPlaying=e,this.hls.trigger(D.FRAG_CHANGED,{frag:e}),r&&r.level===s||this.hls.trigger(D.LEVEL_SWITCHED,{level:s}))}}},o(e,[{key:"nextLevel",get:function(){var t=this.nextBufferedFrag;return t?t.level:-1}},{key:"currentFrag",get:function(){var t=this.media;return t?this.fragPlaying||this.getAppendedFrag(t.currentTime):null}},{key:"currentProgramDateTime",get:function(){var t=this.media;if(t){var e=t.currentTime,i=this.currentFrag;if(i&&R(e)&&R(i.programDateTime)){var r=i.programDateTime+1e3*(e-i.start);return new Date(r)}}return null}},{key:"currentLevel",get:function(){var t=this.currentFrag;return t?t.level:-1}},{key:"nextBufferedFrag",get:function(){var t=this.currentFrag;return t?this.followingBufferedFrag(t):null}},{key:"forceStartLoad",get:function(){return this._forceStartLoad}}]),e}(Jr),Hl=function(){function t(e){void 0===e&&(e={}),this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this.started=!1,this._emitter=new bn,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,this.triggeringException=void 0,O(e.debug||!1,"Hls instance");var i=this.config=bl(t.DefaultConfig,e);this.userConfig=e,i.progressive&&Dl(i);var r=i.abrController,s=i.bufferController,n=i.capLevelController,a=i.errorController,o=i.fpsController,l=new a(this),h=this.abrController=new r(this),d=this.bufferController=new s(this),u=this.capLevelController=new n(this),c=new o(this),f=new ti(this),g=new mi(this),m=i.contentSteeringController,p=m?new m(this):null,v=this.levelController=new Il(this,p),y=new Rr(this),E=new Cl(this.config),T=this.streamController=new Kl(this,y,E);u.setStreamController(T),c.setStreamController(T);var S=[f,v,T];p&&S.splice(1,0,p),this.networkControllers=S;var A=[h,d,u,c,g,y];this.audioTrackController=this.createController(i.audioTrackController,S);var L=i.audioStreamController;L&&S.push(new L(this,y,E)),this.subtitleTrackController=this.createController(i.subtitleTrackController,S);var R=i.subtitleStreamController;R&&S.push(new R(this,y,E)),this.createController(i.timelineController,A),E.emeController=this.emeController=this.createController(i.emeController,A),this.cmcdController=this.createController(i.cmcdController,A),this.latencyController=this.createController(pi,A),this.coreComponents=A,S.push(l);var b=l.onErrorOut;"function"==typeof b&&this.on(D.ERROR,b,l)}t.isMSESupported=function(){return Pl()},t.isSupported=function(){return xl()},t.getMediaSource=function(){return Se()};var e=t.prototype;return e.createController=function(t,e){if(t){var i=new t(this);return e&&e.push(i),i}return null},e.on=function(t,e,i){void 0===i&&(i=this),this._emitter.on(t,e,i)},e.once=function(t,e,i){void 0===i&&(i=this),this._emitter.once(t,e,i)},e.removeAllListeners=function(t){this._emitter.removeAllListeners(t)},e.off=function(t,e,i,r){void 0===i&&(i=this),this._emitter.off(t,e,i,r)},e.listeners=function(t){return this._emitter.listeners(t)},e.emit=function(t,e,i){return this._emitter.emit(t,e,i)},e.trigger=function(t,e){if(this.config.debug)return this.emit(t,t,e);try{return this.emit(t,t,e)}catch(e){if(F.error("An internal error happened while handling event "+t+'. Error message: "'+e.message+'". Here is a stacktrace:',e),!this.triggeringException){this.triggeringException=!0;var i=t===D.ERROR;this.trigger(D.ERROR,{type:I.OTHER_ERROR,details:w.INTERNAL_EXCEPTION,fatal:i,event:t,error:e}),this.triggeringException=!1}}return!1},e.listenerCount=function(t){return this._emitter.listenerCount(t)},e.destroy=function(){F.log("destroy"),this.trigger(D.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach((function(t){return t.destroy()})),this.networkControllers.length=0,this.coreComponents.forEach((function(t){return t.destroy()})),this.coreComponents.length=0;var t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null},e.attachMedia=function(t){F.log("attachMedia"),this._media=t,this.trigger(D.MEDIA_ATTACHING,{media:t})},e.detachMedia=function(){F.log("detachMedia"),this.trigger(D.MEDIA_DETACHING,void 0),this._media=null},e.loadSource=function(t){this.stopLoad();var e=this.media,i=this.url,r=this.url=L.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,F.log("loadSource:"+r),e&&i&&(i!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(e)),this.trigger(D.MANIFEST_LOADING,{url:t})},e.startLoad=function(t){void 0===t&&(t=-1),F.log("startLoad("+t+")"),this.started=!0,this.networkControllers.forEach((function(e){e.startLoad(t)}))},e.stopLoad=function(){F.log("stopLoad"),this.started=!1,this.networkControllers.forEach((function(t){t.stopLoad()}))},e.resumeBuffering=function(){this.started&&this.networkControllers.forEach((function(t){"fragmentLoader"in t&&t.startLoad(-1)}))},e.pauseBuffering=function(){this.networkControllers.forEach((function(t){"fragmentLoader"in t&&t.stopLoad()}))},e.swapAudioCodec=function(){F.log("swapAudioCodec"),this.streamController.swapAudioCodec()},e.recoverMediaError=function(){F.log("recoverMediaError");var t=this._media;this.detachMedia(),t&&this.attachMedia(t)},e.removeLevel=function(t){this.levelController.removeLevel(t)},e.setAudioOption=function(t){var e;return null==(e=this.audioTrackController)?void 0:e.setAudioOption(t)},e.setSubtitleOption=function(t){var e;return null==(e=this.subtitleTrackController)||e.setSubtitleOption(t),null},o(t,[{key:"levels",get:function(){var t=this.levelController.levels;return t||[]}},{key:"currentLevel",get:function(){return this.streamController.currentLevel},set:function(t){F.log("set currentLevel:"+t),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}},{key:"nextLevel",get:function(){return this.streamController.nextLevel},set:function(t){F.log("set nextLevel:"+t),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}},{key:"loadLevel",get:function(){return this.levelController.level},set:function(t){F.log("set loadLevel:"+t),this.levelController.manualLevel=t}},{key:"nextLoadLevel",get:function(){return this.levelController.nextLoadLevel},set:function(t){this.levelController.nextLoadLevel=t}},{key:"firstLevel",get:function(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)},set:function(t){F.log("set firstLevel:"+t),this.levelController.firstLevel=t}},{key:"startLevel",get:function(){var t=this.levelController.startLevel;return-1===t&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t},set:function(t){F.log("set startLevel:"+t),-1!==t&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}},{key:"capLevelToPlayerSize",get:function(){return this.config.capLevelToPlayerSize},set:function(t){var e=!!t;e!==this.config.capLevelToPlayerSize&&(e?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=e)}},{key:"autoLevelCapping",get:function(){return this._autoLevelCapping},set:function(t){this._autoLevelCapping!==t&&(F.log("set autoLevelCapping:"+t),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}},{key:"bandwidthEstimate",get:function(){var t=this.abrController.bwEstimator;return t?t.getEstimate():NaN},set:function(t){this.abrController.resetEstimator(t)}},{key:"ttfbEstimate",get:function(){var t=this.abrController.bwEstimator;return t?t.getEstimateTTFB():NaN}},{key:"maxHdcpLevel",get:function(){return this._maxHdcpLevel},set:function(t){yi(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,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 t=this.levels,e=this.config.minAutoBitrate;if(!t)return 0;for(var i=t.length,r=0;r<i;r++)if(t[r].maxBitrate>=e)return r;return 0}},{key:"maxAutoLevel",get:function(){var t,e=this.levels,i=this.autoLevelCapping,r=this.maxHdcpLevel;if(t=-1===i&&null!=e&&e.length?e.length-1:i,r)for(var s=t;s--;){var n=e[s].attrs["HDCP-LEVEL"];if(n&&n<=r)return s}return t}},{key:"firstAutoLevel",get:function(){return this.abrController.firstAutoLevel}},{key:"nextAutoLevel",get:function(){return this.abrController.nextAutoLevel},set:function(t){this.abrController.nextAutoLevel=t}},{key:"playingDate",get:function(){return this.streamController.currentProgramDateTime}},{key:"mainForwardBufferInfo",get:function(){return this.streamController.getMainFwdBufferInfo()}},{key:"allAudioTracks",get:function(){var t=this.audioTrackController;return t?t.allAudioTracks:[]}},{key:"audioTracks",get:function(){var t=this.audioTrackController;return t?t.audioTracks:[]}},{key:"audioTrack",get:function(){var t=this.audioTrackController;return t?t.audioTrack:-1},set:function(t){var e=this.audioTrackController;e&&(e.audioTrack=t)}},{key:"allSubtitleTracks",get:function(){var t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}},{key:"subtitleTracks",get:function(){var t=this.subtitleTrackController;return t?t.subtitleTracks:[]}},{key:"subtitleTrack",get:function(){var t=this.subtitleTrackController;return t?t.subtitleTrack:-1},set:function(t){var e=this.subtitleTrackController;e&&(e.subtitleTrack=t)}},{key:"media",get:function(){return this._media}},{key:"subtitleDisplay",get:function(){var t=this.subtitleTrackController;return!!t&&t.subtitleDisplay},set:function(t){var e=this.subtitleTrackController;e&&(e.subtitleDisplay=t)}},{key:"lowLatencyMode",get:function(){return this.config.lowLatencyMode},set:function(t){this.config.lowLatencyMode=t}},{key:"liveSyncPosition",get:function(){return this.latencyController.liveSyncPosition}},{key:"latency",get:function(){return this.latencyController.latency}},{key:"maxLatency",get:function(){return this.latencyController.maxLatency}},{key:"targetLatency",get:function(){return this.latencyController.targetLatency}},{key:"drift",get:function(){return this.latencyController.drift}},{key:"forceStartLoad",get:function(){return this.streamController.forceStartLoad}}],[{key:"version",get:function(){return"1.5.14"}},{key:"Events",get:function(){return D}},{key:"ErrorTypes",get:function(){return I}},{key:"ErrorDetails",get:function(){return w}},{key:"DefaultConfig",get:function(){return t.defaultConfig?t.defaultConfig:Ll},set:function(e){t.defaultConfig=e}}]),t}();return Hl.defaultConfig=void 0,Hl}()}(!1)},54449:(t,e,i)=>{"use strict";i.d(e,{F:()=>v});var r=i(97173),s=i(48669),n=i(14822),a=i(1368),o=i(70182),l=i(89986),h=i.n(l),d=i(25160),u=i(9489),c=function(t,e,i){for(var r=arguments.length>2,s=0;s<e.length;s++)i=r?e[s].call(t,i):e[s].call(t);return r?i:void 0},f=function(t,e,i,r,s,n){function a(t){if(void 0!==t&&"function"!=typeof t)throw new TypeError("Function expected");return t}for(var o,l=r.kind,h="getter"===l?"get":"setter"===l?"set":"value",d=!e&&t?r.static?t:t.prototype:null,u=e||(d?Object.getOwnPropertyDescriptor(d,r.name):{}),c=!1,f=i.length-1;f>=0;f--){var g={};for(var m in r)g[m]="access"===m?{}:r[m];for(var m in r.access)g.access[m]=r.access[m];g.addInitializer=function(t){if(c)throw new TypeError("Cannot add initializers after decoration has completed");n.push(a(t||null))};var p=(0,i[f])("accessor"===l?{get:u.get,set:u.set}:u[h],g);if("accessor"===l){if(void 0===p)continue;if(null===p||"object"!=typeof p)throw new TypeError("Object expected");(o=a(p.get))&&(u.get=o),(o=a(p.set))&&(u.set=o),(o=a(p.init))&&s.unshift(o)}else(o=a(p))&&("field"===l?s.unshift(o):u[h]=o)}d&&Object.defineProperty(d,r.name,u),c=!0},g=function(t,e,i){return"symbol"==typeof e&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(t,"name",{configurable:!0,value:i?"".concat(i," ",e):e})},m=function(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)},p=function(t,e,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(t,i):s?s.value=i:e.set(t,i),i};let v=(()=>{var t,e,i,l,v,y,E,T,S,A,L,R,b,k,D,I,w,C,_,P;let x,M,O,F,N,U,B,G=[d.JW],K=[],H=[];M=class{get executionContextProvider(){var t;return null!==(t=this.player)&&void 0!==t?t:null}get model(){return this.player.model}get pc(){return this.model.playerConfig}get mc(){return this.model.mediaCollection}get vc(){return this.player.viewCtrl}get videoScale(){return this.model.videoScaleMode}set videoScale(t){this.model.videoScaleMode!==t&&(this.model.videoScaleMode=t,this.applyVideoScale(t))}set remotePlaybackDevice(e){m(this,t,"f")!==e&&(this.player.loop.dispatchEvent(r.a.REMOTE_PLAYBACK_CHANGED,(0,u.cl)(e)?{isRemote:!1}:{isRemote:!0,device:e}),this.player.isLive&&!this.player.isAudio&&this.vc.setLiveInitialBufferState()),p(this,t,e,"f")}get remotePlaybackDevice(){return m(this,t,"f")}get isRemotePlayback(){return!(0,u.cl)(m(this,t,"f"))}get playbackStalled(){return m(this,v,"f")}get __cumulativeDrift(){return m(this,b,"f")}constructor(s,a){this.minDisplayedLiveOffset=(c(this,H),7),this.subtitleListeners=[],this.audioTrackListeners=[],this.audioTracks=[],this.audioTrack=null,t.set(this,null),e.set(this,0),i.set(this,0),l.set(this,!1),v.set(this,!1),y.set(this,0),E.set(this,!1),T.set(this,!1),this._duration=0,this._dvrModeEnabled=!1,S.set(this,-1),A.set(this,-1),L.set(this,0),R.set(this,0),b.set(this,0),this.isAtEnd=!1,this._useAndroidInitialSeekFallback=!1,k.set(this,-1),D.set(this,-1),I.set(this,!1),this._ready=!1,this._pendingSeek=0,w.set(this,-1),C.set(this,!1),this._dvrEnabled=!1,this._dvrIsLive=!1,this._dvrWindow=0,this.expectedAudios=[],_.set(this,!1),this.pinnedDvrSync=null,this.dvrWindowUnstable=!1,this[P]=this.getClassTypeString(),this.player=s,this.mediaElement=a,this.applyVideoScale(this.videoScale),this.player.loop.dispatchEvent(r.a.EVENT_INIT,{}),this.player.loop.dispatchEvent(r.a.EVENT_STATUS_CHANGE,{status:"init"}),this.emap=new(h()),this.addEventListeners(),n.x.for(this.player).storageListeners.add(this),a instanceof HTMLMediaElement&&(a.textTracks.onaddtrack=t=>{this.onTextTracksChanged(t)},a.textTracks.onremovetrack=t=>{this.onTextTracksChanged(t)}),this.player.loop.dispatchEvent(r.a.EVENT_STATUS_CHANGE,{status:"ready"})}debugString(){return"none"}debugQualityLevel(){return[-1,1]}debugResolution(){return this.isRemotePlayback?"-":`${this.mediaElement.videoWidth}x${this.mediaElement.videoHeight}`}debugFrames(){if(this.mediaElement instanceof HTMLVideoElement){const t=this.mediaElement.getVideoPlaybackQuality();return`${t.droppedVideoFrames} dropped of ${t.totalVideoFrames}`}return"no video info available"}get subQualities(){return this.error("using base implementation for subQuality listing!"),[{level:-1,label:"Auto",width:-1}]}selectSubQuality(t){this.error("using base implementation for subQuality selection!")}get currentSubQuality(){return this.error("using base implementation for currentSubQuality!"),-1}log(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];this.player.console.log(`[${this.getClassTypeString()}]`,...e)}info(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];this.player.console.info(`[${this.getClassTypeString()}]`,...e)}warn(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];this.player.console.warn(`[${this.getClassTypeString()}]`,...e)}error(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];this.player.console.error(`[${this.getClassTypeString()}]`,...e)}onTextTracksChanged(t){this.subtitleListeners.forEach((e=>{e.onTextTracksChanged(t)}))}addSubtitleListener(t){this.subtitleListeners.includes(t)||this.subtitleListeners.push(t)}removeSubtitleListener(t){const e=this.subtitleListeners.indexOf(t);-1!==e&&(this.subtitleListeners=this.subtitleListeners.splice(e,1))}onAudioTracksChanged(){1===this.audioTracks.length&&1===this.expectedAudios.length&&"audio-description"===this.expectedAudios[0].kind&&(this.audioTracks[0].isAudioDescription=!0),this.player.loop.dispatchEvent(r.a.AUDIO_TRACK_LIST_CHANGED,{audioTracks:this.audioTracks}),this.audioTrackListeners.forEach((t=>{t.onAudioTracksChanged(this.audioTracks)}))}addAudioTrackListener(t){this.audioTrackListeners.includes(t)||this.audioTrackListeners.push(t)}removeAudioTrackListener(t){const e=this.audioTrackListeners.indexOf(t);-1!==e&&(this.audioTrackListeners=this.audioTrackListeners.splice(e,1))}addEventListeners(){this.emap.map(this.mediaElement,"loadstart",this.onLoadStart,this),this.emap.map(this.mediaElement,"canplay",this.onCanPlay,this),this.emap.map(this.mediaElement,"play",this.onPlay,this),this.emap.map(this.mediaElement,"pause",this.onPause,this),this.emap.map(this.mediaElement,"error",this.onError,this),this.emap.map(this.mediaElement,"waiting",this.onWaiting,this),this.emap.map(this.mediaElement,"ended",this.onEnded,this),this.emap.map(this.mediaElement,"timeupdate",this.onTimeUpdate,this),this.emap.map(this.mediaElement,"seeking",this.onSeeking,this),this.emap.map(this.mediaElement,"seeked",this.onSeekEnd,this),this.emap.map(this.mediaElement,"loadedmetadata",this.onLoadedMetadata,this),this.emap.map(this.mediaElement,"loadeddata",this.onLoadedData,this),this.emap.map(this.mediaElement,"durationchange",this.onDurationChange,this),this.emap.map(this.mediaElement,"progress",this.onProgress,this),this.emap.map(this.mediaElement,"stalled",this.onStalled,this),this.emap.map(this.mediaElement,"volumechange",this.onLocalVolumeChange,this)}onLoadStart(){var t,e;s.O.isAndroidDevice&&(null!==(e=null===(t=this.mediaElement)||void 0===t?void 0:t.currentSrc)&&void 0!==e?e:"").toLowerCase().indexOf(".m3u8")>0&&(this._useAndroidInitialSeekFallback=!0)}onCanPlay(){this.mediaElement instanceof HTMLMediaElement&&!(this.mediaElement.readyState>=this.mediaElement.HAVE_FUTURE_DATA)||this.bufferingEventHandler(!1),p(this,v,!1,"f"),this.setPlaybackRate(this.model.playbackRate)}onPlay(){this.startTicker(),this.playEventHandler(),this.bufferingEventHandler(!1),this.vc.setOutDelayed()}onPause(t){this.pauseEventHandler(t,!isNaN(this.mediaElement.currentTime)&&!isNaN(this.mediaElement.duration)&&this.mediaElement.currentTime>=this.mediaElement.duration&&("ios"!==s.O.platform||!this.player.isLive))}onError(t){this.handleError(t)}onWaiting(t){this.mediaElement instanceof HTMLMediaElement&&this.bufferingEventHandler(this.mediaElement.readyState<this.mediaElement.HAVE_FUTURE_DATA),p(this,v,!0,"f")}onEnded(t){this.stopTicker(),this.mediaElement.pause(),this.endEventHandler(t),this.onTimeChange(this._duration,0)}onTimeUpdate(t){if(this.onProgress(null),this.updateTicker(),this.isSeeking()&&!m(this,I,"f")){const t=this.getCurrentTime();Math.abs(m(this,D,"f")-t)<Math.abs(m(this,k,"f")-t)&&this.onSeekEnd(null)}}onSeeking(){p(this,I,!0,"f"),m(this,E,"f")||0!==this._pendingSeek||this.player.loop.dispatchEvent(r.a.EVENT_SEEK_START,{from:m(this,k,"f"),to:m(this,D,"f")}),this.bufferingEventHandler(!0)}onSeekEnd(t){this.isSeeking()&&(m(this,E,"f")||0!==this._pendingSeek||this.player.loop.dispatchEvent(r.a.EVENT_SEEK_END,{lastPosition:m(this,k,"f"),position:this.getCurrentTime()}),p(this,E,!1,"f"),p(this,k,-1,"f"),p(this,D,-1,"f"),m(this,I,"f")||this.bufferingEventHandler(!1),p(this,I,!1,"f"),this.bufferingEventHandler(!1),this.player.clearExecutionContext(r.a.EVENT_SEEK_START,r.a.EVENT_SEEK_START_INTENT,r.a.EVENT_SEEK_END,r.a.EVENT_BUFFERING))}isSeeking(){return m(this,I,"f")||-1!==m(this,D,"f")&&-1!==m(this,k,"f")}onLoadedMetadata(){this._ready=!0,this.evalInitialSeek()}onLoadedData(){this.evalInitialSeek(),this.onProgress(null)}onDurationChange(t){const e=this.mediaElement.duration;isNaN(e)||(this._duration=e),this._ready=!0,this.onProgress(null)}onLocalVolumeChange(t){const e=this.mediaElement.muted,i=this.mediaElement.volume;this.getVolume()/100===i&&m(this,_,"f")===e||(this.player.setMutedInternal(e,!0,!1,!0,!0),this.player.setVolumeInternal(100*i,!0,!1,!1))}onProgress(t){var e;if(!this.mediaElement||"waiting"===(null==t?void 0:t.type)&&this.isSeeking())return;const i=this.getCurrentTime(),r=this.getDuration();let s=-1;const n=null===(e=this.mediaElement)||void 0===e?void 0:e.buffered;if(n)for(let t=0;t<n.length;t++)if(n.start(t)<=i&&n.end(t)>=i){s=n.end(t);break}if(-1===s)return;const a=Math.round(s/r*100);this.bufferProgressHandler(a)}onStalled(t){this.onProgress(t)}onSourceError(t){this.stopTicker(),this.handleError(t)}onTimeChange(t,e){this.model.duration!==t&&t>0&&this.model.duration>0&&null!=this.pinnedDvrSync&&(this.pinnedDvrSync=null,this.dvrWindowUnstable=!0,this.warn("DVR window unstable, disabled sync info pinning")),this.updateDuration(t),this.updateTime(Math.max(e,0))}bufferingEventHandler(t){this.onProgress(null),t&&!this.isAtEnd?this.vc.showBufferingIndicator():this.vc.hideBufferingIndicator(),t!==m(this,l,"f")&&(p(this,l,t,"f"),this.player.loop.dispatchEvent(r.a.EVENT_BUFFERING,{isBuffering:t}))}bufferProgressHandler(t){this.vc.updateBufferProgress(t),p(this,y,t,"f")}playEventHandler(){var t;if(this.stopOtherPlayingPlayers(),this.model.playstate=o.R.PLAYSTATE_PLAYING,this.player.loop.dispatchEvent(r.a.EVENT_STATUS_CHANGE,{status:"play"}),this.isAtEnd){const e=this.getCurrentTimeWithoutSeek();null===(t=this.executionContextProvider)||void 0===t||t.preserveExecutionContext(r.a.EVENT_INITIAL_FRAME,500);const i=t=>{t.currentTime!==e&&(this.player.loop.dispatchEvent(r.a.EVENT_INITIAL_FRAME,{}),m(this,l,"f")||this.bufferingEventHandler(!1))},s=()=>{this.player.loop.removeEventListener(r.a.EVENT_UPDATE_STREAM_TIME,i),this.player.loop.removeEventListener(r.a.EVENT_INITIAL_FRAME,s)};this.player.loop.addEventListener(r.a.EVENT_UPDATE_STREAM_TIME,i),this.player.loop.addEventListener(r.a.EVENT_INITIAL_FRAME,s)}this.isAtEnd=!1,this.player.pixelController.replayTrigger(),this.player.pixelController.initialPlayTrigger(),this.player.loop.dispatchEvent(r.a.EVENT_PLAY_STREAM,{})}pauseEventHandler(t,e){void 0===e&&(e=!1),this.model.playstate=o.R.PLAYSTATE_PAUSED,this.player.loop.dispatchEvent(r.a.EVENT_STATUS_CHANGE,{status:"pause"}),this.player.loop.dispatchEvent(r.a.EVENT_PAUSE_STREAM,{ended:e})}endEventHandler(t){this.jumpToStart(),this.player.pixelController.triggerPixel(a.k.CLIP_ENDED),this.pauseEventHandler(t,!0),this.vc.hidePosterFrame(),this.mc.isLive||this.vc.showPlayAgain(),this.vc.hideBufferingIndicator(),"web"===s.O.platform&&this.player.setFullscreenInternal(!1),this.player.pixelController&&(this.player.pixelController._isReplay=!0),this.isAtEnd=!0,this.player.loop.dispatchEvent(r.a.EVENT_END_STREAM,{})}evalInitialSeek(){if(this._pendingSeek>0){if(this.canSeek()){p(this,E,!0,"f");const t=this._pendingSeek;this._pendingSeek=0,this.setCurrentTime(t,m(this,T,"f"),!1,!0),m(this,T,"f")||this.play()}}else m(this,T,"f")||this.play()}updateDuration(t){this.model.duration!==t&&(this.model.duration=t,this.player.loop.dispatchEvent(r.a.EVENT_UPDATE_STREAM_DURATION,{duration:t}))}restartMedia(){this.jumpToStart(),this.play()}resetStartAndEndTime(){this.pc.generic.vodStartSeconds=0,this.pc.generic.vodEndSeconds=0}updateTime(t){this.model.time=t,this.vc.updateTime(t),this.vc.updateTimeline(t,this.model.duration);const s=Date.now();if(s>=m(this,i,"f")+1e3){p(this,i,s,"f");let e=0;const r=Math.round(this.model.duration),n=Math.round(t);this.vc._dvrEnabledAndRequested&&!this.vc._dvrIsLive&&(e=Math.min(Math.round(r-t),r)),this.player.pixelController.triggerCustomPixel(a.k.SUPER_PLAYHEAD_POSITION,!1,{currentTime:n,duration:r,dvrRelativeTime:-e})}const l=this.pc.generic.vodStartSeconds,h=this.pc.generic.vodEndSeconds;if(l>0&&t<l){const i=Math.round(t);Math.abs(m(this,e,"f")-i)>3&&(this.setCurrentTime(l,!1,!1,!0),p(this,e,i,"f"))}else h>0&&t>h&&(this.setCurrentTime(l,!1,!1,!0),this.pause());this.player.loop.dispatchEvent(r.a.EVENT_UPDATE_STREAM_TIME,{currentTime:t}),window.parent!==window&&n.x.AVAILABLE&&this.model.playstate===o.R.PLAYSTATE_PLAYING&&n.x.get(n.x.SUFFIX_GLOBAL,n.x.CURRENT_PLAYERID,!0)!==this.player.getId()&&this.pause()}removeEventListeners(){this.emap.all()}dispose(){this.log("dispose()"),this.removeEventListeners(),n.x.for(this.player).storageListeners.delete(this),this.mediaElement instanceof HTMLMediaElement&&(this.mediaElement.textTracks.onaddtrack=null,this.mediaElement.textTracks.onremovetrack=null),this.mediaElement.pause(),this.subtitleListeners=[],this.audioTrackListeners=[],this.stopTicker(),this.player.loop.dispatchEvent(r.a.EVENT_STOP_STREAM,{}),m(this,T,"f")&&0===this.model.playstate&&(this.model.playstate=3),this.audioTracks=[],this.audioTrack=null}stopOtherPlayingPlayers(){n.x.add(n.x.SUFFIX_GLOBAL,n.x.CURRENT_PLAYERID,this.player.getId(),!0,!0),o.R.autoPlayerAlreadyActive=this.player.getId()}onStorageValueChanged(t,e){t===n.x.CURRENT_PLAYERID&&"string"==typeof e&&this.isPlaying()&&e!==this.player.getId()&&this.pause()}loadStream(t){if(p(this,T,1===this.model.playstate||3===this.model.playstate,"f"),this.model.playstate=o.R.PLAYSTATE_UNSPECIFIED,m(this,T,"f")||this.stopOtherPlayingPlayers(),this.player.preserveExecutionContext(r.a.EVENT_LOAD_STREAM,5e3),this.player.loop.dispatchEvent(r.a.EVENT_LOAD_STREAM,{mediaStream:t}),this._pendingSeek=this.model.time,0===this._pendingSeek&&!this.mc.isLive){let t=this.pc.generic.vodInitialPlayheadSeconds;t<=0&&(t=this.pc.generic.vodStartSeconds),this._pendingSeek=t}if(this.mediaElement instanceof HTMLMediaElement)for(;this.mediaElement.children.length>0;)this.mediaElement.removeChild(this.mediaElement.children[0]);if(this.expectedAudios=t.audios,this.addSource(t),!s.O.isEmbedded){const t=n.x.volume(this.player),e=this.pc.generic.isMuted||n.x.muted(this.player);this.player.setVolumeInternal(t,!1,!0,!0),this.player.setMutedInternal(e,!1,!0,!1,!1)}if(m(this,T,"f")){const t=()=>{this.pause(),this.mediaElement.removeEventListener("canplay",t)};this.mediaElement.addEventListener("canplay",t)}this.mediaElement.load()}startTicker(){this.stopTicker(),this.updateTicker(),p(this,w,this.player.safeInterval((()=>{this.updateTicker()}),500),"f")}stopTicker(){clearInterval(m(this,w,"f")),p(this,w,-1,"f")}updateTicker(){this.onTimeChange(this.getDuration(),this.getCurrentTime())}play(){var t;this.player.preserveExecutionContext(r.a.EVENT_PLAY_STREAM),p(this,T,!1,"f"),m(this,C,"f")?this.handleError():null===(t=this.mediaElement.play())||void 0===t||t.then((()=>{var t;try{this.player.checkState()}catch(t){return void this.warn("aborting async",t)}null===(t=this.vc)||void 0===t||t.hidePosterFrame(),this.startTicker()})).catch((t=>{var e,i,s;try{this.player.checkState()}catch(t){return void this.warn("aborting async",t)}this.error("playback failure",t),null===(e=this.player)||void 0===e||e.loop.dispatchEvent(r.a.EVENT_AUTOPLAY_STREAM_PROHIBITED,{}),null===(i=this.vc)||void 0===i||i.showPlayBtn(),null===(s=this.vc)||void 0===s||s.showPosterFrame(),this.stopTicker()}))}pause(){this.player.preserveExecutionContext(r.a.EVENT_PAUSE_STREAM),this.model.playstate=o.R.PLAYSTATE_PAUSED,this.mediaElement.pause(),this.mc.isLive&&this.mc.isDvrEnabled||(this.updateTicker(),this.stopTicker())}togglePlay(){m(this,C,"f")?this.handleError():this.isPlaying()?this.pause():this.play()}isPlaying(){return this.model.playstate===o.R.PLAYSTATE_PLAYING}setVolume(t){t>=0&&t<=100&&(this.mediaElement.volume=t/100)}getVolume(){return n.x.volume(this.player)}setMuted(t){p(this,_,t,"f"),this.mediaElement.muted=t,this.mediaElement instanceof HTMLMediaElement&&(t?this.mediaElement.setAttribute("muted","muted"):this.mediaElement.removeAttribute("muted"))}setCurrentTime(t,e,i,s){void 0===e&&(e=!1),void 0===i&&(i=!1),void 0===s&&(s=!1),this.player.preserveExecutionContext(r.a.EVENT_SEEK_START),this.canCalculateDvrUnixTime()&&t>=this.dvrRelToUnix(0)&&(t=this.dvrUnixToRel(t));const n=this.getDuration()>0?Math.min(t,this.getDuration()-.1):t;this.setSeekEventTimestamps(this.getCurrentTime(),n),this.setCurrentTimeRaw(n,e,i,s),this.player.model.time=n}setSeekEventTimestamps(t,e){p(this,k,t,"f"),p(this,D,e,"f")}setCurrentTimeRaw(t,e,i,s){void 0===e&&(e=!1),void 0===i&&(i=!1),void 0===s&&(s=!1),p(this,L,0,"f"),p(this,R,0,"f"),p(this,b,0,"f");const n=this.pc.generic.vodStartSeconds,a=this.pc.generic.vodEndSeconds;if(!s&&(n>0&&t<n||a>0&&t>a)&&this.resetStartAndEndTime(),this._ready){if(!this.canSeek())return;t=Math.max(0,t),this._pendingSeek=0,this.isAtEnd&&p(this,E,!0,"f");try{this.player.preserveExecutionContextAlias(r.a.EVENT_SEEK_START,-1,r.a.EVENT_SEEK_START_INTENT,r.a.EVENT_SEEK_END,r.a.EVENT_BUFFERING),m(this,E,"f")||0!==this._pendingSeek||this.player.loop.dispatchEvent(r.a.EVENT_SEEK_START_INTENT,{from:m(this,k,"f"),to:m(this,D,"f")}),i||(this.mediaElement.currentTime=t)}catch(e){this._pendingSeek=t}}else this._pendingSeek=t;this.updateTicker(),this.isAtEnd&&!e&&this.play()}seekToLive(){this.canSeek()&&this.setCurrentTime(this.getDuration())}setPlaybackRate(t){const e=this.model.playbackRate!==t||this.mediaElement.playbackRate!==t;this.model.playbackRate=t,this.mediaElement.playbackRate!==t&&(this.mediaElement.playbackRate=t),e&&this.player.loop.dispatchEvent(r.a.PLAYBACK_RATE_CHANGE,{rate:t})}getDvrToDateSync(){return null}getSmoothDvrToDateSync(t){var e,i,r;return!this.dvrWindowUnstable&&t&&this.canCalculateDvrUnixTime()?(null==this.pinnedDvrSync&&(this.pinnedDvrSync=this.getDvrToDateSync(),0!==(null===(e=this.pinnedDvrSync)||void 0===e?void 0:e.rel)&&0!==(null===(i=this.pinnedDvrSync)||void 0===i?void 0:i.real)&&0!==(null===(r=this.pinnedDvrSync)||void 0===r?void 0:r.at)||(this.pinnedDvrSync=null)),this.pinnedDvrSync):this.getDvrToDateSync()}dvrRelToUnix(t,e){void 0===e&&(e=!1);const i=this.getSmoothDvrToDateSync(e);if(null!==i){if(e&&!this.dvrWindowUnstable)return this.__dvrRelToUnixRaw(t,i)|0;let r=m(this,b,"f");if(this.isPlaying()&&!this.playbackStalled){if(0!==m(this,L,"f")){const t=this.getCurrentTime();if(isFinite(t)&&t>0){const e=this.__dvrRelToUnixRaw(t,i)-m(this,L,"f");p(this,b,m(this,b,"f")+e,"f"),r+=e,this.info("PAUSE DRIFT",e)}p(this,L,0,"f"),p(this,R,0,"f")}const t=performance.now(),e=1e3*this.__dvrRelToUnixRaw(100,i);if(-1!==m(this,S,"f")&&-1!==m(this,A,"f")){const i=e-(m(this,A,"f")+(t-m(this,S,"f")));Math.abs(i)>=10&&(p(this,b,m(this,b,"f")+i/1e3,"f"),r+=i/1e3)}p(this,S,t,"f"),p(this,A,e,"f")}else p(this,S,-1,"f"),p(this,A,-1,"f"),0===m(this,R,"f")?(p(this,R,this.getCurrentTime(),"f"),p(this,L,this.__dvrRelToUnixRaw(m(this,R,"f"),i),"f")):r+=this.__dvrRelToUnixRaw(this.getCurrentTime(),i)-m(this,L,"f");return this.__dvrRelToUnixRaw(t,i)-r|0}return e&&!this.dvrWindowUnstable||(p(this,L,0,"f"),p(this,R,0,"f"),p(this,b,0,"f")),0}__dvrRelToUnixRaw(t,e){const i=e.rel-t,r=Date.now()-e.at;return(e.real+r)/1e3-i}dvrUnixToRel(t){return t-this.dvrRelToUnix(0)}canCalculateDvrUnixTime(){const t=this.getDvrToDateSync();return null!=t&&0!==t.real&&0!==t.rel&&0!==t.at}dvrUnixToRelNullable(t){const e=this.dvrRelToUnixNullable(0);return null==e?null:t-e}dvrRelToUnixNullable(t,e){return void 0===e&&(e=!1),null==this.getSmoothDvrToDateSync(e)?null:this.dvrRelToUnix(t,e)}canSeek(){return this.mediaElement instanceof HTMLMediaElement&&this.mediaElement.seekable.length>0}getPercentBuffered(){return m(this,y,"f")}getCurrentTime(){if(this._pendingSeek>0)return this._pendingSeek;const t=this.mediaElement.currentTime;return isNaN(t)?this.model.time:t}getCurrentTimeWithoutSeek(){return!m(this,E,"f")&&m(this,k,"f")>=0?m(this,k,"f"):this.getCurrentTime()}setTimeByPercent(t){const e=t/100*this.getDuration();return this.setCurrentTime(e),e}getDuration(){const t=this.mediaElement.duration;return isNaN(t)?0!==this._duration?this._duration:this.model.duration:t}stop(t){if(!this.isAtEnd){this.model.playstate=o.R.PLAYSTATE_STOPPED,this.isAtEnd=!0,this.player.loop.dispatchEvent(r.a.EVENT_STOP_STREAM,{}),this.player.loop.dispatchEvent(r.a.EVENT_STATUS_CHANGE,{status:"stop"});try{this.player.checkStateStrict(),this.pause(),this.jumpToStart(),this.bufferingEventHandler(!1),this.updateTicker(),this.stopTicker()}catch(t){}}}jumpToStart(){this.setCurrentTime(0,!0)}onDVRCallback(t,e,i){this._dvrEnabled=t&&e>=120,this._dvrWindow=e,this._dvrIsLive=i,this.player.viewCtrl.onDVRCallback(this._dvrEnabled,this._dvrWindow,this._dvrIsLive),this.updateTicker(),this.player.loop.dispatchEvent(r.a.EVENT_DVR_CHANGE,{dvrEnabled:this._dvrEnabled,dvrIsLive:this._dvrIsLive,dvrWindow:this._dvrWindow})}getAudioTracks(){return[]}setAudioTrack(t){}setAudioTrackById(t){}getAudioTrack(){return null}handleError(t){var e;this.stopTicker(),p(this,C,!0,"f");let i=[];t&&(this.error(t),"string"==typeof t?i=[t]:"object"==typeof t&&("type"in t&&(0,u.Ed)(t.type)&&"error"!==t.type&&i.push(String(t.type)),"name"in t&&(0,u.Ed)(t.name)&&"error"!==t.name&&i.push(String(t.name)),(0,u.Ed)(t.message)&&i.push(String(t.message)))),null===(e=this.player.errorCtrl)||void 0===e||e.throwStreamError(...i)}toJSON(){return toString()}};return t=new WeakMap,e=new WeakMap,i=new WeakMap,l=new WeakMap,v=new WeakMap,y=new WeakMap,E=new WeakMap,T=new WeakMap,S=new WeakMap,A=new WeakMap,L=new WeakMap,R=new WeakMap,b=new WeakMap,k=new WeakMap,D=new WeakMap,I=new WeakMap,w=new WeakMap,C=new WeakMap,_=new WeakMap,O=[(0,d.C6)(r.a.EVENT_PAUSE_STREAM,{type:"other",initiator:"external-playback-pause"})],F=[(0,d.C6)(r.a.EVENT_PLAY_STREAM)],N=[(0,d.kF)({type:"lifecycle",initiator:"playback-end"})],U=[(0,d.C6)(r.a.EVENT_LOAD_STREAM)],B=[(0,d.kF)({type:"other",initiator:"dvrUpdate"})],P=Symbol.toStringTag,g(M,"AbstractPlayerCtrl"),(()=>{const t="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;f(M,null,O,{kind:"method",name:"onPause",static:!1,private:!1,access:{has:t=>"onPause"in t,get:t=>t.onPause},metadata:t},null,H),f(M,null,F,{kind:"method",name:"playEventHandler",static:!1,private:!1,access:{has:t=>"playEventHandler"in t,get:t=>t.playEventHandler},metadata:t},null,H),f(M,null,N,{kind:"method",name:"endEventHandler",static:!1,private:!1,access:{has:t=>"endEventHandler"in t,get:t=>t.endEventHandler},metadata:t},null,H),f(M,null,U,{kind:"method",name:"evalInitialSeek",static:!1,private:!1,access:{has:t=>"evalInitialSeek"in t,get:t=>t.evalInitialSeek},metadata:t},null,H),f(M,null,B,{kind:"method",name:"onDVRCallback",static:!1,private:!1,access:{has:t=>"onDVRCallback"in t,get:t=>t.onDVRCallback},metadata:t},null,H),f(null,x={value:M},G,{kind:"class",name:M.name,metadata:t},null,K),M=x.value,t&&Object.defineProperty(M,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:t}),c(M,K)})(),M})()},73731:(t,e,i)=>{"use strict";i.d(e,{X:()=>l,q:()=>h});var r=i(65042),s=i(25160),n=function(t,e,i,r,s,n){function a(t){if(void 0!==t&&"function"!=typeof t)throw new TypeError("Function expected");return t}for(var o,l=r.kind,h="getter"===l?"get":"setter"===l?"set":"value",d=!e&&t?r.static?t:t.prototype:null,u=e||(d?Object.getOwnPropertyDescriptor(d,r.name):{}),c=!1,f=i.length-1;f>=0;f--){var g={};for(var m in r)g[m]="access"===m?{}:r[m];for(var m in r.access)g.access[m]=r.access[m];g.addInitializer=function(t){if(c)throw new TypeError("Cannot add initializers after decoration has completed");n.push(a(t||null))};var p=(0,i[f])("accessor"===l?{get:u.get,set:u.set}:u[h],g);if("accessor"===l){if(void 0===p)continue;if(null===p||"object"!=typeof p)throw new TypeError("Object expected");(o=a(p.get))&&(u.get=o),(o=a(p.set))&&(u.set=o),(o=a(p.init))&&s.unshift(o)}else(o=a(p))&&("field"===l?s.unshift(o):u[h]=o)}d&&Object.defineProperty(d,r.name,u),c=!0},a=function(t,e,i){for(var r=arguments.length>2,s=0;s<e.length;s++)i=r?e[s].call(t,i):e[s].call(t);return r?i:void 0},o=function(t,e,i){return"symbol"==typeof e&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(t,"name",{configurable:!0,value:i?"".concat(i," ",e):e})};let l=(()=>{let t,e,i=[s.JW],l=[];e=class{execute(t,e){var i,s;let n;n=t.model.mediaCollection.streams.some((t=>!t.isAudioOnly))?r.J.createVideo(t,!0):r.J.createAudio(t,!0);try{null===(i=t.viewCtrl)||void 0===i||i.removeMediaCanvas()}catch(t){}null!==n?e(n):null===(s=t.errorCtrl)||void 0===s||s.throwError("MEDIACANVAS_NOT_GENERATED",!0)}};return o(e,"DefaultMediaElementGenerator"),(()=>{const r="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;n(null,t={value:e},i,{kind:"class",name:e.name,metadata:r},null,l),e=t.value,r&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:r}),a(e,l)})(),e})(),h=(()=>{let t,e,i=[s.JW],l=[];e=class{execute(t,e){var i,s;const n=r.J.createVideo(t,!0);try{null===(i=t.viewCtrl)||void 0===i||i.removeMediaCanvas()}catch(t){}null!==n?e(n):null===(s=t.errorCtrl)||void 0===s||s.throwError("MEDIACANVAS_NOT_GENERATED",!0)}};return o(e,"DefaultVideoElementGenerator"),(()=>{const r="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;n(null,t={value:e},i,{kind:"class",name:e.name,metadata:r},null,l),e=t.value,r&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:r}),a(e,l)})(),e})()},17994:(t,e,i)=>{"use strict";i.r(e),i.d(e,{default:()=>io});var r=i(97173),s=i(70182),n=i(54449),a=i(25160),o=i(9489);function l(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var h,d,u,c,f,g={exports:{}};h=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,d=/^(?=([^\/?#]*))\1([^]*)$/,u=/(?:\/|^)\.(?=\/)/g,c=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,g.exports=f={buildAbsoluteURL:function(t,e,i){if(i=i||{},t=t.trim(),!(e=e.trim())){if(!i.alwaysNormalize)return t;var r=f.parseURL(t);if(!r)throw new Error("Error trying to parse base URL.");return r.path=f.normalizePath(r.path),f.buildURLFromParts(r)}var s=f.parseURL(e);if(!s)throw new Error("Error trying to parse relative URL.");if(s.scheme)return i.alwaysNormalize?(s.path=f.normalizePath(s.path),f.buildURLFromParts(s)):e;var n=f.parseURL(t);if(!n)throw new Error("Error trying to parse base URL.");if(!n.netLoc&&n.path&&"/"!==n.path[0]){var a=d.exec(n.path);n.netLoc=a[1],n.path=a[2]}n.netLoc&&!n.path&&(n.path="/");var o={scheme:n.scheme,netLoc:s.netLoc,path:null,params:s.params,query:s.query,fragment:s.fragment};if(!s.netLoc&&(o.netLoc=n.netLoc,"/"!==s.path[0]))if(s.path){var l=n.path,h=l.substring(0,l.lastIndexOf("/")+1)+s.path;o.path=f.normalizePath(h)}else o.path=n.path,s.params||(o.params=n.params,s.query||(o.query=n.query));return null===o.path&&(o.path=i.alwaysNormalize?f.normalizePath(s.path):s.path),f.buildURLFromParts(o)},parseURL:function(t){var e=h.exec(t);return e?{scheme:e[1]||"",netLoc:e[2]||"",path:e[3]||"",params:e[4]||"",query:e[5]||"",fragment:e[6]||""}:null},normalizePath:function(t){for(t=t.split("").reverse().join("").replace(u,"");t.length!==(t=t.replace(c,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}};var m=g.exports;function p(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),i.push.apply(i,r)}return i}function v(t){for(var e=1;e<arguments.length;e++){var i=null!=arguments[e]?arguments[e]:{};e%2?p(Object(i),!0).forEach((function(e){E(t,e,i[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):p(Object(i)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))}))}return t}function y(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var r=i.call(t,e||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}function E(t,e,i){return(e=y(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function T(){return T=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var r in i)Object.prototype.hasOwnProperty.call(i,r)&&(t[r]=i[r])}return t},T.apply(this,arguments)}const S=Number.isFinite||function(t){return"number"==typeof t&&isFinite(t)},A=Number.isSafeInteger||function(t){return"number"==typeof t&&Math.abs(t)<=L},L=Number.MAX_SAFE_INTEGER||9007199254740991;let R=function(t){return t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.BUFFER_RESET="hlsBufferReset",t.BUFFER_CODECS="hlsBufferCodecs",t.BUFFER_CREATED="hlsBufferCreated",t.BUFFER_APPENDING="hlsBufferAppending",t.BUFFER_APPENDED="hlsBufferAppended",t.BUFFER_EOS="hlsBufferEos",t.BUFFER_FLUSHING="hlsBufferFlushing",t.BUFFER_FLUSHED="hlsBufferFlushed",t.MANIFEST_LOADING="hlsManifestLoading",t.MANIFEST_LOADED="hlsManifestLoaded",t.MANIFEST_PARSED="hlsManifestParsed",t.LEVEL_SWITCHING="hlsLevelSwitching",t.LEVEL_SWITCHED="hlsLevelSwitched",t.LEVEL_LOADING="hlsLevelLoading",t.LEVEL_LOADED="hlsLevelLoaded",t.LEVEL_UPDATED="hlsLevelUpdated",t.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",t.LEVELS_UPDATED="hlsLevelsUpdated",t.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",t.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",t.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",t.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",t.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",t.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",t.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",t.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",t.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",t.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",t.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",t.CUES_PARSED="hlsCuesParsed",t.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",t.INIT_PTS_FOUND="hlsInitPtsFound",t.FRAG_LOADING="hlsFragLoading",t.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",t.FRAG_LOADED="hlsFragLoaded",t.FRAG_DECRYPTED="hlsFragDecrypted",t.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",t.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",t.FRAG_PARSING_METADATA="hlsFragParsingMetadata",t.FRAG_PARSED="hlsFragParsed",t.FRAG_BUFFERED="hlsFragBuffered",t.FRAG_CHANGED="hlsFragChanged",t.FPS_DROP="hlsFpsDrop",t.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",t.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",t.ERROR="hlsError",t.DESTROYING="hlsDestroying",t.KEY_LOADING="hlsKeyLoading",t.KEY_LOADED="hlsKeyLoaded",t.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",t.BACK_BUFFER_REACHED="hlsBackBufferReached",t.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",t}({}),b=function(t){return t.NETWORK_ERROR="networkError",t.MEDIA_ERROR="mediaError",t.KEY_SYSTEM_ERROR="keySystemError",t.MUX_ERROR="muxError",t.OTHER_ERROR="otherError",t}({}),k=function(t){return t.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",t.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",t.KEY_SYSTEM_NO_SESSION="keySystemNoSession",t.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",t.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",t.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",t.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",t.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",t.MANIFEST_LOAD_ERROR="manifestLoadError",t.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",t.MANIFEST_PARSING_ERROR="manifestParsingError",t.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",t.LEVEL_EMPTY_ERROR="levelEmptyError",t.LEVEL_LOAD_ERROR="levelLoadError",t.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",t.LEVEL_PARSING_ERROR="levelParsingError",t.LEVEL_SWITCH_ERROR="levelSwitchError",t.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",t.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",t.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",t.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",t.FRAG_LOAD_ERROR="fragLoadError",t.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",t.FRAG_DECRYPT_ERROR="fragDecryptError",t.FRAG_PARSING_ERROR="fragParsingError",t.FRAG_GAP="fragGap",t.REMUX_ALLOC_ERROR="remuxAllocError",t.KEY_LOAD_ERROR="keyLoadError",t.KEY_LOAD_TIMEOUT="keyLoadTimeOut",t.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",t.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",t.BUFFER_APPEND_ERROR="bufferAppendError",t.BUFFER_APPENDING_ERROR="bufferAppendingError",t.BUFFER_STALLED_ERROR="bufferStalledError",t.BUFFER_FULL_ERROR="bufferFullError",t.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",t.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",t.INTERNAL_EXCEPTION="internalException",t.INTERNAL_ABORTED="aborted",t.UNKNOWN="unknown",t}({});const D=function(){},I={trace:D,debug:D,log:D,warn:D,info:D,error:D};let w=I;function C(t,...e){e.forEach((function(e){w[e]=t[e]?t[e].bind(t):function(t){const e=self.console[t];return e?e.bind(self.console,`[${t}] >`):D}(e)}))}const _=w,P=/^(\d+)x(\d+)$/,x=/(.+?)=(".*?"|.*?)(?:,|$)/g;class M{constructor(t){"string"==typeof t&&(t=M.parseAttrList(t)),T(this,t)}get clientAttrs(){return Object.keys(this).filter((t=>"X-"===t.substring(0,2)))}decimalInteger(t){const e=parseInt(this[t],10);return e>Number.MAX_SAFE_INTEGER?1/0:e}hexadecimalInteger(t){if(this[t]){let e=(this[t]||"0x").slice(2);e=(1&e.length?"0":"")+e;const i=new Uint8Array(e.length/2);for(let t=0;t<e.length/2;t++)i[t]=parseInt(e.slice(2*t,2*t+2),16);return i}return null}hexadecimalIntegerAsNumber(t){const e=parseInt(this[t],16);return e>Number.MAX_SAFE_INTEGER?1/0:e}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,e){const i=this[t];return i?parseFloat(i):e}enumeratedString(t){return this[t]}bool(t){return"YES"===this[t]}decimalResolution(t){const e=P.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}}static parseAttrList(t){let e;const i={};for(x.lastIndex=0;null!==(e=x.exec(t));){let t=e[2];0===t.indexOf('"')&&t.lastIndexOf('"')===t.length-1&&(t=t.slice(1,-1));i[e[1].trim()]=t}return i}}function O(t){return"SCTE35-OUT"===t||"SCTE35-IN"===t}class F{constructor(t,e){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,e){const i=e.attr;for(const e in i)if(Object.prototype.hasOwnProperty.call(t,e)&&t[e]!==i[e]){_.warn(`DATERANGE tag attribute: "${e}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=e;break}t=T(new M({}),i,t)}if(this.attr=t,this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){const t=new Date(this.attr["END-DATE"]);S(t.getTime())&&(this._endDate=t)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get startDate(){return this._startDate}get endDate(){if(this._endDate)return this._endDate;const t=this.duration;return null!==t?new Date(this._startDate.getTime()+1e3*t):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if(S(t))return t}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isValid(){return!!this.id&&!this._badValueForSameId&&S(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class N{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var U="audio",B="video",G="audiovideo";class K{constructor(t){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[U]:null,[B]:null,[G]:null},this.baseurl=t}setByteRange(t,e){const i=t.split("@",2);let r;r=1===i.length?(null==e?void 0:e.byteRangeEndOffset)||0:parseInt(i[1]),this._byteRange=[r,parseInt(i[0])+r]}get byteRange(){return this._byteRange?this._byteRange:[]}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=m.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}}class H extends K{constructor(t,e){super(e),this._decryptdata=null,this.rawProgramDateTime=null,this.programDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.stats=new N,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=t}get decryptdata(){const{levelkeys:t}=this;if(!t&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const t=this.levelkeys.identity;if(t)this._decryptdata=t.getDecryptData(this.sn);else{const t=Object.keys(this.levelkeys);if(1===t.length)return this._decryptdata=this.levelkeys[t[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;if(!S(this.programDateTime))return null;const t=S(this.duration)?this.duration:0;return this.programDateTime+1e3*t}get encrypted(){var t;if(null!=(t=this._decryptdata)&&t.encrypted)return!0;if(this.levelkeys){const t=Object.keys(this.levelkeys),e=t.length;if(e>1||1===e&&this.levelkeys[t[0]].encrypted)return!0}return!1}setKeyFormat(t){if(this.levelkeys){const e=this.levelkeys[t];e&&!this._decryptdata&&(this._decryptdata=e.getDecryptData(this.sn))}}abortRequests(){var t,e;null==(t=this.loader)||t.abort(),null==(e=this.keyLoader)||e.abort()}setElementaryStreamInfo(t,e,i,r,s,n=!1){const{elementaryStreams:a}=this,o=a[t];o?(o.startPTS=Math.min(o.startPTS,e),o.endPTS=Math.max(o.endPTS,i),o.startDTS=Math.min(o.startDTS,r),o.endDTS=Math.max(o.endDTS,s)):a[t]={startPTS:e,endPTS:i,startDTS:r,endDTS:s,partial:n}}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[U]=null,t[B]=null,t[G]=null}}class $ extends K{constructor(t,e,i,r,s){super(i),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.stats=new N,this.duration=t.decimalFloatingPoint("DURATION"),this.gap=t.bool("GAP"),this.independent=t.bool("INDEPENDENT"),this.relurl=t.enumeratedString("URI"),this.fragment=e,this.index=r;const n=t.enumeratedString("BYTERANGE");n&&this.setByteRange(n,s),s&&(this.fragOffset=s.fragOffset+s.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:t}=this;return!!(t.audio||t.video||t.audiovideo)}}class V{constructor(t){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.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 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.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=t}reloaded(t){if(!t)return this.advanced=!0,void(this.updated=!0);const e=this.lastPartSn-t.lastPartSn,i=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!i||!!e||!this.live,this.advanced=this.endSN>t.endSN||e>0||0===e&&i>0,this.updated||this.advanced?this.misses=Math.floor(.6*t.misses):this.misses=t.misses+1,this.availabilityDelay=t.availabilityDelay}get hasProgramDateTime(){return!!this.fragments.length&&S(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const t=this.driftEndTime-this.driftStartTime;if(t>0){return 1e3*(this.driftEnd-this.driftStart)/t}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var t;return null!=(t=this.fragments)&&t.length?this.fragments[this.fragments.length-1].end:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].index:-1}get lastPartSn(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}function Y(t){return Uint8Array.from(atob(t),(t=>t.charCodeAt(0)))}function W(t){const e=t.split(":");let i=null;if("data"===e[0]&&2===e.length){const t=e[1].split(";"),r=t[t.length-1].split(",");if(2===r.length){const e="base64"===r[0],s=r[1];e?(t.splice(-1,1),i=Y(s)):i=function(t){const e=j(t).subarray(0,16),i=new Uint8Array(16);return i.set(e,16-e.length),i}(s)}}return i}function j(t){return Uint8Array.from(unescape(encodeURIComponent(t)),(t=>t.charCodeAt(0)))}const q="undefined"!=typeof self?self:void 0;var X={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},z="org.w3.clearkey",Q="com.apple.streamingkeydelivery",J="com.microsoft.playready",Z="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function tt(t){switch(t){case Q:return X.FAIRPLAY;case J:return X.PLAYREADY;case Z:return X.WIDEVINE;case z:return X.CLEARKEY}}var et="edef8ba979d64acea3c827dcd51d21ed";function it(t){switch(t){case X.FAIRPLAY:return Q;case X.PLAYREADY:return J;case X.WIDEVINE:return Z;case X.CLEARKEY:return z}}function rt(t){const{drmSystems:e,widevineLicenseUrl:i}=t,r=e?[X.FAIRPLAY,X.WIDEVINE,X.PLAYREADY,X.CLEARKEY].filter((t=>!!e[t])):[];return!r[X.WIDEVINE]&&i&&r.push(X.WIDEVINE),r}const st=null!=q&&null!=(nt=q.navigator)&&nt.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var nt;function at(t,e,i){return Uint8Array.prototype.slice?t.slice(e,i):new Uint8Array(Array.prototype.slice.call(t,e,i))}const ot=(t,e)=>e+10<=t.length&&73===t[e]&&68===t[e+1]&&51===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128,lt=(t,e)=>e+10<=t.length&&51===t[e]&&68===t[e+1]&&73===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128,ht=(t,e)=>{const i=e;let r=0;for(;ot(t,e);){r+=10;r+=dt(t,e+6),lt(t,e+10)&&(r+=10),e+=r}if(r>0)return t.subarray(i,i+r)},dt=(t,e)=>{let i=0;return i=(127&t[e])<<21,i|=(127&t[e+1])<<14,i|=(127&t[e+2])<<7,i|=127&t[e+3],i},ut=(t,e)=>ot(t,e)&&dt(t,e+6)+10<=t.length-e,ct=t=>{const e=mt(t);for(let t=0;t<e.length;t++){const i=e[t];if(ft(i))return Tt(i)}},ft=t=>t&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info,gt=t=>{const e=String.fromCharCode(t[0],t[1],t[2],t[3]),i=dt(t,4);return{type:e,size:i,data:t.subarray(10,10+i)}},mt=t=>{let e=0;const i=[];for(;ot(t,e);){const r=dt(t,e+6);e+=10;const s=e+r;for(;e+8<s;){const r=gt(t.subarray(e)),s=pt(r);s&&i.push(s),e+=r.size+10}lt(t,e)&&(e+=10)}return i},pt=t=>"PRIV"===t.type?vt(t):"W"===t.type[0]?Et(t):yt(t),vt=t=>{if(t.size<2)return;const e=St(t.data,!0),i=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:i.buffer}},yt=t=>{if(t.size<2)return;if("TXXX"===t.type){let e=1;const i=St(t.data.subarray(e),!0);e+=i.length+1;const r=St(t.data.subarray(e));return{key:t.type,info:i,data:r}}const e=St(t.data.subarray(1));return{key:t.type,data:e}},Et=t=>{if("WXXX"===t.type){if(t.size<2)return;let e=1;const i=St(t.data.subarray(e),!0);e+=i.length+1;const r=St(t.data.subarray(e));return{key:t.type,info:i,data:r}}const e=St(t.data);return{key:t.type,data:e}},Tt=t=>{if(8===t.data.byteLength){const e=new Uint8Array(t.data),i=1&e[3];let r=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return r/=45,i&&(r+=47721858.84),Math.round(r)}},St=(t,e=!1)=>{const i=Lt();if(i){const r=i.decode(t);if(e){const t=r.indexOf("\0");return-1!==t?r.substring(0,t):r}return r.replace(/\0/g,"")}const r=t.length;let s,n,a,o="",l=0;for(;l<r;){if(s=t[l++],0===s&&e)return o;if(0!==s&&3!==s)switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(s);break;case 12:case 13:n=t[l++],o+=String.fromCharCode((31&s)<<6|63&n);break;case 14:n=t[l++],a=t[l++],o+=String.fromCharCode((15&s)<<12|(63&n)<<6|63&a)}}return o};let At;function Lt(){if(!navigator.userAgent.includes("PlayStation 4"))return At||void 0===self.TextDecoder||(At=new self.TextDecoder("utf-8")),At}const Rt=function(t){let e="";for(let i=0;i<t.length;i++){let r=t[i].toString(16);r.length<2&&(r="0"+r),e+=r}return e},bt=Math.pow(2,32)-1,kt=[].push,Dt={video:1,audio:2,id3:3,text:4};function It(t){return String.fromCharCode.apply(null,t)}function wt(t,e){const i=t[e]<<8|t[e+1];return i<0?65536+i:i}function Ct(t,e){const i=Pt(t,e);return i<0?4294967296+i:i}function _t(t,e){let i=Ct(t,e);return i*=Math.pow(2,32),i+=Ct(t,e+4),i}function Pt(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function xt(t,e,i){t[e]=i>>24,t[e+1]=i>>16&255,t[e+2]=i>>8&255,t[e+3]=255&i}function Mt(t,e){const i=[];if(!e.length)return i;const r=t.byteLength;for(let s=0;s<r;){const n=Ct(t,s),a=n>1?s+n:r;if(It(t.subarray(s+4,s+8))===e[0])if(1===e.length)i.push(t.subarray(s+8,a));else{const r=Mt(t.subarray(s+8,a),e.slice(1));r.length&&kt.apply(i,r)}s=a}return i}function Ot(t){const e=[],i=t[0];let r=8;const s=Ct(t,r);r+=4;let n=0,a=0;0===i?(n=Ct(t,r),a=Ct(t,r+4),r+=8):(n=_t(t,r),a=_t(t,r+8),r+=16),r+=2;let o=t.length+a;const l=wt(t,r);r+=2;for(let i=0;i<l;i++){let i=r;const n=Ct(t,i);i+=4;const a=2147483647&n;if(1===(2147483648&n)>>>31)return _.warn("SIDX has hierarchical references (not supported)"),null;const l=Ct(t,i);i+=4,e.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/s,start:o,end:o+a-1}}),o+=a,i+=4,r=i}return{earliestPresentationTime:n,timescale:s,version:i,referencesCount:l,references:e}}function Ft(t){const e=[],i=Mt(t,["moov","trak"]);for(let t=0;t<i.length;t++){const r=i[t],s=Mt(r,["tkhd"])[0];if(s){let t=s[0];const i=Ct(s,0===t?12:20),n=Mt(r,["mdia","mdhd"])[0];if(n){t=n[0];const s=Ct(n,0===t?12:20),a=Mt(r,["mdia","hdlr"])[0];if(a){const t=It(a.subarray(8,12)),n={soun:U,vide:B}[t];if(n){const t=Nt(Mt(r,["mdia","minf","stbl","stsd"])[0]);e[i]={timescale:s,type:n},e[n]=v({timescale:s,id:i},t)}}}}}return Mt(t,["moov","mvex","trex"]).forEach((t=>{const i=Ct(t,4),r=e[i];r&&(r.default={duration:Ct(t,12),flags:Ct(t,20)})})),e}function Nt(t){const e=t.subarray(8),i=e.subarray(86),r=It(e.subarray(4,8));let s=r;const n="enca"===r||"encv"===r;if(n){const t=Mt(e,[r])[0];Mt(t.subarray("enca"===r?28:78),["sinf"]).forEach((t=>{const e=Mt(t,["schm"])[0];if(e){const i=It(e.subarray(4,8));if("cbcs"===i||"cenc"===i){const e=Mt(t,["frma"])[0];e&&(s=It(e))}}}))}switch(s){case"avc1":case"avc2":case"avc3":case"avc4":{const t=Mt(i,["avcC"])[0];s+="."+Bt(t[1])+Bt(t[2])+Bt(t[3]);break}case"mp4a":{const t=Mt(e,[r])[0],i=Mt(t.subarray(28),["esds"])[0];if(i&&i.length>12){let t=4;if(3!==i[t++])break;t=Ut(i,t),t+=2;const e=i[t++];if(128&e&&(t+=2),64&e&&(t+=i[t++]),4!==i[t++])break;t=Ut(i,t);const r=i[t++];if(64!==r)break;if(s+="."+Bt(r),t+=12,5!==i[t++])break;t=Ut(i,t);const n=i[t++];let a=(248&n)>>3;31===a&&(a+=1+((7&n)<<3)+((224&i[t])>>5)),s+="."+a}break}case"hvc1":case"hev1":{const t=Mt(i,["hvcC"])[0],e=t[1],r=["","A","B","C"][e>>6],n=31&e,a=Ct(t,2),o=(32&e)>>5?"H":"L",l=t[12],h=t.subarray(6,12);s+="."+r+n,s+="."+a.toString(16).toUpperCase(),s+="."+o+l;let d="";for(let t=h.length;t--;){const e=h[t];if(e||d){d="."+e.toString(16).toUpperCase()+d}}s+=d;break}case"dvh1":case"dvhe":{const t=Mt(i,["dvcC"])[0],e=t[2]>>1&127,r=t[2]<<5&32|t[3]>>3&31;s+="."+Gt(e)+"."+Gt(r);break}case"vp09":{const t=Mt(i,["vpcC"])[0],e=t[4],r=t[5],n=t[6]>>4&15;s+="."+Gt(e)+"."+Gt(r)+"."+Gt(n);break}case"av01":{const t=Mt(i,["av1C"])[0],e=t[1]>>>5,r=31&t[1],n=t[2]>>>7?"H":"M",a=(64&t[2])>>6,o=(32&t[2])>>5,l=2===e&&a?o?12:10:a?10:8,h=(16&t[2])>>4,d=(8&t[2])>>3,u=(4&t[2])>>2,c=3&t[2],f=1,g=1,m=1,p=0;s+="."+e+"."+Gt(r)+n+"."+Gt(l)+"."+h+"."+d+u+c+"."+Gt(f)+"."+Gt(g)+"."+Gt(m)+"."+p;break}}return{codec:s,encrypted:n}}function Ut(t,e){const i=e+5;for(;128&t[e++]&&e<i;);return e}function Bt(t){return("0"+t.toString(16).toUpperCase()).slice(-2)}function Gt(t){return(t<10?"0":"")+t}function Kt(t){const e=Mt(t,["schm"])[0];if(e){const i=It(e.subarray(4,8));if("cbcs"===i||"cenc"===i)return Mt(t,["schi","tenc"])[0]}return _.error("[eme] missing 'schm' box"),null}function Ht(t){const e=Ct(t,0);let i=8;1&e&&(i+=4),4&e&&(i+=4);let r=0;const s=Ct(t,4);for(let n=0;n<s;n++){if(256&e){r+=Ct(t,i),i+=4}512&e&&(i+=4),1024&e&&(i+=4),2048&e&&(i+=4)}return r}function $t(t,e){const i=new Uint8Array(t.length+e.length);return i.set(t),i.set(e,t.length),i}function Vt(t,e){const i=[],r=e.samples,s=e.timescale,n=e.id;let a=!1;return Mt(r,["moof"]).map((o=>{const l=o.byteOffset-8;Mt(o,["traf"]).map((o=>{const h=Mt(o,["tfdt"]).map((t=>{const e=t[0];let i=Ct(t,4);return 1===e&&(i*=Math.pow(2,32),i+=Ct(t,8)),i/s}))[0];return void 0!==h&&(t=h),Mt(o,["tfhd"]).map((h=>{const d=Ct(h,4),u=16777215&Ct(h,0);let c=0;const f=!!(16&u);let g=0;const m=!!(32&u);let p=8;d===n&&(!!(1&u)&&(p+=8),!!(2&u)&&(p+=4),!!(8&u)&&(c=Ct(h,p),p+=4),f&&(g=Ct(h,p),p+=4),m&&(p+=4),"video"===e.type&&(a=function(t){if(!t)return!1;const e=t.indexOf("."),i=e<0?t:t.substring(0,e);return"hvc1"===i||"hev1"===i||"dvh1"===i||"dvhe"===i}(e.codec)),Mt(o,["trun"]).map((n=>{const o=n[0],h=16777215&Ct(n,0),d=!!(1&h);let u=0;const f=!!(4&h),m=!!(256&h);let p=0;const v=!!(512&h);let y=0;const E=!!(1024&h),T=!!(2048&h);let S=0;const A=Ct(n,4);let L=8;d&&(u=Ct(n,L),L+=4),f&&(L+=4);let R=u+l;for(let l=0;l<A;l++){if(m?(p=Ct(n,L),L+=4):p=c,v?(y=Ct(n,L),L+=4):y=g,E&&(L+=4),T&&(S=0===o?Ct(n,L):Pt(n,L),L+=4),e.type===B){let e=0;for(;e<y;){const n=Ct(r,R);if(R+=4,Yt(a,r[R])){Wt(r.subarray(R,R+n),a?2:1,t+S/s,i)}R+=n,e+=n+4}}t+=p/s}})))}))}))})),i}function Yt(t,e){if(t){const t=e>>1&63;return 39===t||40===t}return 6===(31&e)}function Wt(t,e,i,r){const s=jt(t);let n=0;n+=e;let a=0,o=0,l=0;for(;n<s.length;){a=0;do{if(n>=s.length)break;l=s[n++],a+=l}while(255===l);o=0;do{if(n>=s.length)break;l=s[n++],o+=l}while(255===l);const t=s.length-n;let e=n;if(o<t)n+=o;else if(o>t){_.error(`Malformed SEI payload. ${o} is too small, only ${t} bytes left to parse.`);break}if(4===a){if(181===s[e++]){const t=wt(s,e);if(e+=2,49===t){const t=Ct(s,e);if(e+=4,1195456820===t){const t=s[e++];if(3===t){const n=s[e++],o=64&n,l=o?2+3*(31&n):0,h=new Uint8Array(l);if(o){h[0]=n;for(let t=1;t<l;t++)h[t]=s[e++]}r.push({type:t,payloadType:a,pts:i,bytes:h})}}}}}else if(5===a&&o>16){const t=[];for(let i=0;i<16;i++){const r=s[e++].toString(16);t.push(1==r.length?"0"+r:r),3!==i&&5!==i&&7!==i&&9!==i||t.push("-")}const n=o-16,l=new Uint8Array(n);for(let t=0;t<n;t++)l[t]=s[e++];r.push({payloadType:a,pts:i,uuid:t.join(""),userData:St(l),userDataBytes:l})}}}function jt(t){const e=t.byteLength,i=[];let r=1;for(;r<e-2;)0===t[r]&&0===t[r+1]&&3===t[r+2]?(i.push(r+2),r+=2):r++;if(0===i.length)return t;const s=e-i.length,n=new Uint8Array(s);let a=0;for(r=0;r<s;a++,r++)a===i[0]&&(a++,i.shift()),n[r]=t[a];return n}function qt(t,e,i){if(16!==t.byteLength)throw new RangeError("Invalid system id");let r,s,n;if(e){r=1,s=new Uint8Array(16*e.length);for(let t=0;t<e.length;t++){const i=e[t];if(16!==i.byteLength)throw new RangeError("Invalid key");s.set(i,16*t)}}else r=0,s=new Uint8Array;r>0?(n=new Uint8Array(4),e.length>0&&new DataView(n.buffer).setUint32(0,e.length,!1)):n=new Uint8Array;const a=new Uint8Array(4);return i&&i.byteLength>0&&new DataView(a.buffer).setUint32(0,i.byteLength,!1),function(t,...e){const i=e.length;let r=8,s=i;for(;s--;)r+=e[s].byteLength;const n=new Uint8Array(r);for(n[0]=r>>24&255,n[1]=r>>16&255,n[2]=r>>8&255,n[3]=255&r,n.set(t,4),s=0,r=8;s<i;s++)n.set(e[s],r),r+=e[s].byteLength;return n}([112,115,115,104],new Uint8Array([r,0,0,0]),t,n,s,a,i||new Uint8Array)}let Xt={};class zt{static clearKeyUriToKeyIdMap(){Xt={}}constructor(t,e,i,r=[1],s=null){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=t,this.uri=e,this.keyFormat=i,this.keyFormatVersions=r,this.iv=s,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&"AES-128"!==t}isSupported(){if(this.method){if("AES-128"===this.method||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case Q:case Z:case J:case z:return-1!==["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(t){if(!this.encrypted||!this.uri)return null;if("AES-128"===this.method&&this.uri&&!this.iv){"number"!=typeof t&&("AES-128"!==this.method||this.iv||_.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0);const e=function(t){const e=new Uint8Array(16);for(let i=12;i<16;i++)e[i]=t>>8*(15-i)&255;return e}(t);return new zt(this.method,this.uri,"identity",this.keyFormatVersions,e)}const e=W(this.uri);if(e)switch(this.keyFormat){case Z:this.pssh=e,e.length>=22&&(this.keyId=e.subarray(e.length-22,e.length-6));break;case J:{const t=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=qt(t,null,e);const i=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),r=String.fromCharCode.apply(null,Array.from(i)),s=r.substring(r.indexOf("<"),r.length),n=(new DOMParser).parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(n){const t=n.childNodes[0]?n.childNodes[0].nodeValue:n.getAttribute("VALUE");if(t){const e=Y(t).subarray(0,16);!function(t){const e=function(t,e,i){const r=t[e];t[e]=t[i],t[i]=r};e(t,0,3),e(t,1,2),e(t,4,5),e(t,6,7)}(e),this.keyId=e}}break}default:{let t=e.subarray(0,16);if(16!==t.length){const e=new Uint8Array(16);e.set(t,16-t.length),t=e}this.keyId=t;break}}if(!this.keyId||16!==this.keyId.byteLength){let t=Xt[this.uri];if(!t){const e=Object.keys(Xt).length%Number.MAX_SAFE_INTEGER;t=new Uint8Array(16);new DataView(t.buffer,12,4).setUint32(0,e),Xt[this.uri]=t}this.keyId=t}return this}}const Qt=/\{\$([a-zA-Z0-9-_]+)\}/g;function Jt(t){return Qt.test(t)}function Zt(t,e,i){if(null!==t.variableList||t.hasVariableRefs)for(let r=i.length;r--;){const s=i[r],n=e[s];n&&(e[s]=te(t,n))}}function te(t,e){if(null!==t.variableList||t.hasVariableRefs){const i=t.variableList;return e.replace(Qt,(e=>{const r=e.substring(2,e.length-1),s=null==i?void 0:i[r];return void 0===s?(t.playlistParsingError||(t.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),e):s}))}return e}function ee(t,e,i){let r,s,n=t.variableList;if(n||(t.variableList=n={}),"QUERYPARAM"in e){r=e.QUERYPARAM;try{const t=new self.URL(i).searchParams;if(!t.has(r))throw new Error(`"${r}" does not match any query parameter in URI: "${i}"`);s=t.get(r)}catch(e){t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${e.message}`))}}else r=e.NAME,s=e.VALUE;r in n?t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${r}"`)):n[r]=s||""}function ie(t,e,i){const r=e.IMPORT;if(i&&r in i){let e=t.variableList;e||(t.variableList=e={}),e[r]=i[r]}else t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${r}"`))}function re(t=!0){if("undefined"==typeof self)return;return(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}const se={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,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function ne(t,e,i=!0){return!t.split(",").some((t=>!ae(t,e,i)))}function ae(t,e,i=!0){var r;const s=re(i);return null!=(r=null==s?void 0:s.isTypeSupported(oe(t,e)))&&r}function oe(t,e){return`${e}/mp4;codecs="${t}"`}function le(t){if(t){const e=t.substring(0,4);return se.video[e]}return 2}function he(t){return t.split(",").reduce(((t,e)=>{const i=se.video[e];return i?(2*i+t)/(t?3:2):(se.audio[e]+t)/(t?2:1)}),0)}const de={};const ue=/flac|opus/i;function ce(t,e=!0){return t.replace(ue,(t=>function(t,e=!0){if(de[t])return de[t];const i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"]}[t];for(let r=0;r<i.length;r++)if(ae(i[r],"audio",e))return de[t]=i[r],i[r];return t}(t.toLowerCase(),e)))}function fe(t,e){return t&&"mp4a"!==t?t:e?e.split(",")[0]:e}const ge=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,me=/#EXT-X-MEDIA:(.*)/g,pe=/^#EXT(?:INF|-X-TARGETDURATION):/m,ve=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),ye=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class Ee{static findGroup(t,e){for(let i=0;i<t.length;i++){const r=t[i];if(r.id===e)return r}}static resolve(t,e){return m.buildAbsoluteURL(e,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return pe.test(t)}static parseMasterPlaylist(t,e){const i={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:Jt(t)},r=[];let s;for(ge.lastIndex=0;null!=(s=ge.exec(t));)if(s[1]){var n;const t=new M(s[1]);Zt(i,t,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);const a=te(i,s[2]),o={attrs:t,bitrate:t.decimalInteger("BANDWIDTH")||t.decimalInteger("AVERAGE-BANDWIDTH"),name:t.NAME,url:Ee.resolve(a,e)},l=t.decimalResolution("RESOLUTION");l&&(o.width=l.width,o.height=l.height),Ae(t.CODECS,o),null!=(n=o.unknownCodecs)&&n.length||r.push(o),i.levels.push(o)}else if(s[3]){const t=s[3],r=s[4];switch(t){case"SESSION-DATA":{const t=new M(r);Zt(i,t,["DATA-ID","LANGUAGE","VALUE","URI"]);const e=t["DATA-ID"];e&&(null===i.sessionData&&(i.sessionData={}),i.sessionData[e]=t);break}case"SESSION-KEY":{const t=Te(r,e,i);t.encrypted&&t.isSupported()?(null===i.sessionKeys&&(i.sessionKeys=[]),i.sessionKeys.push(t)):_.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${r}"`);break}case"DEFINE":{const t=new M(r);Zt(i,t,["NAME","VALUE","QUERYPARAM"]),ee(i,t,e)}break;case"CONTENT-STEERING":{const t=new M(r);Zt(i,t,["SERVER-URI","PATHWAY-ID"]),i.contentSteering={uri:Ee.resolve(t["SERVER-URI"],e),pathwayId:t["PATHWAY-ID"]||"."};break}case"START":i.startTimeOffset=Se(r)}}const a=r.length>0&&r.length<i.levels.length;return i.levels=a?r:i.levels,0===i.levels.length&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(t,e,i){let r;const s={},n=i.levels,a={AUDIO:n.map((t=>({id:t.attrs.AUDIO,audioCodec:t.audioCodec}))),SUBTITLES:n.map((t=>({id:t.attrs.SUBTITLES,textCodec:t.textCodec}))),"CLOSED-CAPTIONS":[]};let o=0;for(me.lastIndex=0;null!==(r=me.exec(t));){const t=new M(r[1]),n=t.TYPE;if(n){const r=a[n],l=s[n]||[];s[n]=l,Zt(i,t,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const h=t.LANGUAGE,d=t["ASSOC-LANGUAGE"],u=t.CHANNELS,c=t.CHARACTERISTICS,f=t["INSTREAM-ID"],g={attrs:t,bitrate:0,id:o++,groupId:t["GROUP-ID"]||"",name:t.NAME||h||"",type:n,default:t.bool("DEFAULT"),autoselect:t.bool("AUTOSELECT"),forced:t.bool("FORCED"),lang:h,url:t.URI?Ee.resolve(t.URI,e):""};if(d&&(g.assocLang=d),u&&(g.channels=u),c&&(g.characteristics=c),f&&(g.instreamId=f),null!=r&&r.length){const t=Ee.findGroup(r,g.groupId)||r[0];Le(g,t,"audioCodec"),Le(g,t,"textCodec")}l.push(g)}}return s}static parseLevelPlaylist(t,e,i,r,s,n){const a=new V(e),o=a.fragments;let l,h,d,u=null,c=0,f=0,g=0,m=0,p=null,v=new H(r,e),y=-1,E=!1,A=null;for(ve.lastIndex=0,a.m3u8=t,a.hasVariableRefs=Jt(t);null!==(l=ve.exec(t));){E&&(E=!1,v=new H(r,e),v.start=g,v.sn=c,v.cc=m,v.level=i,u&&(v.initSegment=u,v.rawProgramDateTime=u.rawProgramDateTime,u.rawProgramDateTime=null,A&&(v.setByteRange(A),A=null)));const t=l[1];if(t){v.duration=parseFloat(t);const e=(" "+l[2]).slice(1);v.title=e||null,v.tagList.push(e?["INF",t,e]:["INF",t])}else if(l[3]){if(S(v.duration)){v.start=g,d&&ke(v,d,a),v.sn=c,v.level=i,v.cc=m,o.push(v);const t=(" "+l[3]).slice(1);v.relurl=te(a,t),Re(v,p),p=v,g+=v.duration,c++,f=0,E=!0}}else if(l[4]){const t=(" "+l[4]).slice(1);p?v.setByteRange(t,p):v.setByteRange(t)}else if(l[5])v.rawProgramDateTime=(" "+l[5]).slice(1),v.tagList.push(["PROGRAM-DATE-TIME",v.rawProgramDateTime]),-1===y&&(y=o.length);else{if(l=l[0].match(ye),!l){_.warn("No matches on slow regex match for level playlist!");continue}for(h=1;h<l.length&&void 0===l[h];h++);const t=(" "+l[h]).slice(1),s=(" "+l[h+1]).slice(1),g=l[h+2]?(" "+l[h+2]).slice(1):"";switch(t){case"PLAYLIST-TYPE":a.type=s.toUpperCase();break;case"MEDIA-SEQUENCE":c=a.startSN=parseInt(s);break;case"SKIP":{const t=new M(s);Zt(a,t,["RECENTLY-REMOVED-DATERANGES"]);const e=t.decimalInteger("SKIPPED-SEGMENTS");if(S(e)){a.skippedSegments=e;for(let t=e;t--;)o.unshift(null);c+=e}const i=t.enumeratedString("RECENTLY-REMOVED-DATERANGES");i&&(a.recentlyRemovedDateranges=i.split("\t"));break}case"TARGETDURATION":a.targetduration=Math.max(parseInt(s),1);break;case"VERSION":a.version=parseInt(s);break;case"INDEPENDENT-SEGMENTS":case"EXTM3U":break;case"ENDLIST":a.live=!1;break;case"#":(s||g)&&v.tagList.push(g?[s,g]:[s]);break;case"DISCONTINUITY":m++,v.tagList.push(["DIS"]);break;case"GAP":v.gap=!0,v.tagList.push([t]);break;case"BITRATE":v.tagList.push([t,s]);break;case"DATERANGE":{const t=new M(s);Zt(a,t,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),Zt(a,t,t.clientAttrs);const e=new F(t,a.dateRanges[t.ID]);e.isValid||a.skippedSegments?a.dateRanges[e.id]=e:_.warn(`Ignoring invalid DATERANGE tag: "${s}"`),v.tagList.push(["EXT-X-DATERANGE",s]);break}case"DEFINE":{const t=new M(s);Zt(a,t,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in t?ie(a,t,n):ee(a,t,e)}break;case"DISCONTINUITY-SEQUENCE":m=parseInt(s);break;case"KEY":{const t=Te(s,e,a);if(t.isSupported()){if("NONE"===t.method){d=void 0;break}d||(d={}),d[t.keyFormat]&&(d=T({},d)),d[t.keyFormat]=t}else _.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${s}"`);break}case"START":a.startTimeOffset=Se(s);break;case"MAP":{const t=new M(s);if(Zt(a,t,["BYTERANGE","URI"]),v.duration){const s=new H(r,e);be(s,t,i,d),u=s,v.initSegment=u,u.rawProgramDateTime&&!v.rawProgramDateTime&&(v.rawProgramDateTime=u.rawProgramDateTime)}else{const e=v.byteRangeEndOffset;if(e){const t=v.byteRangeStartOffset;A=`${e-t}@${t}`}else A=null;be(v,t,i,d),u=v,E=!0}break}case"SERVER-CONTROL":{const t=new M(s);a.canBlockReload=t.bool("CAN-BLOCK-RELOAD"),a.canSkipUntil=t.optionalFloat("CAN-SKIP-UNTIL",0),a.canSkipDateRanges=a.canSkipUntil>0&&t.bool("CAN-SKIP-DATERANGES"),a.partHoldBack=t.optionalFloat("PART-HOLD-BACK",0),a.holdBack=t.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const t=new M(s);a.partTarget=t.decimalFloatingPoint("PART-TARGET");break}case"PART":{let t=a.partList;t||(t=a.partList=[]);const i=f>0?t[t.length-1]:void 0,r=f++,n=new M(s);Zt(a,n,["BYTERANGE","URI"]);const o=new $(n,v,e,r,i);t.push(o),v.duration+=o.duration;break}case"PRELOAD-HINT":{const t=new M(s);Zt(a,t,["URI"]),a.preloadHint=t;break}case"RENDITION-REPORT":{const t=new M(s);Zt(a,t,["URI"]),a.renditionReports=a.renditionReports||[],a.renditionReports.push(t);break}default:_.warn(`line parsed but not handled: ${l}`)}}}p&&!p.relurl?(o.pop(),g-=p.duration,a.partList&&(a.fragmentHint=p)):a.partList&&(Re(v,p),v.cc=m,a.fragmentHint=v,d&&ke(v,d,a));const L=o.length,R=o[0],b=o[L-1];if(g+=a.skippedSegments*a.targetduration,g>0&&L&&b){a.averagetargetduration=g/L;const t=b.sn;a.endSN="initSegment"!==t?t:0,a.live||(b.endList=!0),R&&(a.startCC=R.cc)}else a.endSN=0,a.startCC=0;return a.fragmentHint&&(g+=a.fragmentHint.duration),a.totalduration=g,a.endCC=m,y>0&&function(t,e){let i=t[e];for(let r=e;r--;){const e=t[r];if(!e)return;e.programDateTime=i.programDateTime-1e3*e.duration,i=e}}(o,y),a}}function Te(t,e,i){var r,s;const n=new M(t);Zt(i,n,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const a=null!=(r=n.METHOD)?r:"",o=n.URI,l=n.hexadecimalInteger("IV"),h=n.KEYFORMATVERSIONS,d=null!=(s=n.KEYFORMAT)?s:"identity";o&&n.IV&&!l&&_.error(`Invalid IV: ${n.IV}`);const u=o?Ee.resolve(o,e):"",c=(h||"1").split("/").map(Number).filter(Number.isFinite);return new zt(a,u,d,c,l)}function Se(t){const e=new M(t).decimalFloatingPoint("TIME-OFFSET");return S(e)?e:null}function Ae(t,e){let i=(t||"").split(/[ ,]+/).filter((t=>t));["video","audio","text"].forEach((t=>{const r=i.filter((e=>function(t,e){const i=se[e];return!!i&&!!i[t.slice(0,4)]}(e,t)));r.length&&(e[`${t}Codec`]=r.join(","),i=i.filter((t=>-1===r.indexOf(t))))})),e.unknownCodecs=i}function Le(t,e,i){const r=e[i];r&&(t[i]=r)}function Re(t,e){t.rawProgramDateTime?t.programDateTime=Date.parse(t.rawProgramDateTime):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime),S(t.programDateTime)||(t.programDateTime=null,t.rawProgramDateTime=null)}function be(t,e,i,r){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=i,t.sn="initSegment",r&&(t.levelkeys=r),t.initSegment=null}function ke(t,e,i){t.levelkeys=e;const{encryptedFragments:r}=i;r.length&&r[r.length-1].levelkeys===e||!Object.keys(e).some((t=>e[t].isCommonEncryption))||r.push(t)}var De="manifest",Ie="level",we="audioTrack",Ce="subtitleTrack",_e="main",Pe="audio",xe="subtitle";function Me(t){const{type:e}=t;switch(e){case we:return Pe;case Ce:return xe;default:return _e}}function Oe(t,e){let i=t.url;return void 0!==i&&0!==i.indexOf("data:")||(i=e.url),i}class Fe{constructor(t){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=t,this.registerListeners()}startLoad(t){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:t}=this;t.on(R.MANIFEST_LOADING,this.onManifestLoading,this),t.on(R.LEVEL_LOADING,this.onLevelLoading,this),t.on(R.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(R.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:t}=this;t.off(R.MANIFEST_LOADING,this.onManifestLoading,this),t.off(R.LEVEL_LOADING,this.onLevelLoading,this),t.off(R.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(R.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(t){const e=this.hls.config,i=e.pLoader,r=e.loader,s=new(i||r)(e);return this.loaders[t.type]=s,s}getInternalLoader(t){return this.loaders[t.type]}resetInternalLoader(t){this.loaders[t]&&delete this.loaders[t]}destroyInternalLoaders(){for(const t in this.loaders){const e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(t,e){const{url:i}=e;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:De,url:i,deliveryDirectives:null})}onLevelLoading(t,e){const{id:i,level:r,pathwayId:s,url:n,deliveryDirectives:a}=e;this.load({id:i,level:r,pathwayId:s,responseType:"text",type:Ie,url:n,deliveryDirectives:a})}onAudioTrackLoading(t,e){const{id:i,groupId:r,url:s,deliveryDirectives:n}=e;this.load({id:i,groupId:r,level:null,responseType:"text",type:we,url:s,deliveryDirectives:n})}onSubtitleTrackLoading(t,e){const{id:i,groupId:r,url:s,deliveryDirectives:n}=e;this.load({id:i,groupId:r,level:null,responseType:"text",type:Ce,url:s,deliveryDirectives:n})}load(t){var e;const i=this.hls.config;let r,s=this.getInternalLoader(t);if(s){const e=s.context;if(e&&e.url===t.url&&e.level===t.level)return void _.trace("[playlist-loader]: playlist request ongoing");_.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),s.abort()}if(r=t.type===De?i.manifestLoadPolicy.default:T({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(t),S(null==(e=t.deliveryDirectives)?void 0:e.part)){let e;if(t.type===Ie&&null!==t.level?e=this.hls.levels[t.level].details:t.type===we&&null!==t.id?e=this.hls.audioTracks[t.id].details:t.type===Ce&&null!==t.id&&(e=this.hls.subtitleTracks[t.id].details),e){const t=e.partTarget,i=e.targetduration;if(t&&i){const e=1e3*Math.max(3*t,.8*i);r=T({},r,{maxTimeToFirstByteMs:Math.min(e,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(e,r.maxTimeToFirstByteMs)})}}}const n=r.errorRetry||r.timeoutRetry||{},a={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},o={onSuccess:(t,e,i,r)=>{const s=this.getInternalLoader(i);this.resetInternalLoader(i.type);const n=t.data;0===n.indexOf("#EXTM3U")?(e.parsing.start=performance.now(),Ee.isMediaPlaylist(n)?this.handleTrackOrLevelPlaylist(t,e,i,r||null,s):this.handleMasterPlaylist(t,e,i,r)):this.handleManifestParsingError(t,i,new Error("no EXTM3U delimiter"),r||null,e)},onError:(t,e,i,r)=>{this.handleNetworkError(e,i,!1,t,r)},onTimeout:(t,e,i)=>{this.handleNetworkError(e,i,!0,void 0,t)}};s.load(t,a,o)}handleMasterPlaylist(t,e,i,r){const s=this.hls,n=t.data,a=Oe(t,i),o=Ee.parseMasterPlaylist(n,a);if(o.playlistParsingError)return void this.handleManifestParsingError(t,i,o.playlistParsingError,r,e);const{contentSteering:l,levels:h,sessionData:d,sessionKeys:u,startTimeOffset:c,variableList:f}=o;this.variableList=f;const{AUDIO:g=[],SUBTITLES:m,"CLOSED-CAPTIONS":p}=Ee.parseMasterPlaylistMedia(n,a,o);if(g.length){g.some((t=>!t.url))||!h[0].audioCodec||h[0].attrs.AUDIO||(_.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new M({}),bitrate:0,url:""}))}s.trigger(R.MANIFEST_LOADED,{levels:h,audioTracks:g,subtitles:m,captions:p,contentSteering:l,url:a,stats:e,networkDetails:r,sessionData:d,sessionKeys:u,startTimeOffset:c,variableList:f})}handleTrackOrLevelPlaylist(t,e,i,r,s){const n=this.hls,{id:a,level:o,type:l}=i,h=Oe(t,i),d=S(o)?o:S(a)?a:0,u=Me(i),c=Ee.parseLevelPlaylist(t.data,h,d,u,0,this.variableList);if(l===De){const t={attrs:new M({}),bitrate:0,details:c,name:"",url:h};n.trigger(R.MANIFEST_LOADED,{levels:[t],audioTracks:[],url:h,stats:e,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),i.levelDetails=c,this.handlePlaylistLoaded(c,t,e,i,r,s)}handleManifestParsingError(t,e,i,r,s){this.hls.trigger(R.ERROR,{type:b.NETWORK_ERROR,details:k.MANIFEST_PARSING_ERROR,fatal:e.type===De,url:t.url,err:i,error:i,reason:i.message,response:t,context:e,networkDetails:r,stats:s})}handleNetworkError(t,e,i=!1,r,s){let n=`A network ${i?"timeout":"error"+(r?" (status "+r.code+")":"")} occurred while loading ${t.type}`;t.type===Ie?n+=`: ${t.level} id: ${t.id}`:t.type!==we&&t.type!==Ce||(n+=` id: ${t.id} group-id: "${t.groupId}"`);const a=new Error(n);_.warn(`[playlist-loader]: ${n}`);let o=k.UNKNOWN,l=!1;const h=this.getInternalLoader(t);switch(t.type){case De:o=i?k.MANIFEST_LOAD_TIMEOUT:k.MANIFEST_LOAD_ERROR,l=!0;break;case Ie:o=i?k.LEVEL_LOAD_TIMEOUT:k.LEVEL_LOAD_ERROR,l=!1;break;case we:o=i?k.AUDIO_TRACK_LOAD_TIMEOUT:k.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case Ce:o=i?k.SUBTITLE_TRACK_LOAD_TIMEOUT:k.SUBTITLE_LOAD_ERROR,l=!1}h&&this.resetInternalLoader(t.type);const d={type:b.NETWORK_ERROR,details:o,fatal:l,url:t.url,loader:h,context:t,error:a,networkDetails:e,stats:s};if(r){const i=(null==e?void 0:e.url)||t.url;d.response=v({url:i,data:void 0},r)}this.hls.trigger(R.ERROR,d)}handlePlaylistLoaded(t,e,i,r,s,n){const a=this.hls,{type:o,level:l,id:h,groupId:d,deliveryDirectives:u}=r,c=Oe(e,r),f=Me(r),g="number"==typeof r.level&&f===_e?l:void 0;if(!t.fragments.length){const t=new Error("No Segments found in Playlist");return void a.trigger(R.ERROR,{type:b.NETWORK_ERROR,details:k.LEVEL_EMPTY_ERROR,fatal:!1,url:c,error:t,reason:t.message,response:e,context:r,level:g,parent:f,networkDetails:s,stats:i})}t.targetduration||(t.playlistParsingError=new Error("Missing Target Duration"));const m=t.playlistParsingError;if(m)a.trigger(R.ERROR,{type:b.NETWORK_ERROR,details:k.LEVEL_PARSING_ERROR,fatal:!1,url:c,error:m,reason:m.message,response:e,context:r,level:g,parent:f,networkDetails:s,stats:i});else switch(t.live&&n&&(n.getCacheAge&&(t.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(t.ageHeader)||(t.ageHeader=0)),o){case De:case Ie:a.trigger(R.LEVEL_LOADED,{details:t,level:g||0,id:h||0,stats:i,networkDetails:s,deliveryDirectives:u});break;case we:a.trigger(R.AUDIO_TRACK_LOADED,{details:t,id:h||0,groupId:d||"",stats:i,networkDetails:s,deliveryDirectives:u});break;case Ce:a.trigger(R.SUBTITLE_TRACK_LOADED,{details:t,id:h||0,groupId:d||"",stats:i,networkDetails:s,deliveryDirectives:u})}}}function Ne(t,e){let i;try{i=new Event("addtrack")}catch(t){i=document.createEvent("Event"),i.initEvent("addtrack",!1,!1)}i.track=t,e.dispatchEvent(i)}function Ue(t,e){const i=t.mode;if("disabled"===i&&(t.mode="hidden"),t.cues&&!t.cues.getCueById(e.id))try{if(t.addCue(e),!t.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(i){_.debug(`[texttrack-utils]: ${i}`);try{const i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,t.addCue(i)}catch(t){_.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${t}`)}}"disabled"===i&&(t.mode=i)}function Be(t){const e=t.mode;if("disabled"===e&&(t.mode="hidden"),t.cues)for(let e=t.cues.length;e--;)t.removeCue(t.cues[e]);"disabled"===e&&(t.mode=e)}function Ge(t,e,i,r){const s=t.mode;if("disabled"===s&&(t.mode="hidden"),t.cues&&t.cues.length>0){const s=function(t,e,i){const r=[],s=function(t,e){if(e<t[0].startTime)return 0;const i=t.length-1;if(e>t[i].endTime)return-1;let r=0,s=i;for(;r<=s;){const n=Math.floor((s+r)/2);if(e<t[n].startTime)s=n-1;else{if(!(e>t[n].startTime&&r<i))return n;r=n+1}}return t[r].startTime-e<e-t[s].startTime?r:s}(t,e);if(s>-1)for(let n=s,a=t.length;n<a;n++){const s=t[n];if(s.startTime>=e&&s.endTime<=i)r.push(s);else if(s.startTime>i)return r}return r}(t.cues,e,i);for(let e=0;e<s.length;e++)r&&!r(s[e])||t.removeCue(s[e])}"disabled"===s&&(t.mode=s)}function Ke(t){const e=[];for(let i=0;i<t.length;i++){const r=t[i];"subtitles"!==r.kind&&"captions"!==r.kind||!r.label||e.push(t[i])}return e}var He="org.id3",$e="com.apple.quicktime.HLS",Ve="https://aomedia.org/emsg/ID3";function Ye(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function We(t,e,i,r,s){let n=new t(e,i,"");try{n.value=r,s&&(n.type=s)}catch(a){n=new t(e,i,JSON.stringify(s?v({type:s},r):r))}return n}const je=(()=>{const t=Ye();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function qe(t,e){return t.getTime()/1e3-e}class Xe{constructor(t){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=t,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null}_registerListeners(){const{hls:t}=this;t.on(R.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(R.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(R.MANIFEST_LOADING,this.onManifestLoading,this),t.on(R.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(R.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(R.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:t}=this;t.off(R.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(R.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(R.MANIFEST_LOADING,this.onManifestLoading,this),t.off(R.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(R.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(R.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(t,e){this.media=e.media}onMediaDetaching(){this.id3Track&&(Be(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(t){const e=this.getID3Track(t.textTracks);return e.mode="hidden",e}getID3Track(t){if(this.media){for(let e=0;e<t.length;e++){const i=t[e];if("metadata"===i.kind&&"id3"===i.label)return Ne(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(t,e){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:i,enableID3MetadataCues:r}}}=this;if(!i&&!r)return;const{samples:s}=e;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=Ye();if(n)for(let t=0;t<s.length;t++){const e=s[t].type;if(e===Ve&&!i||!r)continue;const a=mt(s[t].data);if(a){const i=s[t].pts;let r=i+s[t].duration;r>je&&(r=je);r-i<=0&&(r=i+.25);for(let t=0;t<a.length;t++){const s=a[t];if(!ft(s)){this.updateId3CueEnds(i,e);const t=We(n,i,r,s,e);t&&this.id3Track.addCue(t)}}}}}updateId3CueEnds(t,e){var i;const r=null==(i=this.id3Track)?void 0:i.cues;if(r)for(let i=r.length;i--;){const s=r[i];s.type===e&&s.startTime<t&&s.endTime===je&&(s.endTime=t)}}onBufferFlushing(t,{startOffset:e,endOffset:i,type:r}){const{id3Track:s,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=n;if(s&&(a||o)){let t;t="audio"===r?t=>t.type===He&&o:"video"===r?t=>t.type===Ve&&a:t=>t.type===He&&o||t.type===Ve&&a,Ge(s,e,i,t)}}onLevelUpdated(t,{details:e}){if(!this.media||!e.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:i,id3Track:r}=this,{dateRanges:s}=e,n=Object.keys(s);if(r){const t=Object.keys(i).filter((t=>!n.includes(t)));for(let e=t.length;e--;){const s=t[e];Object.keys(i[s].cues).forEach((t=>{r.removeCue(i[s].cues[t])})),delete i[s]}}const a=e.fragments[e.fragments.length-1];if(0===n.length||!S(null==a?void 0:a.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const o=a.programDateTime/1e3-a.start,l=Ye();for(let t=0;t<n.length;t++){const e=n[t],r=s[e],a=qe(r.startDate,o),u=i[e],c=(null==u?void 0:u.cues)||{};let f=(null==u?void 0:u.durationKnown)||!1,g=je;const m=r.endDate;if(m)g=qe(m,o),f=!0;else if(r.endOnNext&&!f){const t=n.reduce(((t,e)=>{if(e!==r.id){const i=s[e];if(i.class===r.class&&i.startDate>r.startDate&&(!t||r.startDate<t.startDate))return i}return t}),null);t&&(g=qe(t.startDate,o),f=!0)}const p=Object.keys(r.attr);for(let t=0;t<p.length;t++){const i=p[t];if("ID"===(d=i)||"CLASS"===d||"START-DATE"===d||"DURATION"===d||"END-DATE"===d||"END-ON-NEXT"===d)continue;const s=c[i];if(s)f&&!u.durationKnown&&(s.endTime=g);else if(l){let t=r.attr[i];O(i)&&(h=t,t=Uint8Array.from(h.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer);const s=We(l,a,g,{key:i,data:t},$e);s&&(s.id=e,this.id3Track.addCue(s),c[i]=s)}}i[e]={cues:c,dateRange:r,durationKnown:f}}var h,d}}class ze{constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.levelDetails=null,this.currentTime=0,this.stallCount=0,this._latency=null,this.timeupdateHandler=()=>this.timeupdate(),this.hls=t,this.config=t.config,this.registerListeners()}get latency(){return this._latency||0}get maxLatency(){const{config:t,levelDetails:e}=this;return void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:e?t.liveMaxLatencyDurationCount*e.targetduration:0}get targetLatency(){const{levelDetails:t}=this;if(null===t)return null;const{holdBack:e,partHoldBack:i,targetduration:r}=t,{liveSyncDuration:s,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&i||e;(o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==s?s:n*r);const h=r;return l+Math.min(1*this.stallCount,h)}get liveSyncPosition(){const t=this.estimateLiveEdge(),e=this.targetLatency,i=this.levelDetails;if(null===t||null===e||null===i)return null;const r=i.edge,s=t-e-this.edgeStalled,n=r-i.totalduration,a=r-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(n,s),a)}get drift(){const{levelDetails:t}=this;return null===t?1:t.drift}get edgeStalled(){const{levelDetails:t}=this;if(null===t)return 0;const e=3*(this.config.lowLatencyMode&&t.partTarget||t.targetduration);return Math.max(t.age-e,0)}get forwardBufferLength(){const{media:t,levelDetails:e}=this;if(!t||!e)return 0;const i=t.buffered.length;return(i?t.buffered.end(i-1):e.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(R.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(R.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(R.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(R.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(R.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(R.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(R.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(R.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(R.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(R.ERROR,this.onError,this)}onMediaAttached(t,e){this.media=e.media,this.media.addEventListener("timeupdate",this.timeupdateHandler)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.timeupdateHandler),this.media=null)}onManifestLoading(){this.levelDetails=null,this._latency=null,this.stallCount=0}onLevelUpdated(t,{details:e}){this.levelDetails=e,e.advanced&&this.timeupdate(),!e.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(t,e){var i;e.details===k.BUFFER_STALLED_ERROR&&(this.stallCount++,null!=(i=this.levelDetails)&&i.live&&_.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}timeupdate(){const{media:t,levelDetails:e}=this;if(!t||!e)return;this.currentTime=t.currentTime;const i=this.computeLatency();if(null===i)return;this._latency=i;const{lowLatencyMode:r,maxLiveSyncPlaybackRate:s}=this.config;if(!r||1===s||!e.live)return;const n=this.targetLatency;if(null===n)return;const a=i-n;if(a<Math.min(this.maxLatency,n+e.targetduration)&&a>.05&&this.forwardBufferLength>1){const e=Math.min(2,Math.max(1,s)),i=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20;t.playbackRate=Math.min(e,Math.max(1,i))}else 1!==t.playbackRate&&0!==t.playbackRate&&(t.playbackRate=1)}estimateLiveEdge(){const{levelDetails:t}=this;return null===t?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return null===t?null:t-this.currentTime}}const Qe=["NONE","TYPE-0","TYPE-1",null];const Je=["SDR","PQ","HLG"];var Ze="",ti="YES",ei="v2";function ii(t){const{canSkipUntil:e,canSkipDateRanges:i,age:r}=t;return e&&r<e/2?i?ei:ti:Ze}class ri{constructor(t,e,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=e,this.skip=i}addDirectives(t){const e=new self.URL(t);return void 0!==this.msn&&e.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&e.searchParams.set("_HLS_part",this.part.toString()),this.skip&&e.searchParams.set("_HLS_skip",this.skip),e.href}}class si{constructor(t){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.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[t.url],this._attrs=[t.attrs],this.bitrate=t.bitrate,t.details&&(this.details=t.details),this.id=t.id||0,this.name=t.name,this.width=t.width||0,this.height=t.height||0,this.frameRate=t.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=t.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,this.codecSet=[t.videoCodec,t.audioCodec].filter((t=>!!t)).map((t=>t.substring(0,4))).join(","),this.addGroupId("audio",t.attrs.AUDIO),this.addGroupId("text",t.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(t){return ni(this._audioGroups,t)}hasSubtitleGroup(t){return ni(this._subtitleGroups,t)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(t,e){if(e)if("audio"===t){let t=this._audioGroups;t||(t=this._audioGroups=[]),-1===t.indexOf(e)&&t.push(e)}else if("text"===t){let t=this._subtitleGroups;t||(t=this._subtitleGroups=[]),-1===t.indexOf(e)&&t.push(e)}}get urlId(){return 0}set urlId(t){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var t;return null==(t=this.audioGroups)?void 0:t[0]}get textGroupId(){var t;return null==(t=this.subtitleGroups)?void 0:t[0]}addFallback(){}}function ni(t,e){return!(!e||!t)&&-1!==t.indexOf(e)}function ai(t,e){const i=e.startPTS;if(S(i)){let r,s=0;e.sn>t.sn?(s=i-t.start,r=t):(s=t.start-i,r=e),r.duration!==s&&(r.duration=s)}else if(e.sn>t.sn){t.cc===e.cc&&t.minEndPTS?e.start=t.start+(t.minEndPTS-t.start):e.start=t.start+t.duration}else e.start=Math.max(t.start-e.duration,0)}function oi(t,e,i,r,s,n){r-i<=0&&(_.warn("Fragment should have a positive duration",e),r=i+e.duration,n=s+e.duration);let a=i,o=r;const l=e.startPTS,h=e.endPTS;if(S(l)){const t=Math.abs(l-i);S(e.deltaPTS)?e.deltaPTS=Math.max(t,e.deltaPTS):e.deltaPTS=t,a=Math.max(i,l),i=Math.min(i,l),s=Math.min(s,e.startDTS),o=Math.min(r,h),r=Math.max(r,h),n=Math.max(n,e.endDTS)}const d=i-e.start;0!==e.start&&(e.start=i),e.duration=r-e.start,e.startPTS=i,e.maxStartPTS=a,e.startDTS=s,e.endPTS=r,e.minEndPTS=o,e.endDTS=n;const u=e.sn;if(!t||u<t.startSN||u>t.endSN)return 0;let c;const f=u-t.startSN,g=t.fragments;for(g[f]=e,c=f;c>0;c--)ai(g[c],g[c-1]);for(c=f;c<g.length-1;c++)ai(g[c],g[c+1]);return t.fragmentHint&&ai(g[g.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,d}function li(t,e){let i=null;const r=t.fragments;for(let t=r.length-1;t>=0;t--){const e=r[t].initSegment;if(e){i=e;break}}t.fragmentHint&&delete t.fragmentHint.endPTS;let s,n=0;if(function(t,e,i){const r=e.skippedSegments,s=Math.max(t.startSN,e.startSN)-e.startSN,n=(t.fragmentHint?1:0)+(r?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,a=e.startSN-t.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments;for(let t=s;t<=n;t++){const s=l[a+t];let n=o[t];r&&!n&&t<r&&(n=e.fragments[t]=s),s&&n&&i(s,n)}}(t,e,((t,r)=>{t.relurl&&(n=t.cc-r.cc),S(t.startPTS)&&S(t.endPTS)&&(r.start=r.startPTS=t.startPTS,r.startDTS=t.startDTS,r.maxStartPTS=t.maxStartPTS,r.endPTS=t.endPTS,r.endDTS=t.endDTS,r.minEndPTS=t.minEndPTS,r.duration=t.endPTS-t.startPTS,r.duration&&(s=r),e.PTSKnown=e.alignedSliding=!0),r.elementaryStreams=t.elementaryStreams,r.loader=t.loader,r.stats=t.stats,t.initSegment&&(r.initSegment=t.initSegment,i=t.initSegment)})),i){(e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments).forEach((t=>{var e;!t||t.initSegment&&t.initSegment.relurl!==(null==(e=i)?void 0:e.relurl)||(t.initSegment=i)}))}if(e.skippedSegments)if(e.deltaUpdateFailed=e.fragments.some((t=>!t)),e.deltaUpdateFailed){_.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let t=e.skippedSegments;t--;)e.fragments.shift();e.startSN=e.fragments[0].sn,e.startCC=e.fragments[0].cc}else e.canSkipDateRanges&&(e.dateRanges=function(t,e,i){const r=T({},t);i&&i.forEach((t=>{delete r[t]}));return Object.keys(e).forEach((t=>{const i=new F(e[t].attr,r[t]);i.isValid?r[t]=i:_.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(e[t].attr)}"`)})),r}(t.dateRanges,e.dateRanges,e.recentlyRemovedDateranges));const a=e.fragments;if(n){_.warn("discontinuity sliding from playlist, take drift into account");for(let t=0;t<a.length;t++)a[t].cc+=n}e.skippedSegments&&(e.startCC=e.fragments[0].cc),function(t,e,i){if(t&&e){let r=0;for(let s=0,n=t.length;s<=n;s++){const n=t[s],a=e[s+r];n&&a&&n.index===a.index&&n.fragment.sn===a.fragment.sn?i(n,a):r--}}}(t.partList,e.partList,((t,e)=>{e.elementaryStreams=t.elementaryStreams,e.stats=t.stats})),s?oi(e,s,s.startPTS,s.endPTS,s.startDTS,s.endDTS):hi(t,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=t.driftStartTime,e.driftStart=t.driftStart;const o=e.advancedDateTime;if(e.advanced&&o){const t=e.edge;e.driftStart||(e.driftStartTime=o,e.driftStart=t),e.driftEndTime=o,e.driftEnd=t}else e.driftEndTime=t.driftEndTime,e.driftEnd=t.driftEnd,e.advancedDateTime=t.advancedDateTime}function hi(t,e){const i=e.startSN+e.skippedSegments-t.startSN,r=t.fragments;i<0||i>=r.length||di(e,r[i].start)}function di(t,e){if(e){const i=t.fragments;for(let r=t.skippedSegments;r<i.length;r++)i[r].start+=e;t.fragmentHint&&(t.fragmentHint.start+=e)}}function ui(t,e,i){var r;return null!=t&&t.details?ci(null==(r=t.details)?void 0:r.partList,e,i):null}function ci(t,e,i){if(t)for(let r=t.length;r--;){const s=t[r];if(s.index===i&&s.fragment.sn===e)return s}return null}function fi(t){t.forEach(((t,e)=>{const{details:i}=t;null!=i&&i.fragments&&i.fragments.forEach((t=>{t.level=e}))}))}function gi(t){switch(t.details){case k.FRAG_LOAD_TIMEOUT:case k.KEY_LOAD_TIMEOUT:case k.LEVEL_LOAD_TIMEOUT:case k.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function mi(t,e){const i=gi(e);return t.default[(i?"timeout":"error")+"Retry"]}function pi(t,e){const i="linear"===t.backoff?1:Math.pow(2,e);return Math.min(i*t.retryDelayMs,t.maxRetryDelayMs)}function vi(t){return v(v({},t),{errorRetry:null,timeoutRetry:null})}function yi(t,e,i,r){if(!t)return!1;const s=null==r?void 0:r.code,n=e<t.maxNumRetry&&(function(t){return 0===t&&!1===navigator.onLine||!!t&&(t<400||t>499)}(s)||!!i);return t.shouldRetry?t.shouldRetry(t,e,i,r,n):n}const Ei=function(t,e){let i=0,r=t.length-1,s=null,n=null;for(;i<=r;){s=(i+r)/2|0,n=t[s];const a=e(n);if(a>0)i=s+1;else{if(!(a<0))return n;r=s-1}}return null};function Ti(t,e,i=0,r=0,s=.005){let n=null;if(t){n=e[t.sn-e[0].sn+1]||null;const r=t.endDTS-i;r>0&&r<15e-7&&(i+=15e-7)}else 0===i&&0===e[0].start&&(n=e[0]);if(n&&((!t||t.level===n.level)&&0===Si(i,r,n)||function(t,e,i){if(e&&0===e.start&&e.level<t.level&&(e.endPTS||0)>0){const r=e.tagList.reduce(((t,e)=>("INF"===e[0]&&(t+=parseFloat(e[1])),t)),i);return t.start<=r}return!1}(n,t,Math.min(s,r))))return n;const a=Ei(e,Si.bind(null,i,r));return!a||a===t&&n?n:a}function Si(t=0,e=0,i){if(i.start<=t&&i.start+i.duration>t)return 0;const r=Math.min(e,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-r<=t?1:i.start-r>t&&i.start?-1:0}function Ai(t,e,i){const r=1e3*Math.min(e,i.duration+(i.deltaPTS?i.deltaPTS:0));return(i.endProgramDateTime||0)-r>t}var Li=0,Ri=2,bi=3,ki=5,Di=0,Ii=1,wi=2;class Ci{constructor(t,e){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=_.log.bind(_,`${e}:`),this.warn=_.warn.bind(_,`${e}:`),this.hls=t}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.requestScheduled=-1,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(t,e,i){const r=null==e?void 0:e.renditionReports;if(r){let s=-1;for(let i=0;i<r.length;i++){const n=r[i];let a;try{a=new self.URL(n.URI,e.url).href}catch(t){_.warn(`Could not construct new URL for Rendition Report: ${t}`),a=n.URI||""}if(a===t){s=i;break}a===t.substring(0,a.length)&&(s=i)}if(-1!==s){const t=r[s],n=parseInt(t["LAST-MSN"])||(null==e?void 0:e.lastPartSn);let a=parseInt(t["LAST-PART"])||(null==e?void 0:e.lastPartIndex);if(this.hls.config.lowLatencyMode){const t=Math.min(e.age-e.partTarget,e.targetduration);a>=0&&t>e.partTarget&&(a+=1)}const o=i&&ii(i);return new ri(n,a>=0?a:void 0,o)}}}loadPlaylist(t){-1===this.requestScheduled&&(this.requestScheduled=self.performance.now())}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}shouldReloadPlaylist(t){return-1===this.timer&&-1===this.requestScheduled&&this.shouldLoadPlaylist(t)}playlistLoaded(t,e,i){const{details:r,stats:s}=e,n=self.performance.now(),a=s.loading.first?Math.max(0,n-s.loading.first):0;if(r.advancedDateTime=Date.now()-a,r.live||null!=i&&i.live){if(r.reloaded(i),i&&this.log(`live playlist ${t} ${r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:r.updated?"UPDATED":"MISSED"}`),i&&r.fragments.length>0&&li(i,r),!this.canLoad||!r.live)return;let a,o,l;if(r.canBlockReload&&r.endSN&&r.advanced){const t=this.hls.config.lowLatencyMode,s=r.lastPartSn,n=r.endSN,h=r.lastPartIndex,d=s===n;-1!==h?(o=d?n+1:s,l=d?t?0:h:h+1):o=n+1;const u=r.age,c=u+r.ageHeader;let f=Math.min(c-r.partTarget,1.5*r.targetduration);if(f>0){if(i&&f>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${f} with playlist age: ${r.age}`),f=0;else{const t=Math.floor(f/r.targetduration);if(o+=t,void 0!==l){l+=Math.round(f%r.targetduration/r.partTarget)}this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${u.toFixed(2)}s goal: ${f} skip sn ${t} to part ${l}`)}r.tuneInGoal=f}if(a=this.getDeliveryDirectives(r,e.deliveryDirectives,o,l),t||!d)return void this.loadPlaylist(a)}else(r.canBlockReload||r.canSkipUntil)&&(a=this.getDeliveryDirectives(r,e.deliveryDirectives,o,l));const h=this.hls.mainForwardBufferInfo,d=h?h.end-h.len:0,u=function(t,e=1/0){let i=1e3*t.targetduration;if(t.updated){const r=t.fragments,s=4;if(r.length&&i*s>e){const t=1e3*r[r.length-1].duration;t<i&&(i=t)}}else i/=2;return Math.round(i)}(r,1e3*(r.edge-d));r.updated&&n>this.requestScheduled+u&&(this.requestScheduled=s.loading.start),void 0!==o&&r.canBlockReload?this.requestScheduled=s.loading.first+u-(1e3*r.partTarget||1e3):-1===this.requestScheduled||this.requestScheduled+u<n?this.requestScheduled=n:this.requestScheduled-n<=0&&(this.requestScheduled+=u);let c=this.requestScheduled-n;c=Math.max(0,c),this.log(`reload live playlist ${t} in ${Math.round(c)} ms`),this.timer=self.setTimeout((()=>this.loadPlaylist(a)),c)}else this.clearTimer()}getDeliveryDirectives(t,e,i,r){let s=ii(t);return null!=e&&e.skip&&t.deltaUpdateFailed&&(i=e.msn,r=e.part,s=Ze),new ri(i,r,s)}checkRetry(t){const e=t.details,i=gi(t),r=t.errorAction,{action:s,retryCount:n=0,retryConfig:a}=r||{},o=!!r&&!!a&&(s===ki||!r.resolved&&s===Ri);if(o){var l;if(this.requestScheduled=-1,n>=a.maxNumRetry)return!1;if(i&&null!=(l=t.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" without delivery-directives`),this.loadPlaylist();else{const t=pi(a,n);this.timer=self.setTimeout((()=>this.loadPlaylist()),t),this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" in ${t}ms`)}t.levelRetry=!0,r.resolved=!0}return o}}class _i{constructor(t,e=0,i=0){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_=e,this.totalWeight_=i}sample(t,e){const i=Math.pow(this.alpha_,t);this.estimate_=e*(1-i)+i*this.estimate_,this.totalWeight_+=t}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_}}class Pi{constructor(t,e,i,r=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new _i(t),this.fast_=new _i(e),this.defaultTTFB_=r,this.ttfb_=new _i(t)}update(t,e){const{slow_:i,fast_:r,ttfb_:s}=this;i.halfLife!==t&&(this.slow_=new _i(t,i.getEstimate(),i.getTotalWeight())),r.halfLife!==e&&(this.fast_=new _i(e,r.getEstimate(),r.getTotalWeight())),s.halfLife!==t&&(this.ttfb_=new _i(t,s.getEstimate(),s.getTotalWeight()))}sample(t,e){const i=(t=Math.max(t,this.minDelayMs_))/1e3,r=8*e/i;this.fast_.sample(i,r),this.slow_.sample(i,r)}sampleTTFB(t){const e=t/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(e,2)/2);this.ttfb_.sample(i,Math.max(t,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}destroy(){}}const xi={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},Mi={};function Oi(t,e,i,r,s,n){const a=t.audioCodec?t.audioGroups:null,o=null==n?void 0:n.audioCodec,l=null==n?void 0:n.channels,h=l?parseInt(l):o?1/0:2;let d=null;if(null!=a&&a.length)try{d=1===a.length&&a[0]?e.groups[a[0]].channels:a.reduce(((t,i)=>{if(i){const r=e.groups[i];if(!r)throw new Error(`Audio track group ${i} not found`);Object.keys(r.channels).forEach((e=>{t[e]=(t[e]||0)+r.channels[e]}))}return t}),{2:0})}catch(t){return!0}return void 0!==t.videoCodec&&(t.width>1920&&t.height>1088||t.height>1920&&t.width>1088||t.frameRate>Math.max(r,30)||"SDR"!==t.videoRange&&t.videoRange!==i||t.bitrate>Math.max(s,8e6))||!!d&&S(h)&&Object.keys(d).some((t=>parseInt(t)>h))}function Fi(t,e,i){const r=t.videoCodec,s=t.audioCodec;if(!r||!s||!i)return Promise.resolve(xi);const n={width:t.width,height:t.height,bitrate:Math.ceil(Math.max(.9*t.bitrate,t.averageBitrate)),framerate:t.frameRate||30},a=t.videoRange;"SDR"!==a&&(n.transferFunction=a.toLowerCase());const o=r.split(",").map((t=>({type:"media-source",video:v(v({},n),{},{contentType:oe(t,"video")})})));return s&&t.audioGroups&&t.audioGroups.forEach((t=>{var i;t&&(null==(i=e.groups[t])||i.tracks.forEach((e=>{if(e.groupId===t){const t=e.channels||"",i=parseFloat(t);S(i)&&i>2&&o.push.apply(o,s.split(",").map((t=>({type:"media-source",audio:{contentType:oe(t,"audio"),channels:""+i}}))))}})))})),Promise.all(o.map((t=>{const e=function(t){const{audio:e,video:i}=t,r=i||e;if(r){const t=r.contentType.split('"')[1];if(i)return`r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${t}_${Math.ceil(i.bitrate/1e5)}`;if(e)return`c${e.channels}${e.spatialRendering?"s":"n"}_${t}`}return""}(t);return Mi[e]||(Mi[e]=i.decodingInfo(t))}))).then((t=>({supported:!t.some((t=>!t.supported)),configurations:o,decodingInfoResults:t}))).catch((t=>({supported:!1,configurations:o,decodingInfoResults:[],error:t})))}function Ni(t,e){let i=!1,r=[];return t&&(i="SDR"!==t,r=[t]),e&&(r=e.allowedVideoRanges||Je.slice(0),i=void 0!==e.preferHDR?e.preferHDR:function(){if("function"==typeof matchMedia){const t=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(t.media!==e.media)return!0===t.matches}return!1}(),r=i?r.filter((t=>"SDR"!==t)):["SDR"]),{preferHDR:i,allowedVideoRanges:r}}function Ui(t,e){_.log(`[abr] start candidates with "${t}" ignored because ${e}`)}function Bi(t,e,i){if("attrs"in t){const i=e.indexOf(t);if(-1!==i)return i}for(let r=0;r<e.length;r++){if(Gi(t,e[r],i))return r}return-1}function Gi(t,e,i){const{groupId:r,name:s,lang:n,assocLang:a,characteristics:o,default:l}=t,h=t.forced;return(void 0===r||e.groupId===r)&&(void 0===s||e.name===s)&&(void 0===n||e.lang===n)&&(void 0===n||e.assocLang===a)&&(void 0===l||e.default===l)&&(void 0===h||e.forced===h)&&(void 0===o||function(t,e=""){const i=t.split(","),r=e.split(",");return i.length===r.length&&!i.some((t=>-1===r.indexOf(t)))}(o,e.characteristics))&&(void 0===i||i(t,e))}function Ki(t,e){const{audioCodec:i,channels:r}=t;return!(void 0!==i&&(e.audioCodec||"").substring(0,4)!==i.substring(0,4)||void 0!==r&&r!==(e.channels||"2"))}function Hi(t,e,i){for(let r=e;r;r--)if(i(t[r]))return r;for(let r=e+1;r<t.length;r++)if(i(t[r]))return r;return-1}class $i{constructor(){this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(t){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,t),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}var Vi="NOT_LOADED",Yi="APPENDING",Wi="PARTIAL",ji="OK";class qi{constructor(t){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()}_registerListeners(){const{hls:t}=this;t.on(R.BUFFER_APPENDED,this.onBufferAppended,this),t.on(R.FRAG_BUFFERED,this.onFragBuffered,this),t.on(R.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:t}=this;t.off(R.BUFFER_APPENDED,this.onBufferAppended,this),t.off(R.FRAG_BUFFERED,this.onFragBuffered,this),t.off(R.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(t,e){const i=this.activePartLists[e];if(i)for(let e=i.length;e--;){const r=i[e];if(!r)break;const s=r.end;if(r.start<=t&&null!==s&&t<=s)return r}return this.getBufferedFrag(t,e)}getBufferedFrag(t,e){const{fragments:i}=this,r=Object.keys(i);for(let s=r.length;s--;){const n=i[r[s]];if((null==n?void 0:n.body.type)===e&&n.buffered){const e=n.body;if(e.start<=t&&t<=e.end)return e}}return null}detectEvictedFragments(t,e,i,r){this.timeRanges&&(this.timeRanges[t]=e);const s=(null==r?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach((r=>{const n=this.fragments[r];if(!n)return;if(s>=n.body.sn)return;if(!n.buffered&&!n.loaded)return void(n.body.type===i&&this.removeFragment(n.body));const a=n.range[t];a&&a.time.some((t=>{const i=!this.isTimeBuffered(t.startPTS,t.endPTS,e);return i&&this.removeFragment(n.body),i}))}))}detectPartialFragments(t){const e=this.timeRanges,{frag:i,part:r}=t;if(!e||"initSegment"===i.sn)return;const s=zi(i),n=this.fragments[s];if(!n||n.buffered&&i.gap)return;const a=!i.relurl;if(Object.keys(e).forEach((t=>{const s=i.elementaryStreams[t];if(!s)return;const o=e[t],l=a||!0===s.partial;n.range[t]=this.getBufferedTimes(i,r,l,o)})),n.loaded=null,Object.keys(n.range).length){n.buffered=!0;(n.body.endList=i.endList||n.body.endList)&&(this.endListFragments[n.body.type]=n),Xi(n)||this.removeParts(i.sn-1,i.type)}else this.removeFragment(n.body)}removeParts(t,e){const i=this.activePartLists[e];i&&(this.activePartLists[e]=i.filter((e=>e.fragment.sn>=t)))}fragBuffered(t,e){const i=zi(t);let r=this.fragments[i];!r&&e&&(r=this.fragments[i]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,r.buffered=!0)}getBufferedTimes(t,e,i,r){const s={time:[],partial:i},n=t.start,a=t.end,o=t.minEndPTS||a,l=t.maxStartPTS||n;for(let t=0;t<r.length;t++){const e=r.start(t)-this.bufferPadding,i=r.end(t)+this.bufferPadding;if(l>=e&&o<=i){s.time.push({startPTS:Math.max(n,r.start(t)),endPTS:Math.min(a,r.end(t))});break}if(n<i&&a>e){const e=Math.max(n,r.start(t)),i=Math.min(a,r.end(t));i>e&&(s.partial=!0,s.time.push({startPTS:e,endPTS:i}))}else if(a<=e)break}return s}getPartialFragment(t){let e,i,r,s=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach((l=>{const h=o[l];h&&Xi(h)&&(i=h.body.start-a,r=h.body.end+a,t>=i&&t<=r&&(e=Math.min(t-i,r-t),n<=e&&(s=h.body,n=e)))})),s}isEndListAppended(t){const e=this.endListFragments[t];return void 0!==e&&(e.buffered||Xi(e))}getState(t){const e=zi(t),i=this.fragments[e];return i?i.buffered?Xi(i)?Wi:ji:Yi:Vi}isTimeBuffered(t,e,i){let r,s;for(let n=0;n<i.length;n++){if(r=i.start(n)-this.bufferPadding,s=i.end(n)+this.bufferPadding,t>=r&&e<=s)return!0;if(e<=r)return!1}return!1}onFragLoaded(t,e){const{frag:i,part:r}=e;if("initSegment"===i.sn||i.bitrateTest)return;const s=r?null:e,n=zi(i);this.fragments[n]={body:i,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:i,part:r,timeRanges:s}=e;if("initSegment"===i.sn)return;const n=i.type;if(r){let t=this.activePartLists[n];t||(this.activePartLists[n]=t=[]),t.push(r)}this.timeRanges=s,Object.keys(s).forEach((t=>{const e=s[t];this.detectEvictedFragments(t,e,n,r)}))}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=zi(t);return!!this.fragments[e]}hasParts(t){var e;return!(null==(e=this.activePartLists[t])||!e.length)}removeFragmentsInRange(t,e,i,r,s){r&&!this.hasGaps||Object.keys(this.fragments).forEach((n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==i||r&&!o.gap||o.start<e&&o.end>t&&(a.buffered||s)&&this.removeFragment(o)}))}removeFragment(t){const e=zi(t);t.stats.loaded=0,t.clearElementaryStreamInfo();const i=this.activePartLists[t.type];if(i){const e=t.sn;this.activePartLists[t.type]=i.filter((t=>t.fragment.sn!==e))}delete this.fragments[e],t.endList&&delete this.endListFragments[t.type]}removeAllFragments(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1}}function Xi(t){var e,i,r;return t.buffered&&(t.body.gap||(null==(e=t.range.video)?void 0:e.partial)||(null==(i=t.range.audio)?void 0:i.partial)||(null==(r=t.range.audiovideo)?void 0:r.partial))}function zi(t){return`${t.type}_${t.level}_${t.sn}`}const Qi={length:0,start:()=>0,end:()=>0};class Ji{static isBuffered(t,e){try{if(t){const i=Ji.getBuffered(t);for(let t=0;t<i.length;t++)if(e>=i.start(t)&&e<=i.end(t))return!0}}catch(t){}return!1}static bufferInfo(t,e,i){try{if(t){const r=Ji.getBuffered(t),s=[];let n;for(n=0;n<r.length;n++)s.push({start:r.start(n),end:r.end(n)});return this.bufferedInfo(s,e,i)}}catch(t){}return{len:0,start:e,end:e,nextStart:void 0}}static bufferedInfo(t,e,i){e=Math.max(0,e),t.sort((function(t,e){const i=t.start-e.start;return i||e.end-t.end}));let r=[];if(i)for(let e=0;e<t.length;e++){const s=r.length;if(s){const n=r[s-1].end;t[e].start-n<i?t[e].end>n&&(r[s-1].end=t[e].end):r.push(t[e])}else r.push(t[e])}else r=t;let s,n=0,a=e,o=e;for(let t=0;t<r.length;t++){const l=r[t].start,h=r[t].end;if(e+i>=l&&e<h)a=l,o=h,n=o-e;else if(e+i<l){s=l;break}}return{len:n,start:a||0,end:o||0,nextStart:s}}static getBuffered(t){try{return t.buffered}catch(t){return _.log("failed to get media.buffered",t),Qi}}}class Zi{constructor(t,e,i,r=0,s=-1,n=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=t,this.sn=e,this.id=i,this.size=r,this.part=s,this.partial=n}}function tr(t,e){for(let r=0,s=t.length;r<s;r++){var i;if((null==(i=t[r])?void 0:i.cc)===e)return t[r]}return null}function er(t,e){if(t){const i=t.start+e;t.start=t.startPTS=i,t.endPTS=i+t.duration}}function ir(t,e){const i=e.fragments;for(let e=0,r=i.length;e<r;e++)er(i[e],t);e.fragmentHint&&er(e.fragmentHint,t),e.alignedSliding=!0}function rr(t,e,i){e&&(!function(t,e,i){if(function(t,e,i){return!(!e||!(i.endCC>i.startCC||t&&t.cc<i.startCC))}(t,i,e)){const t=function(t,e){const i=t.fragments,r=e.fragments;if(!r.length||!i.length)return void _.log("No fragments to align");const s=tr(i,r[0].cc);if(s&&(!s||s.startPTS))return s;_.log("No frag in previous level to align on")}(i,e);t&&S(t.start)&&(_.log(`Adjusting PTS using last level due to CC increase within current level ${e.url}`),ir(t.start,e))}}(t,i,e),!i.alignedSliding&&e&&sr(i,e),i.alignedSliding||!e||i.skippedSegments||hi(e,i))}function sr(t,e){if(!t.hasProgramDateTime||!e.hasProgramDateTime)return;const i=t.fragments,r=e.fragments;if(!i.length||!r.length)return;let s,n;const a=Math.min(e.endCC,t.endCC);e.startCC<a&&t.startCC<a&&(s=tr(r,a),n=tr(i,a)),s&&n||(s=r[Math.floor(r.length/2)],n=tr(i,s.cc)||i[Math.floor(i.length/2)]);const o=s.programDateTime,l=n.programDateTime;if(!o||!l)return;ir((l-o)/1e3-(n.start-s.start),t)}const nr=Math.pow(2,17);class ar{constructor(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(t,e){const i=t.url;if(!i)return Promise.reject(new hr({type:b.NETWORK_ERROR,details:k.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error("Fragment does not have a "+(i?"part list":"url")),networkDetails:null}));this.abort();const r=this.config,s=r.fLoader,n=r.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),t.gap){if(t.tagList.some((t=>"GAP"===t[0])))return void o(lr(t));t.gap=!1}const l=this.loader=t.loader=s?new s(r):new n(r),h=or(t),d=vi(r.fragLoadPolicy.default),u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?1/0:nr};t.stats=l.stats,l.load(h,u,{onSuccess:(e,i,r,s)=>{this.resetLoader(t,l);let n=e.data;r.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),a({frag:t,part:null,payload:n,networkDetails:s})},onError:(e,r,s,n)=>{this.resetLoader(t,l),o(new hr({type:b.NETWORK_ERROR,details:k.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:v({url:i,data:void 0},e),error:new Error(`HTTP Error ${e.code} ${e.text}`),networkDetails:s,stats:n}))},onAbort:(e,i,r)=>{this.resetLoader(t,l),o(new hr({type:b.NETWORK_ERROR,details:k.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:r,stats:e}))},onTimeout:(e,i,r)=>{this.resetLoader(t,l),o(new hr({type:b.NETWORK_ERROR,details:k.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:r,stats:e}))},onProgress:(i,r,s,n)=>{e&&e({frag:t,part:null,payload:s,networkDetails:n})}})}))}loadPart(t,e,i){this.abort();const r=this.config,s=r.fLoader,n=r.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap)return void o(lr(t,e));const l=this.loader=t.loader=s?new s(r):new n(r),h=or(t,e),d=vi(r.fragLoadPolicy.default),u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:nr};e.stats=l.stats,l.load(h,u,{onSuccess:(r,s,n,o)=>{this.resetLoader(t,l),this.updateStatsFromPart(t,e);const h={frag:t,part:e,payload:r.data,networkDetails:o};i(h),a(h)},onError:(i,r,s,n)=>{this.resetLoader(t,l),o(new hr({type:b.NETWORK_ERROR,details:k.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:v({url:h.url,data:void 0},i),error:new Error(`HTTP Error ${i.code} ${i.text}`),networkDetails:s,stats:n}))},onAbort:(i,r,s)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,l),o(new hr({type:b.NETWORK_ERROR,details:k.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:s,stats:i}))},onTimeout:(i,r,s)=>{this.resetLoader(t,l),o(new hr({type:b.NETWORK_ERROR,details:k.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:s,stats:i}))}})}))}updateStatsFromPart(t,e){const i=t.stats,r=e.stats,s=r.total;if(i.loaded+=r.loaded,s){const r=Math.round(t.duration/e.duration),n=Math.min(Math.round(i.loaded/s),r),a=(r-n)*Math.round(i.loaded/n);i.total=i.loaded+a}else i.total=Math.max(i.loaded,i.total);const n=i.loading,a=r.loading;n.start?n.first+=a.first-a.start:(n.start=a.start,n.first=a.first),n.end=a.end}resetLoader(t,e){t.loader=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()}}function or(t,e=null){const i=e||t,r={frag:t,part:e,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},s=i.byteRangeStartOffset,n=i.byteRangeEndOffset;if(S(s)&&S(n)){var a;let e=s,i=n;if("initSegment"===t.sn&&"AES-128"===(null==(a=t.decryptdata)?void 0:a.method)){const t=n-s;t%16&&(i=n+(16-t%16)),0!==s&&(r.resetIV=!0,e=s-16)}r.rangeStart=e,r.rangeEnd=i}return r}function lr(t,e){const i=new Error(`GAP ${t.gap?"tag":"attribute"} found`),r={type:b.MEDIA_ERROR,details:k.FRAG_GAP,fatal:!1,frag:t,error:i,networkDetails:null};return e&&(r.part=e),(e||t).stats.aborted=!0,new hr(r)}class hr extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class dr{constructor(t,e){this.subtle=void 0,this.aesIV=void 0,this.subtle=t,this.aesIV=e}decrypt(t,e){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t)}}class ur{constructor(t,e){this.subtle=void 0,this.key=void 0,this.subtle=t,this.key=e}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}}class cr{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(t){const e=new DataView(t),i=new Uint32Array(4);for(let t=0;t<4;t++)i[t]=e.getUint32(4*t);return i}initTable(){const t=this.sBox,e=this.invSBox,i=this.subMix,r=i[0],s=i[1],n=i[2],a=i[3],o=this.invSubMix,l=o[0],h=o[1],d=o[2],u=o[3],c=new Uint32Array(256);let f=0,g=0,m=0;for(m=0;m<256;m++)c[m]=m<128?m<<1:m<<1^283;for(m=0;m<256;m++){let i=g^g<<1^g<<2^g<<3^g<<4;i=i>>>8^255&i^99,t[f]=i,e[i]=f;const o=c[f],m=c[o],p=c[m];let v=257*c[i]^16843008*i;r[f]=v<<24|v>>>8,s[f]=v<<16|v>>>16,n[f]=v<<8|v>>>24,a[f]=v,v=16843009*p^65537*m^257*o^16843008*f,l[i]=v<<24|v>>>8,h[i]=v<<16|v>>>16,d[i]=v<<8|v>>>24,u[i]=v,f?(f=o^c[c[c[p^o]]],g^=c[c[g]]):f=g=1}}expandKey(t){const e=this.uint8ArrayToUint32Array_(t);let i=!0,r=0;for(;r<e.length&&i;)i=e[r]===this.key[r],r++;if(i)return;this.key=e;const s=this.keySize=e.length;if(4!==s&&6!==s&&8!==s)throw new Error("Invalid aes key size="+s);const n=this.ksRows=4*(s+6+1);let a,o;const l=this.keySchedule=new Uint32Array(n),h=this.invKeySchedule=new Uint32Array(n),d=this.sBox,u=this.rcon,c=this.invSubMix,f=c[0],g=c[1],m=c[2],p=c[3];let v,y;for(a=0;a<n;a++)a<s?v=l[a]=e[a]:(y=v,a%s==0?(y=y<<8|y>>>24,y=d[y>>>24]<<24|d[y>>>16&255]<<16|d[y>>>8&255]<<8|d[255&y],y^=u[a/s|0]<<24):s>6&&a%s==4&&(y=d[y>>>24]<<24|d[y>>>16&255]<<16|d[y>>>8&255]<<8|d[255&y]),l[a]=v=(l[a-s]^y)>>>0);for(o=0;o<n;o++)a=n-o,y=3&o?l[a]:l[a-4],h[o]=o<4||a<=4?y:f[d[y>>>24]]^g[d[y>>>16&255]]^m[d[y>>>8&255]]^p[d[255&y]],h[o]=h[o]>>>0}networkToHostOrderSwap(t){return t<<24|(65280&t)<<8|(16711680&t)>>8|t>>>24}decrypt(t,e,i){const r=this.keySize+6,s=this.invKeySchedule,n=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],h=a[2],d=a[3],u=this.uint8ArrayToUint32Array_(i);let c=u[0],f=u[1],g=u[2],m=u[3];const p=new Int32Array(t),v=new Int32Array(p.length);let y,E,T,S,A,L,R,b,k,D,I,w,C,_;const P=this.networkToHostOrderSwap;for(;e<p.length;){for(k=P(p[e]),D=P(p[e+1]),I=P(p[e+2]),w=P(p[e+3]),A=k^s[0],L=w^s[1],R=I^s[2],b=D^s[3],C=4,_=1;_<r;_++)y=o[A>>>24]^l[L>>16&255]^h[R>>8&255]^d[255&b]^s[C],E=o[L>>>24]^l[R>>16&255]^h[b>>8&255]^d[255&A]^s[C+1],T=o[R>>>24]^l[b>>16&255]^h[A>>8&255]^d[255&L]^s[C+2],S=o[b>>>24]^l[A>>16&255]^h[L>>8&255]^d[255&R]^s[C+3],A=y,L=E,R=T,b=S,C+=4;y=n[A>>>24]<<24^n[L>>16&255]<<16^n[R>>8&255]<<8^n[255&b]^s[C],E=n[L>>>24]<<24^n[R>>16&255]<<16^n[b>>8&255]<<8^n[255&A]^s[C+1],T=n[R>>>24]<<24^n[b>>16&255]<<16^n[A>>8&255]<<8^n[255&L]^s[C+2],S=n[b>>>24]<<24^n[A>>16&255]<<16^n[L>>8&255]<<8^n[255&R]^s[C+3],v[e]=P(y^c),v[e+1]=P(S^f),v[e+2]=P(T^g),v[e+3]=P(E^m),c=k,f=D,g=I,m=w,e+=4}return v.buffer}}class fr{constructor(t,{removePKCS7Padding:e=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.useSoftware=t.enableSoftwareAES,this.removePKCS7Padding=e,e)try{const t=self.crypto;t&&(this.subtle=t.subtle||t.webkitSubtle)}catch(t){}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:t,remainderData:e}=this;if(!t||e)return this.reset(),null;const i=new Uint8Array(t);return this.reset(),this.removePKCS7Padding?function(t){const e=t.byteLength,i=e&&new DataView(t.buffer).getUint8(e-1);return i?at(t,0,e-i):t}(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(t,e,i){return this.useSoftware?new Promise(((r,s)=>{this.softwareDecrypt(new Uint8Array(t),e,i);const n=this.flush();n?r(n.buffer):s(new Error("[softwareDecrypt] Failed to decrypt data"))})):this.webCryptoDecrypt(new Uint8Array(t),e,i)}softwareDecrypt(t,e,i){const{currentIV:r,currentResult:s,remainderData:n}=this;this.logOnce("JS AES decrypt"),n&&(t=$t(n,t),this.remainderData=null);const a=this.getValidChunk(t);if(!a.length)return null;r&&(i=r);let o=this.softwareDecrypter;o||(o=this.softwareDecrypter=new cr),o.expandKey(e);const l=s;return this.currentResult=o.decrypt(a.buffer,0,i),this.currentIV=at(a,-16).buffer,l||null}webCryptoDecrypt(t,e,i){if(this.key!==e||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,e,i));this.key=e,this.fastAesKey=new ur(this.subtle,e)}return this.fastAesKey.expandKey().then((e=>{if(!this.subtle)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new dr(this.subtle,new Uint8Array(i)).decrypt(t.buffer,e)})).catch((r=>(_.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(t,e,i))))}onWebCryptoError(t,e,i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,i);const r=this.flush();if(r)return r.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(t){let e=t;const i=t.length-t.length%16;return i!==t.length&&(e=at(t,0,i),this.remainderData=at(t,i)),e}logOnce(t){this.logEnabled&&(_.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const gr=function(t){let e="";const i=t.length;for(let r=0;r<i;r++)e+=`[${t.start(r).toFixed(3)}-${t.end(r).toFixed(3)}]`;return e},mr="STOPPED",pr="IDLE",vr="KEY_LOADING",yr="FRAG_LOADING",Er="FRAG_LOADING_WAITING_RETRY",Tr="WAITING_TRACK",Sr="PARSING",Ar="PARSED",Lr="ENDED",Rr="ERROR",br="WAITING_INIT_PTS",kr="WAITING_LEVEL";class Dr extends $i{constructor(t,e,i,r,s){super(),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=mr,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.loadedmetadata=!1,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.onvseeking=null,this.onvended=null,this.logPrefix="",this.log=void 0,this.warn=void 0,this.playlistType=s,this.logPrefix=r,this.log=_.log.bind(_,`${r}:`),this.warn=_.warn.bind(_,`${r}:`),this.hls=t,this.fragmentLoader=new ar(t.config),this.keyLoader=i,this.fragmentTracker=e,this.config=t.config,this.decrypter=new fr(t.config),t.on(R.MANIFEST_LOADED,this.onManifestLoaded,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const t=this.fragCurrent;null!=t&&t.loader&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=mr}_streamEnded(t,e){if(e.live||t.nextStart||!t.end||!this.media)return!1;const i=e.partList;if(null!=i&&i.length){const t=i[i.length-1];return Ji.isBuffered(this.media,t.start+t.duration/2)}const r=e.fragments[e.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(r)}getLevelDetails(){var t;if(this.levels&&null!==this.levelLastLoaded)return null==(t=this.levelLastLoaded)?void 0:t.details}onMediaAttached(t,e){const i=this.media=this.mediaBuffer=e.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),i.addEventListener("seeking",this.onvseeking),i.addEventListener("ended",this.onvended);const r=this.config;this.levels&&r.autoStartLoad&&this.state===mr&&this.startLoad(r.startPosition)}onMediaDetaching(){const t=this.media;null!=t&&t.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),t&&this.onvseeking&&this.onvended&&(t.removeEventListener("seeking",this.onvseeking),t.removeEventListener("ended",this.onvended),this.onvseeking=this.onvended=null),this.keyLoader&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}onMediaSeeking(){const{config:t,fragCurrent:e,media:i,mediaBuffer:r,state:s}=this,n=i?i.currentTime:0,a=Ji.bufferInfo(r||i,n,t.maxBufferHole);if(this.log(`media seeking to ${S(n)?n.toFixed(3):n}, state: ${s}`),this.state===Lr)this.resetLoadingState();else if(e){const i=t.maxFragLookUpTolerance,r=e.start-i,s=e.start+e.duration+i;if(!a.len||s<a.start||r>a.end){const t=n>s;(n<r||t)&&(t&&e.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),e.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}i&&(this.fragmentTracker.removeFragmentsInRange(n,1/0,this.playlistType,!0),this.lastCurrentTime=n),this.loadedmetadata||a.len||(this.nextLoadPosition=this.startPosition=n),this.tickImmediate()}onMediaEnded(){this.startPosition=this.lastCurrentTime=0}onManifestLoaded(t,e){this.startTimeOffset=e.startTimeOffset,this.initPTS=[]}onHandlerDestroying(){this.hls.off(R.MANIFEST_LOADED,this.onManifestLoaded,this),this.stopLoad(),super.onHandlerDestroying(),this.hls=null}onHandlerDestroyed(){this.state=mr,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(t,e,i){this._loadFragForPlayback(t,e,i)}_loadFragForPlayback(t,e,i){this._doFragLoad(t,e,i,(e=>{if(this.fragContextChanged(t))return this.warn(`Fragment ${t.sn}${e.part?" p: "+e.part.index:""} of level ${t.level} was dropped during download.`),void this.fragmentTracker.removeFragment(t);t.stats.chunkCount++,this._handleFragmentLoadProgress(e)})).then((e=>{if(!e)return;const i=this.state;this.fragContextChanged(t)?(i===yr||!this.fragCurrent&&i===Sr)&&(this.fragmentTracker.removeFragment(t),this.state=pr):("payload"in e&&(this.log(`Loaded fragment ${t.sn} of level ${t.level}`),this.hls.trigger(R.FRAG_LOADED,e)),this._handleFragmentLoadComplete(e))})).catch((e=>{this.state!==mr&&this.state!==Rr&&(this.warn(`Frag error: ${(null==e?void 0:e.message)||e}`),this.resetFragmentLoading(t))}))}clearTrackerIfNeeded(t){var e;const{fragmentTracker:i}=this;if(i.getState(t)===Yi){const e=t.type,r=this.getFwdBufferInfo(this.mediaBuffer,e),s=Math.max(t.duration,r?r.len:this.config.maxBufferLength),n=this.backtrackFragment;(1===(n?t.sn-n.sn:0)||this.reduceMaxBufferLength(s,t.duration))&&i.removeFragment(t)}else 0===(null==(e=this.mediaBuffer)?void 0:e.buffered.length)?i.removeAllFragments():i.hasParts(t.type)&&(i.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),i.getState(t)===Wi&&i.removeFragment(t))}checkLiveUpdate(t){if(t.updated&&!t.live){const e=t.fragments[t.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type})}t.fragments[0]||(t.deltaUpdateFailed=!0)}flushMainBuffer(t,e,i=null){if(!(t-e))return;const r={startOffset:t,endOffset:e,type:i};this.hls.trigger(R.BUFFER_FLUSHING,r)}_loadInitSegment(t,e){this._doFragLoad(t,e).then((e=>{if(!e||this.fragContextChanged(t)||!this.levels)throw new Error("init load aborted");return e})).then((e=>{const{hls:i}=this,{payload:r}=e,s=t.decryptdata;if(r&&r.byteLength>0&&null!=s&&s.key&&s.iv&&"AES-128"===s.method){const n=self.performance.now();return this.decrypter.decrypt(new Uint8Array(r),s.key.buffer,s.iv.buffer).catch((e=>{throw i.trigger(R.ERROR,{type:b.MEDIA_ERROR,details:k.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e})).then((r=>{const s=self.performance.now();return i.trigger(R.FRAG_DECRYPTED,{frag:t,payload:r,stats:{tstart:n,tdecrypt:s}}),e.payload=r,this.completeInitSegmentLoad(e)}))}return this.completeInitSegmentLoad(e)})).catch((e=>{this.state!==mr&&this.state!==Rr&&(this.warn(e),this.resetFragmentLoading(t))}))}completeInitSegmentLoad(t){const{levels:e}=this;if(!e)throw new Error("init load aborted, missing levels");const i=t.frag.stats;this.state=pr,t.frag.data=new Uint8Array(t.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}fragContextChanged(t){const{fragCurrent:e}=this;return!t||!e||t.sn!==e.sn||t.level!==e.level}fragBufferedComplete(t,e){var i,r,s,n;const a=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.playlistType===_e?"level":"track"} ${t.level} (frag:[${(null!=(i=t.startPTS)?i:NaN).toFixed(3)}-${(null!=(r=t.endPTS)?r:NaN).toFixed(3)}] > buffer:${a?gr(Ji.getBuffered(a)):"(detached)"})`),"initSegment"!==t.sn){var o;if(t.type!==xe){const e=t.elementaryStreams;if(!Object.keys(e).some((t=>!!e[t])))return void(this.state=pr)}const e=null==(o=this.levels)?void 0:o[t.level];null!=e&&e.fragmentError&&(this.log(`Resetting level fragment error count of ${e.fragmentError} on frag buffered`),e.fragmentError=0)}this.state=pr,a&&(!this.loadedmetadata&&t.type==_e&&a.buffered.length&&(null==(s=this.fragCurrent)?void 0:s.sn)===(null==(n=this.fragPrevious)?void 0:n.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(t){const{transmuxer:e}=this;if(!e)return;const{frag:i,part:r,partsLoaded:s}=t,n=!s||0===s.length||s.some((t=>!t)),a=new Zi(i.level,i.sn,i.stats.chunkCount+1,0,r?r.index:-1,!n);e.flush(a)}_handleFragmentLoadProgress(t){}_doFragLoad(t,e,i=null,r){var s;const n=null==e?void 0:e.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let a=null;if(!t.encrypted||null!=(s=t.decryptdata)&&s.key?!t.encrypted&&n.encryptedFragments.length&&this.keyLoader.loadClear(t,n.encryptedFragments):(this.log(`Loading key for ${t.sn} of [${n.startSN}-${n.endSN}], ${"[stream-controller]"===this.logPrefix?"level":"track"} ${t.level}`),this.state=vr,this.fragCurrent=t,a=this.keyLoader.load(t).then((t=>{if(!this.fragContextChanged(t.frag))return this.hls.trigger(R.KEY_LOADED,t),this.state===vr&&(this.state=pr),t})),this.hls.trigger(R.KEY_LOADING,{frag:t}),null===this.fragCurrent&&(a=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))),i=Math.max(t.start,i||0),this.config.lowLatencyMode&&"initSegment"!==t.sn){const s=n.partList;if(s&&r){i>t.end&&n.fragmentHint&&(t=n.fragmentHint);const o=this.getNextPart(s,t,i);if(o>-1){const l=s[o];let h;return this.log(`Loading part sn: ${t.sn} p: ${l.index} cc: ${t.cc} of playlist [${n.startSN}-${n.endSN}] parts [0-${o}-${s.length-1}] ${"[stream-controller]"===this.logPrefix?"level":"track"}: ${t.level}, target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=yr,h=a?a.then((i=>!i||this.fragContextChanged(i.frag)?null:this.doFragPartsLoad(t,l,e,r))).catch((t=>this.handleFragLoadError(t))):this.doFragPartsLoad(t,l,e,r).catch((t=>this.handleFragLoadError(t))),this.hls.trigger(R.FRAG_LOADING,{frag:t,part:l,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):h}if(!t.url||this.loadedEndOfParts(s,i))return Promise.resolve(null)}}this.log(`Loading fragment ${t.sn} cc: ${t.cc} ${n?"of ["+n.startSN+"-"+n.endSN+"] ":""}${"[stream-controller]"===this.logPrefix?"level":"track"}: ${t.level}, target: ${parseFloat(i.toFixed(3))}`),S(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=yr;const o=this.config.progressive;let l;return l=o&&a?a.then((e=>!e||this.fragContextChanged(null==e?void 0:e.frag)?null:this.fragmentLoader.load(t,r))).catch((t=>this.handleFragLoadError(t))):Promise.all([this.fragmentLoader.load(t,o?r:void 0),a]).then((([t])=>(!o&&t&&r&&r(t),t))).catch((t=>this.handleFragLoadError(t))),this.hls.trigger(R.FRAG_LOADING,{frag:t,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):l}doFragPartsLoad(t,e,i,r){return new Promise(((s,n)=>{var a;const o=[],l=null==(a=i.details)?void 0:a.partList,h=e=>{this.fragmentLoader.loadPart(t,e,r).then((r=>{o[e.index]=r;const n=r.part;this.hls.trigger(R.FRAG_LOADED,r);const a=ui(i,t.sn,e.index+1)||ci(l,t.sn,e.index+1);if(!a)return s({frag:t,part:n,partsLoaded:o});h(a)})).catch(n)};h(e)}))}handleFragLoadError(t){if("data"in t){const e=t.data;t.data&&e.details===k.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):this.hls.trigger(R.ERROR,e)}else this.hls.trigger(R.ERROR,{type:b.OTHER_ERROR,details:k.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==Sr)return void(this.fragCurrent||this.state===mr||this.state===Rr||(this.state=pr));const{frag:i,part:r,level:s}=e,n=self.performance.now();i.stats.parsing.end=n,r&&(r.stats.parsing.end=n),this.updateLevelTiming(i,r,s,t.partial)}getCurrentContext(t){const{levels:e,fragCurrent:i}=this,{level:r,sn:s,part:n}=t;if(null==e||!e[r])return this.warn(`Levels object was unset while buffering fragment ${s} of level ${r}. The current chunk will not be buffered.`),null;const a=e[r],o=n>-1?ui(a,s,n):null,l=o?o.fragment:function(t,e,i){if(null==t||!t.details)return null;const r=t.details;let s=r.fragments[e-r.startSN];return s||(s=r.fragmentHint,s&&s.sn===e?s:e<r.startSN&&i&&i.sn===e?i:null)}(a,s,i);return l?(i&&i!==l&&(l.stats=i.stats),{frag:l,part:o,level:a}):null}bufferFragmentData(t,e,i,r,s){var n;if(!t||this.state!==Sr)return;const{data1:a,data2:o}=t;let l=a;if(a&&o&&(l=$t(a,o)),null==(n=l)||!n.length)return;const h={type:t.type,frag:e,part:i,chunkMeta:r,parent:e.type,data:l};if(this.hls.trigger(R.BUFFER_APPENDING,h),t.dropped&&t.independent&&!i){if(s)return;this.flushBufferGap(e)}}flushBufferGap(t){const e=this.media;if(!e)return;if(!Ji.isBuffered(e,e.currentTime))return void this.flushMainBuffer(0,t.start);const i=e.currentTime,r=Ji.bufferInfo(e,i,0),s=t.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*s),a=Math.max(Math.min(t.start-n,r.end-n),i+n);t.start-a>n&&this.flushMainBuffer(a,t.start)}getFwdBufferInfo(t,e){const i=this.getLoadPosition();return S(i)?this.getFwdBufferInfoAtPos(t,i,e):null}getFwdBufferInfoAtPos(t,e,i){const{config:{maxBufferHole:r}}=this,s=Ji.bufferInfo(t,e,r);if(0===s.len&&void 0!==s.nextStart){const n=this.fragmentTracker.getBufferedFrag(e,i);if(n&&s.nextStart<n.end)return Ji.bufferInfo(t,e,Math.max(s.nextStart,r))}return s}getMaxBufferLength(t){const{config:e}=this;let i;return i=t?Math.max(8*e.maxBufferSize/t,e.maxBufferLength):e.maxBufferLength,Math.min(i,e.maxMaxBufferLength)}reduceMaxBufferLength(t,e){const i=this.config,r=Math.max(Math.min(t-e,i.maxBufferLength),e),s=Math.max(t-3*e,i.maxMaxBufferLength/2,r);return s>=r&&(i.maxMaxBufferLength=s,this.warn(`Reduce max buffer length to ${s}s`),!0)}getAppendedFrag(t,e=_e){const i=this.fragmentTracker.getAppendedFrag(t,_e);return i&&"fragment"in i?i.fragment:i}getNextFragment(t,e){const i=e.fragments,r=i.length;if(!r)return null;const{config:s}=this,n=i[0].start;let a;if(e.live){const o=s.initialLiveManifestSize;if(r<o)return this.warn(`Not enough fragments to start playback (have: ${r}, need: ${o})`),null;(!e.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||t<n)&&(a=this.getInitialLiveFragment(e,i),this.startPosition=this.nextLoadPosition=a?this.hls.liveSyncPosition||a.start:t)}else t<=n&&(a=i[0]);if(!a){const i=s.lowLatencyMode?e.partEnd:e.fragmentEnd;a=this.getFragmentAtPosition(t,i,e)}return this.mapToInitFragWhenRequired(a)}isLoopLoading(t,e){const i=this.fragmentTracker.getState(t);return(i===ji||i===Wi&&!!t.gap)&&this.nextLoadPosition>e}getNextFragmentLoopLoading(t,e,i,r,s){const n=t.gap,a=this.getNextFragment(this.nextLoadPosition,e);if(null===a)return a;if(t=a,n&&t&&!t.gap&&i.nextStart){const e=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,r);if(null!==e&&i.len+e.len>=s)return this.log(`buffer full after gaps in "${r}" playlist starting at sn: ${t.sn}`),null}return t}mapToInitFragWhenRequired(t){return null==t||!t.initSegment||null!=t&&t.initSegment.data||this.bitrateTest?t:t.initSegment}getNextPart(t,e,i){let r=-1,s=!1,n=!0;for(let a=0,o=t.length;a<o;a++){const o=t[a];if(n=n&&!o.independent,r>-1&&i<o.start)break;const l=o.loaded;l?r=-1:(s||o.independent||n)&&o.fragment===e&&(r=a),s=l}return r}loadedEndOfParts(t,e){const i=t[t.length-1];return i&&e>i.start&&i.loaded}getInitialLiveFragment(t,e){const i=this.fragPrevious;let r=null;if(i){if(t.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),r=function(t,e,i){if(null===e||!Array.isArray(t)||!t.length||!S(e))return null;if(e<(t[0].programDateTime||0))return null;if(e>=(t[t.length-1].endProgramDateTime||0))return null;i=i||0;for(let r=0;r<t.length;++r){const s=t[r];if(Ai(e,i,s))return s}return null}(e,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){const s=i.sn+1;if(s>=t.startSN&&s<=t.endSN){const n=e[s-t.startSN];i.cc===n.cc&&(r=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}r||(r=function(t,e){return Ei(t,(t=>t.cc<e?1:t.cc>e?-1:0))}(e,i.cc),r&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`))}}else{const e=this.hls.liveSyncPosition;null!==e&&(r=this.getFragmentAtPosition(e,this.bitrateTest?t.fragmentEnd:t.edge,t))}return r}getFragmentAtPosition(t,e,i){const{config:r}=this;let{fragPrevious:s}=this,{fragments:n,endSN:a}=i;const{fragmentHint:o}=i,{maxFragLookUpTolerance:l}=r,h=i.partList,d=!!(r.lowLatencyMode&&null!=h&&h.length&&o);let u;if(d&&o&&!this.bitrateTest&&(n=n.concat(o),a=o.sn),t<e){u=Ti(s,n,t,t>e-l?0:l)}else u=n[n.length-1];if(u){const t=u.sn-i.startSN,e=this.fragmentTracker.getState(u);if((e===ji||e===Wi&&u.gap)&&(s=u),s&&u.sn===s.sn&&(!d||h[0].fragment.sn>u.sn)){if(s&&u.level===s.level){const e=n[t+1];u=u.sn<a&&this.fragmentTracker.getState(e)!==ji?e:null}}}return u}synchronizeToLiveEdge(t){const{config:e,media:i}=this;if(!i)return;const r=this.hls.liveSyncPosition,s=i.currentTime,n=t.fragments[0].start,a=t.edge,o=s>=n-e.maxFragLookUpTolerance&&s<=a;if(null!==r&&i.duration>r&&(s<r||!o)){const n=void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.targetduration;(!o&&i.readyState<4||s<a-n)&&(this.loadedmetadata||(this.nextLoadPosition=r),i.readyState&&(this.warn(`Playback: ${s.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${r.toFixed(3)}`),i.currentTime=r))}}alignPlaylists(t,e,i){const r=t.fragments.length;if(!r)return this.warn("No fragments in live playlist"),0;const s=t.fragments[0].start,n=!e,a=t.alignedSliding&&S(s);if(n||!a&&!s){const{fragPrevious:s}=this;rr(s,i,t);const n=t.fragments[0].start;return this.log(`Live playlist sliding: ${n.toFixed(2)} start-sn: ${e?e.startSN:"na"}->${t.startSN} prev-sn: ${s?s.sn:"na"} fragments: ${r}`),n}return s}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,3*t.partTarget)}setStartPosition(t,e){let i=this.startPosition;if(i<e&&(i=-1),-1===i||-1===this.lastCurrentTime){const r=null!==this.startTimeOffset,s=r?this.startTimeOffset:t.startTimeOffset;null!==s&&S(s)?(i=e+s,s<0&&(i+=t.totalduration),i=Math.min(Math.max(e,i),e+t.totalduration),this.log(`Start time offset ${s} found in ${r?"multivariant":"media"} playlist, adjust startPosition to ${i}`),this.startPosition=i):t.live?i=this.hls.liveSyncPosition||e:this.startPosition=i=0,this.lastCurrentTime=i}this.nextLoadPosition=i}getLoadPosition(){const{media:t}=this;let e=0;return this.loadedmetadata&&t?e=t.currentTime:this.nextLoadPosition&&(e=this.nextLoadPosition),e}handleFragLoadAborted(t,e){this.transmuxer&&"initSegment"!==t.sn&&t.stats.aborted&&(this.warn(`Fragment ${t.sn}${e?" part "+e.index:""} of level ${t.level} was aborted`),this.resetFragmentLoading(t))}resetFragmentLoading(t){this.fragCurrent&&(this.fragContextChanged(t)||this.state===Er)||(this.state=pr)}onFragmentOrKeyLoadError(t,e){if(e.chunkMeta&&!e.frag){const t=this.getCurrentContext(e.chunkMeta);t&&(e.frag=t.frag)}const i=e.frag;if(!i||i.type!==t||!this.levels)return;var r;if(this.fragContextChanged(i))return void this.warn(`Frag load error must match current frag to retry ${i.url} > ${null==(r=this.fragCurrent)?void 0:r.url}`);const s=e.details===k.FRAG_GAP;s&&this.fragmentTracker.fragBuffered(i,!0);const n=e.errorAction,{action:a,retryCount:o=0,retryConfig:l}=n||{};if(n&&a===ki&&l){this.resetStartWhenNotLoaded(this.levelLastLoaded);const r=pi(l,o);this.warn(`Fragment ${i.sn} of ${t} ${i.level} errored with ${e.details}, retrying loading ${o+1}/${l.maxNumRetry} in ${r}ms`),n.resolved=!0,this.retryDate=self.performance.now()+r,this.state=Er}else if(l&&n){if(this.resetFragmentErrors(t),!(o<l.maxNumRetry))return void _.warn(`${e.details} reached or exceeded max retry (${o})`);s||a===bi||(n.resolved=!0)}else(null==n?void 0:n.action)===Ri?this.state=kr:this.state=Rr;this.tickImmediate()}reduceLengthAndFlushBuffer(t){if(this.state===Sr||this.state===Ar){const e=t.frag,i=t.parent,r=this.getFwdBufferInfo(this.mediaBuffer,i),s=r&&r.len>.5;s&&this.reduceMaxBufferLength(r.len,(null==e?void 0:e.duration)||10);const n=!s;return n&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${i} buffer`),e&&(this.fragmentTracker.removeFragment(e),this.nextLoadPosition=e.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(t){t===Pe&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==mr&&(this.state=pr)}afterBufferFlushed(t,e,i){if(!t)return;const r=Ji.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,r,i),this.state===Lr&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=pr}resetStartWhenNotLoaded(t){if(!this.loadedmetadata){this.startFragRequested=!1;const e=t?t.details:null;null!=e&&e.live?(this.startPosition=-1,this.setStartPosition(e,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){this.warn(`The loading context changed while buffering fragment ${t.sn} of level ${t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,e,i,r){var s;const n=i.details;if(!n)return void this.warn("level.details undefined");if(!Object.keys(t.elementaryStreams).reduce(((e,s)=>{const a=t.elementaryStreams[s];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${t.sn} ${s} duration reliably (${o})`),e||!1;const l=r?0:oi(n,t,a.startPTS,a.endPTS,a.startDTS,a.endDTS);return this.hls.trigger(R.LEVEL_PTS_UPDATED,{details:n,level:i,drift:l,type:s,frag:t,start:a.startPTS,end:a.endPTS}),!0}return e}),!1)&&null===(null==(s=this.transmuxer)?void 0:s.error)){const e=new Error(`Found no media in fragment ${t.sn} of level ${t.level} resetting transmuxer to fallback to playlist timing`);if(0===i.fragmentError&&(i.fragmentError++,t.gap=!0,this.fragmentTracker.removeFragment(t),this.fragmentTracker.fragBuffered(t,!0)),this.warn(e.message),this.hls.trigger(R.ERROR,{type:b.MEDIA_ERROR,details:k.FRAG_PARSING_ERROR,fatal:!1,error:e,frag:t,reason:`Found no media in msn ${t.sn} of level "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=Ar,this.hls.trigger(R.FRAG_PARSED,{frag:t,part:e})}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(t){"demuxerWorker"===t.event&&(this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())}set state(t){const e=this._state;e!==t&&(this._state=t,this.log(`${e}->${t}`))}get state(){return this._state}}class Ir{constructor(){this.chunks=[],this.dataLength=0}push(t){this.chunks.push(t),this.dataLength+=t.length}flush(){const{chunks:t,dataLength:e}=this;let i;return t.length?(i=1===t.length?t[0]:function(t,e){const i=new Uint8Array(e);let r=0;for(let e=0;e<t.length;e++){const s=t[e];i.set(s,r),r+=s.length}return i}(t,e),this.reset(),i):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}function wr(t="",e=9e4){return{type:t,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class Cr{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(t,e,i,r){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(t){this.initPTS=t,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(t,e){return!1}appendFrame(t,e,i){}demux(t,e){this.cachedData&&(t=$t(this.cachedData,t),this.cachedData=null);let i,r=ht(t,0),s=r?r.length:0;const n=this._audioTrack,a=this._id3Track,o=r?ct(r):void 0,l=t.length;for((null===this.basePTS||0===this.frameIndex&&S(o))&&(this.basePTS=_r(o,e,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),r&&r.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:He,duration:Number.POSITIVE_INFINITY});s<l;){if(this.canParse(t,s)){const e=this.appendFrame(n,t,s);e?(this.frameIndex++,this.lastPTS=e.sample.pts,s+=e.length,i=s):s=l}else ut(t,s)?(r=ht(t,s),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:He,duration:Number.POSITIVE_INFINITY}),s+=r.length,i=s):s++;if(s===l&&i!==l){const e=at(t,i);this.cachedData?this.cachedData=$t(this.cachedData,e):this.cachedData=e}}return{audioTrack:n,videoTrack:wr(),id3Track:a,textTrack:wr()}}demuxSampleAes(t,e,i){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(t){const e=this.cachedData;return e&&(this.cachedData=null,this.demux(e,0)),{audioTrack:this._audioTrack,videoTrack:wr(),id3Track:this._id3Track,textTrack:wr()}}destroy(){}}const _r=(t,e,i)=>{if(S(t))return 90*t;return 9e4*e+(i?9e4*i.baseTime/i.timescale:0)};function Pr(t,e){return 255===t[e]&&240==(246&t[e+1])}function xr(t,e){return 1&t[e+1]?7:9}function Mr(t,e){return(3&t[e+3])<<11|t[e+4]<<3|(224&t[e+5])>>>5}function Or(t,e){return e+1<t.length&&Pr(t,e)}function Fr(t,e){if(Or(t,e)){const i=xr(t,e);if(e+i>=t.length)return!1;const r=Mr(t,e);if(r<=i)return!1;const s=e+r;return s===t.length||Or(t,s)}return!1}function Nr(t,e,i,r,s){if(!t.samplerate){const n=function(t,e,i,r){let s,n,a,o;const l=navigator.userAgent.toLowerCase(),h=r,d=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];s=1+((192&e[i+2])>>>6);const u=(60&e[i+2])>>>2;if(!(u>d.length-1))return a=(1&e[i+2])<<2,a|=(192&e[i+3])>>>6,_.log(`manifest codec:${r}, ADTS type:${s}, samplingIndex:${u}`),/firefox/i.test(l)?u>=6?(s=5,o=new Array(4),n=u-3):(s=2,o=new Array(2),n=u):-1!==l.indexOf("android")?(s=2,o=new Array(2),n=u):(s=5,o=new Array(4),r&&(-1!==r.indexOf("mp4a.40.29")||-1!==r.indexOf("mp4a.40.5"))||!r&&u>=6?n=u-3:((r&&-1!==r.indexOf("mp4a.40.2")&&(u>=6&&1===a||/vivaldi/i.test(l))||!r&&1===a)&&(s=2,o=new Array(2)),n=u)),o[0]=s<<3,o[0]|=(14&u)>>1,o[1]|=(1&u)<<7,o[1]|=a<<3,5===s&&(o[1]|=(14&n)>>1,o[2]=(1&n)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:d[u],channelCount:a,codec:"mp4a.40."+s,manifestCodec:h};{const e=new Error(`invalid ADTS sampling index:${u}`);t.emit(R.ERROR,R.ERROR,{type:b.MEDIA_ERROR,details:k.FRAG_PARSING_ERROR,fatal:!0,error:e,reason:e.message})}}(e,i,r,s);if(!n)return;t.config=n.config,t.samplerate=n.samplerate,t.channelCount=n.channelCount,t.codec=n.codec,t.manifestCodec=n.manifestCodec,_.log(`parsed codec:${t.codec}, rate:${n.samplerate}, channels:${n.channelCount}`)}}function Ur(t){return 9216e4/t}function Br(t,e,i,r,s){const n=r+s*Ur(t.samplerate),a=function(t,e){const i=xr(t,e);if(e+i<=t.length){const r=Mr(t,e)-i;if(r>0)return{headerLength:i,frameLength:r}}}(e,i);let o;if(a){const{frameLength:r,headerLength:s}=a,l=s+r,h=Math.max(0,i+l-e.length);h?(o=new Uint8Array(l-s),o.set(e.subarray(i+s,e.length),0)):o=e.subarray(i+s,i+l);const d={unit:o,pts:n};return h||t.samples.push(d),{sample:d,length:l,missing:h}}const l=e.length-i;o=new Uint8Array(l),o.set(e.subarray(i,e.length),0);return{sample:{unit:o,pts:n},length:l,missing:-1}}let Gr=null;const Kr=[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],Hr=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],$r=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Vr=[0,1,1,4];function Yr(t,e,i,r,s){if(i+24>e.length)return;const n=Wr(e,i);if(n&&i+n.frameLength<=e.length){const a=r+s*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:e.subarray(i,i+n.frameLength),pts:a,dts:a};return t.config=[],t.channelCount=n.channelCount,t.samplerate=n.sampleRate,t.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function Wr(t,e){const i=t[e+1]>>3&3,r=t[e+1]>>1&3,s=t[e+2]>>4&15,n=t[e+2]>>2&3;if(1!==i&&0!==s&&15!==s&&3!==n){const a=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*Kr[14*(3===i?3-r:3===r?3:4)+s-1],h=Hr[3*(3===i?0:2===i?1:2)+n],d=3===o?1:2,u=$r[i][r],c=Vr[r],f=8*u*c,g=Math.floor(u*l/h+a)*c;if(null===Gr){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Gr=t?parseInt(t[1]):0}return!!Gr&&Gr<=87&&2===r&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:h,channelCount:d,frameLength:g,samplesPerFrame:f}}}function jr(t,e){return!(255!==t[e]||224&~t[e+1]||!(6&t[e+1]))}function qr(t,e){return e+1<t.length&&jr(t,e)}function Xr(t,e){if(e+1<t.length&&jr(t,e)){const i=4,r=Wr(t,e);let s=i;null!=r&&r.frameLength&&(s=r.frameLength);const n=e+s;return n===t.length||qr(t,n)}return!1}const zr=/\/emsg[-/]ID3/i;const Qr=(t,e)=>{let i=0,r=5;e+=r;const s=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;r>0;){a[0]=t[e];const o=Math.min(r,8),l=8-o;n[0]=4278190080>>>24+l<<l,s[0]=(a[0]&n[0])>>l,i=i?i<<o|s[0]:s[0],e+=1,r-=o}return i};class Jr extends Cr{constructor(t){super(),this.observer=void 0,this.observer=t}resetInitSegment(t,e,i,r){super.resetInitSegment(t,e,i,r),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:e,duration:r,inputTimeScale:9e4,dropped:0}}canParse(t,e){return e+64<t.length}appendFrame(t,e,i){const r=Zr(t,e,i,this.basePTS,this.frameIndex);if(-1!==r){return{sample:t.samples[t.samples.length-1],length:r,missing:0}}}static probe(t){if(!t)return!1;const e=ht(t,0);if(!e)return!1;const i=e.length;return 11===t[i]&&119===t[i+1]&&void 0!==ct(e)&&Qr(t,i)<16}}function Zr(t,e,i,r,s){if(i+8>e.length)return-1;if(11!==e[i]||119!==e[i+1])return-1;const n=e[i+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=63&e[i+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+n];if(i+l>e.length)return-1;const h=e[i+6]>>5;let d=0;2===h?d+=2:(1&h&&1!==h&&(d+=2),4&h&&(d+=2));const u=(e[i+6]<<8|e[i+7])>>12-d&1,c=[2,1,2,3,3,4,4,5][h]+u,f=e[i+5]>>3,g=7&e[i+5],m=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|h<<3|u<<2|o>>4,o<<4&224]),p=r+s*(1536/a*9e4),v=e.subarray(i,i+l);return t.config=m,t.channelCount=c,t.samplerate=a,t.samples.push({unit:v,pts:p}),l}class ts{constructor(){this.VideoSample=null}createVideoSample(t,e,i,r){return{key:t,frame:!1,pts:e,dts:i,units:[],debug:r,length:0}}getLastNalUnit(t){var e;let i,r=this.VideoSample;if(r&&0!==r.units.length||(r=t[t.length-1]),null!=(e=r)&&e.units){const t=r.units;i=t[t.length-1]}return i}pushAccessUnit(t,e){if(t.units.length&&t.frame){if(void 0===t.pts){const i=e.samples,r=i.length;if(!r)return void e.dropped++;{const e=i[r-1];t.pts=e.pts,t.dts=e.dts}}e.samples.push(t)}t.debug.length&&_.log(t.pts+"/"+t.dts+":"+t.debug)}}class es{constructor(t){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}loadWord(){const t=this.data,e=this.bytesAvailable,i=t.byteLength-e,r=new Uint8Array(4),s=Math.min(4,e);if(0===s)throw new Error("no bytes available");r.set(t.subarray(i,i+s)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=8*s,this.bytesAvailable-=s}skipBits(t){let e;t=Math.min(t,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(e=(t-=this.bitsAvailable)>>3,t-=e<<3,this.bytesAvailable-=e,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)}readBits(t){let e=Math.min(this.bitsAvailable,t);const i=this.word>>>32-e;if(t>32&&_.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0)this.word<<=e;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return e=t-e,e>0&&this.bitsAvailable?i<<e|this.readBits(e):i}skipLZ(){let t;for(t=0;t<this.bitsAvailable;++t)if(this.word&2147483648>>>t)return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const t=this.skipLZ();return this.readBits(t+1)-1}readEG(){const t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}skipScalingList(t){let e,i=8,r=8;for(let s=0;s<t;s++)0!==r&&(e=this.readEG(),r=(i+e+256)%256),i=0===r?i:r}readSPS(){let t,e,i,r=0,s=0,n=0,a=0;const o=this.readUByte.bind(this),l=this.readBits.bind(this),h=this.readUEG.bind(this),d=this.readBoolean.bind(this),u=this.skipBits.bind(this),c=this.skipEG.bind(this),f=this.skipUEG.bind(this),g=this.skipScalingList.bind(this);o();const m=o();if(l(5),u(3),o(),f(),100===m||110===m||122===m||244===m||44===m||83===m||86===m||118===m||128===m){const t=h();if(3===t&&u(1),f(),f(),u(1),d())for(e=3!==t?8:12,i=0;i<e;i++)d()&&g(i<6?16:64)}f();const p=h();if(0===p)h();else if(1===p)for(u(1),c(),c(),t=h(),i=0;i<t;i++)c();f(),u(1);const v=h(),y=h(),E=l(1);0===E&&u(1),u(1),d()&&(r=h(),s=h(),n=h(),a=h());let T=[1,1];if(d()&&d()){switch(o()){case 1:T=[1,1];break;case 2:T=[12,11];break;case 3:T=[10,11];break;case 4:T=[16,11];break;case 5:T=[40,33];break;case 6:T=[24,11];break;case 7:T=[20,11];break;case 8:T=[32,11];break;case 9:T=[80,33];break;case 10:T=[18,11];break;case 11:T=[15,11];break;case 12:T=[64,33];break;case 13:T=[160,99];break;case 14:T=[4,3];break;case 15:T=[3,2];break;case 16:T=[2,1];break;case 255:T=[o()<<8|o(),o()<<8|o()]}}return{width:Math.ceil(16*(v+1)-2*r-2*s),height:(2-E)*(y+1)*16-(E?2:4)*(n+a),pixelRatio:T}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}class is extends ts{parseAVCPES(t,e,i,r,s){const n=this.parseAVCNALu(t,i.data);let a,o=this.VideoSample,l=!1;i.data=null,o&&n.length&&!t.audFound&&(this.pushAccessUnit(o,t),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts,"")),n.forEach((r=>{var n;switch(r.type){case 1:{let e=!1;a=!0;const s=r.data;if(l&&s.length>4){const t=new es(s).readSliceType();2!==t&&4!==t&&7!==t&&9!==t||(e=!0)}var h;if(e)null!=(h=o)&&h.frame&&!o.key&&(this.pushAccessUnit(o,t),o=this.VideoSample=null);o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts,"")),o.frame=!0,o.key=e;break}case 5:a=!0,null!=(n=o)&&n.frame&&!o.key&&(this.pushAccessUnit(o,t),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts,"")),o.key=!0,o.frame=!0;break;case 6:a=!0,Wt(r.data,1,i.pts,e.samples);break;case 7:{var d,u;a=!0,l=!0;const e=r.data,i=new es(e).readSPS();if(!t.sps||t.width!==i.width||t.height!==i.height||(null==(d=t.pixelRatio)?void 0:d[0])!==i.pixelRatio[0]||(null==(u=t.pixelRatio)?void 0:u[1])!==i.pixelRatio[1]){t.width=i.width,t.height=i.height,t.pixelRatio=i.pixelRatio,t.sps=[e],t.duration=s;const r=e.subarray(1,4);let n="avc1.";for(let t=0;t<3;t++){let e=r[t].toString(16);e.length<2&&(e="0"+e),n+=e}t.codec=n}break}case 8:a=!0,t.pps=[r.data];break;case 9:a=!0,t.audFound=!0,o&&this.pushAccessUnit(o,t),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts,"");break;case 12:a=!0;break;default:a=!1,o&&(o.debug+="unknown NAL "+r.type+" ")}if(o&&a){o.units.push(r)}})),r&&o&&(this.pushAccessUnit(o,t),this.VideoSample=null)}parseAVCNALu(t,e){const i=e.byteLength;let r=t.naluState||0;const s=r,n=[];let a,o,l,h=0,d=-1,u=0;for(-1===r&&(d=0,u=31&e[0],r=0,h=1);h<i;)if(a=e[h++],r)if(1!==r)if(a)if(1===a){if(o=h-r-1,d>=0){const t={data:e.subarray(d,o),type:u};n.push(t)}else{const i=this.getLastNalUnit(t.samples);i&&(s&&h<=4-s&&i.state&&(i.data=i.data.subarray(0,i.data.byteLength-s)),o>0&&(i.data=$t(i.data,e.subarray(0,o)),i.state=0))}h<i?(l=31&e[h],d=h,u=l,r=0):r=-1}else r=0;else r=3;else r=a?0:2;else r=a?0:1;if(d>=0&&r>=0){const t={data:e.subarray(d,i),type:u,state:r};n.push(t)}if(0===n.length){const i=this.getLastNalUnit(t.samples);i&&(i.data=$t(i.data,e))}return t.naluState=r,n}}class rs{constructor(t,e,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new fr(e,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(t,e,i){const r=t[e].unit;if(r.length<=16)return;const s=r.subarray(16,r.length-r.length%16),n=s.buffer.slice(s.byteOffset,s.byteOffset+s.length);this.decryptBuffer(n).then((s=>{const n=new Uint8Array(s);r.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(t,e+1,i)}))}decryptAacSamples(t,e,i){for(;;e++){if(e>=t.length)return void i();if(!(t[e].unit.length<32)&&(this.decryptAacSample(t,e,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(t){const e=16*Math.floor((t.length-48)/160)+16,i=new Int8Array(e);let r=0;for(let e=32;e<t.length-16;e+=160,r+=16)i.set(t.subarray(e,e+16),r);return i}getAvcDecryptedUnit(t,e){const i=new Uint8Array(e);let r=0;for(let e=32;e<t.length-16;e+=160,r+=16)t.set(i.subarray(r,r+16),e);return t}decryptAvcSample(t,e,i,r,s){const n=jt(s.data),a=this.getAvcEncryptedData(n);this.decryptBuffer(a.buffer).then((a=>{s.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(t,e,i+1,r)}))}decryptAvcSamples(t,e,i,r){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,i=0){if(e>=t.length)return void r();const s=t[e].units;for(;!(i>=s.length);i++){const n=s[i];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(t,e,i,r,n),this.decrypter.isSync())))return}}}}const ss=188;class ns{constructor(t,e,i){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._duration=0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=t,this.config=e,this.typeSupported=i,this.videoParser=new is}static probe(t){const e=ns.syncOffset(t);return e>0&&_.warn(`MPEG2-TS detected but first sync word found @ offset ${e}`),-1!==e}static syncOffset(t){const e=t.length;let i=Math.min(940,e-ss)+1,r=0;for(;r<i;){let s=!1,n=-1,a=0;for(let o=r;o<e;o+=ss){if(71!==t[o]||e-o!==ss&&71!==t[o+ss]){if(a)return-1;break}if(a++,-1===n&&(n=o,0!==n&&(i=Math.min(n+18612,t.length-ss)+1)),s||(s=0===as(t,o)),s&&a>1&&(0===n&&a>2||o+ss>i))return n}r++}return-1}static createTrack(t,e){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:Dt[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===t?e:void 0}}resetInitSegment(t,e,i,r){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=ns.createTrack("video"),this._audioTrack=ns.createTrack("audio",r),this._id3Track=ns.createTrack("id3"),this._txtTrack=ns.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=e,this.videoCodec=i,this._duration=r}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:e,_id3Track:i}=this;t&&(t.pesData=null),e&&(e.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,e,i=!1,r=!1){let s;i||(this.sampleAes=null);const n=this._videoTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let h=n.pid,d=n.pesData,u=a.pid,c=o.pid,f=a.pesData,g=o.pesData,m=null,p=this.pmtParsed,v=this._pmtId,y=t.length;if(this.remainderData&&(y=(t=$t(this.remainderData,t)).length,this.remainderData=null),y<ss&&!r)return this.remainderData=t,{audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};const E=Math.max(0,ns.syncOffset(t));y-=(y-E)%ss,y<t.byteLength&&!r&&(this.remainderData=new Uint8Array(t.buffer,y,t.buffer.byteLength-y));let T=0;for(let e=E;e<y;e+=ss)if(71===t[e]){const r=!!(64&t[e+1]),y=as(t,e);let T;if((48&t[e+3])>>4>1){if(T=e+5+t[e+4],T===e+ss)continue}else T=e+4;switch(y){case h:r&&(d&&(s=us(d))&&this.videoParser.parseAVCPES(n,l,s,!1,this._duration),d={data:[],size:0}),d&&(d.data.push(t.subarray(T,e+ss)),d.size+=e+ss-T);break;case u:if(r){if(f&&(s=us(f)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,s);break;case"mp3":this.parseMPEGPES(a,s);break;case"ac3":this.parseAC3PES(a,s)}f={data:[],size:0}}f&&(f.data.push(t.subarray(T,e+ss)),f.size+=e+ss-T);break;case c:r&&(g&&(s=us(g))&&this.parseID3PES(o,s),g={data:[],size:0}),g&&(g.data.push(t.subarray(T,e+ss)),g.size+=e+ss-T);break;case 0:r&&(T+=t[T]+1),v=this._pmtId=os(t,T);break;case v:{r&&(T+=t[T]+1);const s=ls(t,T,this.typeSupported,i,this.observer);h=s.videoPid,h>0&&(n.pid=h,n.segmentCodec=s.segmentVideoCodec),u=s.audioPid,u>0&&(a.pid=u,a.segmentCodec=s.segmentAudioCodec),c=s.id3Pid,c>0&&(o.pid=c),null===m||p||(_.warn(`MPEG-TS PMT found at ${e} after unknown PID '${m}'. Backtracking to sync byte @${E} to parse all TS packets.`),m=null,e=E-188),p=this.pmtParsed=!0;break}case 17:case 8191:break;default:m=y}}else T++;T>0&&hs(this.observer,new Error(`Found ${T} TS packet/s that do not start with 0x47`)),n.pesData=d,a.pesData=f,o.pesData=g;const S={audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};return r&&this.extractRemainingSamples(S),S}flush(){const{remainderData:t}=this;let e;return this.remainderData=null,e=t?this.demux(t,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(e),this.sampleAes?this.decrypt(e,this.sampleAes):e}extractRemainingSamples(t){const{audioTrack:e,videoTrack:i,id3Track:r,textTrack:s}=t,n=i.pesData,a=e.pesData,o=r.pesData;let l;if(n&&(l=us(n))?(this.videoParser.parseAVCPES(i,s,l,!0,this._duration),i.pesData=null):i.pesData=n,a&&(l=us(a))){switch(e.segmentCodec){case"aac":this.parseAACPES(e,l);break;case"mp3":this.parseMPEGPES(e,l);break;case"ac3":this.parseAC3PES(e,l)}e.pesData=null}else null!=a&&a.size&&_.log("last AAC PES packet truncated,might overlap between fragments"),e.pesData=a;o&&(l=us(o))?(this.parseID3PES(r,l),r.pesData=null):r.pesData=o}demuxSampleAes(t,e,i){const r=this.demux(t,i,!0,!this.config.progressive),s=this.sampleAes=new rs(this.observer,this.config,e);return this.decrypt(r,s)}decrypt(t,e){return new Promise((i=>{const{audioTrack:r,videoTrack:s}=t;r.samples&&"aac"===r.segmentCodec?e.decryptAacSamples(r.samples,0,(()=>{s.samples?e.decryptAvcSamples(s.samples,0,0,(()=>{i(t)})):i(t)})):s.samples&&e.decryptAvcSamples(s.samples,0,0,(()=>{i(t)}))}))}destroy(){this._duration=0}parseAACPES(t,e){let i=0;const r=this.aacOverFlow;let s,n,a,o=e.data;if(r){this.aacOverFlow=null;const e=r.missing,s=r.sample.unit.byteLength;if(-1===e)o=$t(r.sample.unit,o);else{const n=s-e;r.sample.unit.set(o.subarray(0,e),n),t.samples.push(r.sample),i=r.missing}}for(s=i,n=o.length;s<n-1&&!Or(o,s);s++);if(s!==i){let t;const e=s<n-1;if(t=e?`AAC PES did not start with ADTS header,offset:${s}`:"No ADTS header found in AAC PES",hs(this.observer,new Error(t),e),!e)return}if(Nr(t,this.observer,o,s,this.audioCodec),void 0!==e.pts)a=e.pts;else{if(!r)return void _.warn("[tsdemuxer]: AAC PES unknown PTS");{const e=Ur(t.samplerate);a=r.sample.pts+e}}let l,h=0;for(;s<n;){if(l=Br(t,o,s,a,h),s+=l.length,l.missing){this.aacOverFlow=l;break}for(h++;s<n-1&&!Or(o,s);s++);}}parseMPEGPES(t,e){const i=e.data,r=i.length;let s=0,n=0;const a=e.pts;if(void 0!==a)for(;n<r;)if(qr(i,n)){const e=Yr(t,i,n,a,s);if(!e)break;n+=e.length,s++}else n++;else _.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(t,e){{const i=e.data,r=e.pts;if(void 0===r)return void _.warn("[tsdemuxer]: AC3 PES unknown PTS");const s=i.length;let n,a=0,o=0;for(;o<s&&(n=Zr(t,i,o,r,a++))>0;)o+=n}}parseID3PES(t,e){if(void 0===e.pts)return void _.warn("[tsdemuxer]: ID3 PES unknown PTS");const i=T({},e,{type:this._videoTrack?Ve:He,duration:Number.POSITIVE_INFINITY});t.samples.push(i)}}function as(t,e){return((31&t[e+1])<<8)+t[e+2]}function os(t,e){return(31&t[e+10])<<8|t[e+11]}function ls(t,e,i,r,s){const n={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},a=e+3+((15&t[e+1])<<8|t[e+2])-4;for(e+=12+((15&t[e+10])<<8|t[e+11]);e<a;){const a=as(t,e),o=(15&t[e+3])<<8|t[e+4];switch(t[e]){case 207:if(!r){ds("ADTS AAC");break}case 15:-1===n.audioPid&&(n.audioPid=a);break;case 21:-1===n.id3Pid&&(n.id3Pid=a);break;case 219:if(!r){ds("H.264");break}case 27:-1===n.videoPid&&(n.videoPid=a,n.segmentVideoCodec="avc");break;case 3:case 4:i.mpeg||i.mp3?-1===n.audioPid&&(n.audioPid=a,n.segmentAudioCodec="mp3"):_.log("MPEG audio found, not supported in this browser");break;case 193:if(!r){ds("AC-3");break}case 129:i.ac3?-1===n.audioPid&&(n.audioPid=a,n.segmentAudioCodec="ac3"):_.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===n.audioPid&&o>0){let r=e+5,s=o;for(;s>2;){if(106===t[r])!0!==i.ac3?_.log("AC-3 audio found, not supported in this browser for now"):(n.audioPid=a,n.segmentAudioCodec="ac3");const e=t[r+1]+2;r+=e,s-=e}}break;case 194:case 135:return hs(s,new Error("Unsupported EC-3 in M2TS found")),n;case 36:return hs(s,new Error("Unsupported HEVC in M2TS found")),n}e+=o+5}return n}function hs(t,e,i){_.warn(`parsing error: ${e.message}`),t.emit(R.ERROR,R.ERROR,{type:b.MEDIA_ERROR,details:k.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,error:e,reason:e.message})}function ds(t){_.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function us(t){let e,i,r,s,n,a=0;const o=t.data;if(!t||0===t.size)return null;for(;o[0].length<19&&o.length>1;)o[0]=$t(o[0],o[1]),o.splice(1,1);e=o[0];if(1===(e[0]<<16)+(e[1]<<8)+e[2]){if(i=(e[4]<<8)+e[5],i&&i>t.size-6)return null;const l=e[7];192&l&&(s=536870912*(14&e[9])+4194304*(255&e[10])+16384*(254&e[11])+128*(255&e[12])+(254&e[13])/2,64&l?(n=536870912*(14&e[14])+4194304*(255&e[15])+16384*(254&e[16])+128*(255&e[17])+(254&e[18])/2,s-n>54e5&&(_.warn(`${Math.round((s-n)/9e4)}s delta between PTS and DTS, align them`),s=n)):n=s),r=e[8];let h=r+9;if(t.size<=h)return null;t.size-=h;const d=new Uint8Array(t.size);for(let t=0,i=o.length;t<i;t++){e=o[t];let i=e.byteLength;if(h){if(h>i){h-=i;continue}e=e.subarray(h),i-=h,h=0}d.set(e,a),a+=i}return i&&(i-=r+3),{data:d,pts:s,dts:n,len:i}}return null}class cs{static getSilentFrame(t,e){if("mp4a.40.2"===t){if(1===e)return new Uint8Array([0,200,0,128,35,128]);if(2===e)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===e)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===e)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===e)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===e)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===e)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}}const fs=Math.pow(2,32)-1;class gs{static init(){let t;for(t in gs.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},gs.types)gs.types.hasOwnProperty(t)&&(gs.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);const e=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),i=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);gs.HDLR_TYPES={video:e,audio:i};const r=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),s=new Uint8Array([0,0,0,0,0,0,0,0]);gs.STTS=gs.STSC=gs.STCO=s,gs.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),gs.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),gs.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),gs.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const n=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),o=new Uint8Array([0,0,0,1]);gs.FTYP=gs.box(gs.types.ftyp,n,o,n,a),gs.DINF=gs.box(gs.types.dinf,gs.box(gs.types.dref,r))}static box(t,...e){let i=8,r=e.length;const s=r;for(;r--;)i+=e[r].byteLength;const n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=255&i,n.set(t,4),r=0,i=8;r<s;r++)n.set(e[r],i),i+=e[r].byteLength;return n}static hdlr(t){return gs.box(gs.types.hdlr,gs.HDLR_TYPES[t])}static mdat(t){return gs.box(gs.types.mdat,t)}static mdhd(t,e){e*=t;const i=Math.floor(e/(fs+1)),r=Math.floor(e%(fs+1));return gs.box(gs.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,r>>24,r>>16&255,r>>8&255,255&r,85,196,0,0]))}static mdia(t){return gs.box(gs.types.mdia,gs.mdhd(t.timescale,t.duration),gs.hdlr(t.type),gs.minf(t))}static mfhd(t){return gs.box(gs.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}static minf(t){return"audio"===t.type?gs.box(gs.types.minf,gs.box(gs.types.smhd,gs.SMHD),gs.DINF,gs.stbl(t)):gs.box(gs.types.minf,gs.box(gs.types.vmhd,gs.VMHD),gs.DINF,gs.stbl(t))}static moof(t,e,i){return gs.box(gs.types.moof,gs.mfhd(t),gs.traf(i,e))}static moov(t){let e=t.length;const i=[];for(;e--;)i[e]=gs.trak(t[e]);return gs.box.apply(null,[gs.types.moov,gs.mvhd(t[0].timescale,t[0].duration)].concat(i).concat(gs.mvex(t)))}static mvex(t){let e=t.length;const i=[];for(;e--;)i[e]=gs.trex(t[e]);return gs.box.apply(null,[gs.types.mvex,...i])}static mvhd(t,e){e*=t;const i=Math.floor(e/(fs+1)),r=Math.floor(e%(fs+1)),s=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,r>>24,r>>16&255,r>>8&255,255&r,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 gs.box(gs.types.mvhd,s)}static sdtp(t){const e=t.samples||[],i=new Uint8Array(4+e.length);let r,s;for(r=0;r<e.length;r++)s=e[r].flags,i[r+4]=s.dependsOn<<4|s.isDependedOn<<2|s.hasRedundancy;return gs.box(gs.types.sdtp,i)}static stbl(t){return gs.box(gs.types.stbl,gs.stsd(t),gs.box(gs.types.stts,gs.STTS),gs.box(gs.types.stsc,gs.STSC),gs.box(gs.types.stsz,gs.STSZ),gs.box(gs.types.stco,gs.STCO))}static avc1(t){let e,i,r,s=[],n=[];for(e=0;e<t.sps.length;e++)i=t.sps[e],r=i.byteLength,s.push(r>>>8&255),s.push(255&r),s=s.concat(Array.prototype.slice.call(i));for(e=0;e<t.pps.length;e++)i=t.pps[e],r=i.byteLength,n.push(r>>>8&255),n.push(255&r),n=n.concat(Array.prototype.slice.call(i));const a=gs.box(gs.types.avcC,new Uint8Array([1,s[3],s[4],s[5],255,224|t.sps.length].concat(s).concat([t.pps.length]).concat(n))),o=t.width,l=t.height,h=t.pixelRatio[0],d=t.pixelRatio[1];return gs.box(gs.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,o>>8&255,255&o,l>>8&255,255&l,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),a,gs.box(gs.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),gs.box(gs.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,d>>24,d>>16&255,d>>8&255,255&d])))}static esds(t){const e=t.config.length;return new Uint8Array([0,0,0,0,3,23+e,0,1,0,4,15+e,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([e]).concat(t.config).concat([6,1,2]))}static audioStsd(t){const e=t.samplerate;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,e>>8&255,255&e,0,0])}static mp4a(t){return gs.box(gs.types.mp4a,gs.audioStsd(t),gs.box(gs.types.esds,gs.esds(t)))}static mp3(t){return gs.box(gs.types[".mp3"],gs.audioStsd(t))}static ac3(t){return gs.box(gs.types["ac-3"],gs.audioStsd(t),gs.box(gs.types.dac3,t.config))}static stsd(t){return"audio"===t.type?"mp3"===t.segmentCodec&&"mp3"===t.codec?gs.box(gs.types.stsd,gs.STSD,gs.mp3(t)):"ac3"===t.segmentCodec?gs.box(gs.types.stsd,gs.STSD,gs.ac3(t)):gs.box(gs.types.stsd,gs.STSD,gs.mp4a(t)):gs.box(gs.types.stsd,gs.STSD,gs.avc1(t))}static tkhd(t){const e=t.id,i=t.duration*t.timescale,r=t.width,s=t.height,n=Math.floor(i/(fs+1)),a=Math.floor(i%(fs+1));return gs.box(gs.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,r>>8&255,255&r,0,0,s>>8&255,255&s,0,0]))}static traf(t,e){const i=gs.sdtp(t),r=t.id,s=Math.floor(e/(fs+1)),n=Math.floor(e%(fs+1));return gs.box(gs.types.traf,gs.box(gs.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r])),gs.box(gs.types.tfdt,new Uint8Array([1,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,n>>24,n>>16&255,n>>8&255,255&n])),gs.trun(t,i.length+16+20+8+16+8+8),i)}static trak(t){return t.duration=t.duration||4294967295,gs.box(gs.types.trak,gs.tkhd(t),gs.mdia(t))}static trex(t){const e=t.id;return gs.box(gs.types.trex,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,e){const i=t.samples||[],r=i.length,s=12+16*r,n=new Uint8Array(s);let a,o,l,h,d,u;for(e+=8+s,n.set(["video"===t.type?1:0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,255&r,e>>>24&255,e>>>16&255,e>>>8&255,255&e],0),a=0;a<r;a++)o=i[a],l=o.duration,h=o.size,d=o.flags,u=o.cts,n.set([l>>>24&255,l>>>16&255,l>>>8&255,255&l,h>>>24&255,h>>>16&255,h>>>8&255,255&h,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,61440&d.degradPrio,15&d.degradPrio,u>>>24&255,u>>>16&255,u>>>8&255,255&u],12+16*a);return gs.box(gs.types.trun,n)}static initSegment(t){gs.types||gs.init();const e=gs.moov(t);return $t(gs.FTYP,e)}}gs.types=void 0,gs.HDLR_TYPES=void 0,gs.STTS=void 0,gs.STSC=void 0,gs.STCO=void 0,gs.STSZ=void 0,gs.VMHD=void 0,gs.SMHD=void 0,gs.STSD=void 0,gs.FTYP=void 0,gs.DINF=void 0;const ms=9e4;function ps(t,e,i=1,r=!1){const s=t*e*i;return r?Math.round(s):s}function vs(t,e=!1){return ps(t,1e3,1/ms,e)}let ys,Es=null,Ts=null;class Ss{constructor(t,e,i,r=""){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=t,this.config=e,this.typeSupported=i,this.ISGenerated=!1,null===Es){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Es=t?parseInt(t[1]):0}if(null===Ts){const t=navigator.userAgent.match(/Safari\/(\d+)/i);Ts=t?parseInt(t[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){_.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=t}resetNextTimestamp(){_.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){_.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(t){let e=!1;const i=t.reduce(((t,i)=>{const r=i.pts-t;return r<-4294967296?(e=!0,As(t,i.pts)):r>0?t:i.pts}),t[0].pts);return e&&_.debug("PTS rollover detected"),i}remux(t,e,i,r,s,n,a,o){let l,h,d,u,c,f,g=s,m=s;const p=t.pid>-1,v=e.pid>-1,y=e.samples.length,E=t.samples.length>0,T=a&&y>0||y>1;if((!p||E)&&(!v||T)||this.ISGenerated||a){if(this.ISGenerated){var S,A,L,R;const t=this.videoTrackConfig;!t||e.width===t.width&&e.height===t.height&&(null==(S=e.pixelRatio)?void 0:S[0])===(null==(A=t.pixelRatio)?void 0:A[0])&&(null==(L=e.pixelRatio)?void 0:L[1])===(null==(R=t.pixelRatio)?void 0:R[1])||this.resetInitSegment()}else d=this.generateIS(t,e,s,n);const i=this.isVideoContiguous;let r,a=-1;if(T&&(a=function(t){for(let e=0;e<t.length;e++)if(t[e].key)return e;return-1}(e.samples),!i&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,a>0){_.warn(`[mp4-remuxer]: Dropped ${a} out of ${y} video samples due to a missing keyframe`);const t=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(a),e.dropped+=a,m+=(e.samples[0].pts-t)/e.inputTimeScale,r=m}else-1===a&&(_.warn(`[mp4-remuxer]: No keyframe found out of ${y} video samples`),f=!1);if(this.ISGenerated){if(E&&T){const i=this.getVideoStartPts(e.samples),r=(As(t.samples[0].pts,i)-i)/e.inputTimeScale;g+=Math.max(0,r),m+=Math.max(0,-r)}if(E){if(t.samplerate||(_.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),d=this.generateIS(t,e,s,n)),h=this.remuxAudio(t,g,this.isAudioContiguous,n,v||T||o===Pe?m:void 0),T){const r=h?h.endPTS-h.startPTS:0;e.inputTimeScale||(_.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),d=this.generateIS(t,e,s,n)),l=this.remuxVideo(e,m,i,r)}}else T&&(l=this.remuxVideo(e,m,i,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=r)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(c=Ls(i,s,this._initPTS,this._initDTS)),r.samples.length&&(u=Rs(r,s,this._initPTS))),{audio:h,video:l,initSegment:d,independent:f,text:u,id3:c}}generateIS(t,e,i,r){const s=t.samples,n=e.samples,a=this.typeSupported,o={},l=this._initPTS;let h,d,u,c=!l||r,f="audio/mp4";if(c&&(h=d=1/0),t.config&&s.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",t.codec=""):a.mp3&&(t.codec="mp3");break;case"ac3":t.codec="ac-3"}o.audio={id:"audio",container:f,codec:t.codec,initSegment:"mp3"===t.segmentCodec&&a.mpeg?new Uint8Array(0):gs.initSegment([t]),metadata:{channelCount:t.channelCount}},c&&(u=t.inputTimeScale,l&&u===l.timescale?c=!1:h=d=s[0].pts-Math.round(u*i))}if(e.sps&&e.pps&&n.length){if(e.timescale=e.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:gs.initSegment([e]),metadata:{width:e.width,height:e.height}},c)if(u=e.inputTimeScale,l&&u===l.timescale)c=!1;else{const t=this.getVideoStartPts(n),e=Math.round(u*i);d=Math.min(d,As(n[0].dts,t)-e),h=Math.min(h,t-e)}this.videoTrackConfig={width:e.width,height:e.height,pixelRatio:e.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,c?(this._initPTS={baseTime:h,timescale:u},this._initDTS={baseTime:d,timescale:u}):h=u=void 0,{tracks:o,initPTS:h,timescale:u}}remuxVideo(t,e,i,r){const s=t.inputTimeScale,n=t.samples,a=[],o=n.length,l=this._initPTS;let h,d,u=this.nextAvcDts,c=8,f=this.videoSampleDuration,g=Number.POSITIVE_INFINITY,m=Number.NEGATIVE_INFINITY,p=!1;if(!i||null===u){const t=e*s,r=n[0].pts-As(n[0].dts,n[0].pts);Es&&null!==u&&Math.abs(t-r-u)<15e3?i=!0:u=t-r}const v=l.baseTime*s/l.timescale;for(let t=0;t<o;t++){const e=n[t];e.pts=As(e.pts-v,u),e.dts=As(e.dts-v,u),e.dts<n[t>0?t-1:t].dts&&(p=!0)}p&&n.sort((function(t,e){const i=t.dts-e.dts,r=t.pts-e.pts;return i||r})),h=n[0].dts,d=n[n.length-1].dts;const y=d-h,E=y?Math.round(y/(o-1)):f||t.inputTimeScale/30;if(i){const t=h-u,i=t>E,r=t<-1;if((i||r)&&(i?_.warn(`AVC: ${vs(t,!0)} ms (${t}dts) hole between fragments detected at ${e.toFixed(3)}`):_.warn(`AVC: ${vs(-t,!0)} ms (${t}dts) overlapping between fragments detected at ${e.toFixed(3)}`),!r||u>=n[0].pts||Es)){h=u;const e=n[0].pts-t;if(i)n[0].dts=h,n[0].pts=e;else for(let i=0;i<n.length&&!(n[i].dts>e);i++)n[i].dts-=t,n[i].pts-=t;_.log(`Video: Initial PTS/DTS adjusted: ${vs(e,!0)}/${vs(h,!0)}, delta: ${vs(t,!0)} ms`)}}h=Math.max(0,h);let S=0,A=0,L=h;for(let t=0;t<o;t++){const e=n[t],i=e.units,r=i.length;let s=0;for(let t=0;t<r;t++)s+=i[t].data.length;A+=s,S+=r,e.length=s,e.dts<L?(e.dts=L,L+=E/4|0||1):L=e.dts,g=Math.min(e.pts,g),m=Math.max(e.pts,m)}d=n[o-1].dts;const D=A+4*S+8;let I;try{I=new Uint8Array(D)}catch(t){return void this.observer.emit(R.ERROR,R.ERROR,{type:b.MUX_ERROR,details:k.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:D,reason:`fail allocating video mdat ${D}`})}const w=new DataView(I.buffer);w.setUint32(0,D),I.set(gs.types.mdat,4);let C=!1,P=Number.POSITIVE_INFINITY,x=Number.POSITIVE_INFINITY,M=Number.NEGATIVE_INFINITY,O=Number.NEGATIVE_INFINITY;for(let t=0;t<o;t++){const e=n[t],i=e.units;let l,h=0;for(let t=0,e=i.length;t<e;t++){const e=i[t],r=e.data,s=e.data.byteLength;w.setUint32(c,s),c+=4,I.set(r,c),c+=s,h+=4+s}if(t<o-1)f=n[t+1].dts-e.dts,l=n[t+1].pts-e.pts;else{const i=this.config,a=t>0?e.dts-n[t-1].dts:E;if(l=t>0?e.pts-n[t-1].pts:E,i.stretchShortVideoTrack&&null!==this.nextAudioPts){const t=Math.floor(i.maxBufferHole*s),n=(r?g+r*s:this.nextAudioPts)-e.pts;n>t?(f=n-a,f<0?f=a:C=!0,_.log(`[mp4-remuxer]: It is approximately ${n/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=a}else f=a}const d=Math.round(e.pts-e.dts);P=Math.min(P,f),M=Math.max(M,f),x=Math.min(x,l),O=Math.max(O,l),a.push(new bs(e.key,f,h,d))}if(a.length)if(Es){if(Es<70){const t=a[0].flags;t.dependsOn=2,t.isNonSync=0}}else if(Ts&&O-x<M-P&&E/M<.025&&0===a[0].cts){_.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let t=h;for(let e=0,i=a.length;e<i;e++){const r=t+a[e].duration,s=t+a[e].cts;if(e<i-1){const t=r+a[e+1].cts;a[e].duration=t-s}else a[e].duration=e?a[e-1].duration:E;a[e].cts=0,t=r}}f=C||!f?E:f,this.nextAvcDts=u=d+f,this.videoSampleDuration=f,this.isVideoContiguous=!0;const F={data1:gs.moof(t.sequenceNumber++,h,T({},t,{samples:a})),data2:I,startPTS:g/s,endPTS:(m+f)/s,startDTS:h/s,endDTS:u/s,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:t.dropped};return t.samples=[],t.dropped=0,F}getSamplesPerFrame(t){switch(t.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(t,e,i,r,s){const n=t.inputTimeScale,a=n/(t.samplerate?t.samplerate:n),o=this.getSamplesPerFrame(t),l=o*a,h=this._initPTS,d="mp3"===t.segmentCodec&&this.typeSupported.mpeg,u=[],c=void 0!==s;let f=t.samples,g=d?0:8,m=this.nextAudioPts||-1;const p=e*n,v=h.baseTime*n/h.timescale;if(this.isAudioContiguous=i=i||f.length&&m>0&&(r&&Math.abs(p-m)<9e3||Math.abs(As(f[0].pts-v,p)-m)<20*l),f.forEach((function(t){t.pts=As(t.pts-v,p)})),!i||m<0){if(f=f.filter((t=>t.pts>=0)),!f.length)return;m=0===s?0:r&&!c?Math.max(0,p):f[0].pts}if("aac"===t.segmentCodec){const e=this.config.maxAudioFramesDrift;for(let i=0,r=m;i<f.length;i++){const s=f[i],a=s.pts,o=a-r,h=Math.abs(1e3*o/n);if(o<=-e*l&&c)0===i&&(_.warn(`Audio frame @ ${(a/n).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*o/n)} ms.`),this.nextAudioPts=m=r=a);else if(o>=e*l&&h<1e4&&c){let e=Math.round(o/l);r=a-e*l,r<0&&(e--,r+=l),0===i&&(this.nextAudioPts=m=r),_.warn(`[mp4-remuxer]: Injecting ${e} audio frame @ ${(r/n).toFixed(3)}s due to ${Math.round(1e3*o/n)} ms gap.`);for(let n=0;n<e;n++){const e=Math.max(r,0);let n=cs.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);n||(_.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),n=s.unit.subarray()),f.splice(i,0,{unit:n,pts:e}),r+=l,i++}}s.pts=r,r+=l}}let y,E=null,S=null,A=0,L=f.length;for(;L--;)A+=f[L].unit.byteLength;for(let e=0,r=f.length;e<r;e++){const r=f[e],s=r.unit;let n=r.pts;if(null!==S){u[e-1].duration=Math.round((n-S)/a)}else{if(i&&"aac"===t.segmentCodec&&(n=m),E=n,!(A>0))return;A+=g;try{y=new Uint8Array(A)}catch(t){return void this.observer.emit(R.ERROR,R.ERROR,{type:b.MUX_ERROR,details:k.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:A,reason:`fail allocating audio mdat ${A}`})}if(!d){new DataView(y.buffer).setUint32(0,A),y.set(gs.types.mdat,4)}}y.set(s,g);const l=s.byteLength;g+=l,u.push(new bs(!0,o,l,0)),S=n}const D=u.length;if(!D)return;const I=u[u.length-1];this.nextAudioPts=m=S+a*I.duration;const w=d?new Uint8Array(0):gs.moof(t.sequenceNumber++,E/a,T({},t,{samples:u}));t.samples=[];const C=E/n,P=m/n,x={data1:w,data2:y,startPTS:C,endPTS:P,startDTS:C,endDTS:P,type:"audio",hasAudio:!0,hasVideo:!1,nb:D};return this.isAudioContiguous=!0,x}remuxEmptyAudio(t,e,i,r){const s=t.inputTimeScale,n=s/(t.samplerate?t.samplerate:s),a=this.nextAudioPts,o=this._initDTS,l=9e4*o.baseTime/o.timescale,h=(null!==a?a:r.startDTS*s)+l,d=r.endDTS*s+l,u=1024*n,c=Math.ceil((d-h)/u),f=cs.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);if(_.warn("[mp4-remuxer]: remux empty Audio"),!f)return void _.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");const g=[];for(let t=0;t<c;t++){const e=h+t*u;g.push({unit:f,pts:e,dts:e})}return t.samples=g,this.remuxAudio(t,e,i,!1)}}function As(t,e){let i;if(null===e)return t;for(i=e<t?-8589934592:8589934592;Math.abs(t-e)>4294967296;)t+=i;return t}function Ls(t,e,i,r){const s=t.samples.length;if(!s)return;const n=t.inputTimeScale;for(let a=0;a<s;a++){const s=t.samples[a];s.pts=As(s.pts-i.baseTime*n/i.timescale,e*n)/n,s.dts=As(s.dts-r.baseTime*n/r.timescale,e*n)/n}const a=t.samples;return t.samples=[],{samples:a}}function Rs(t,e,i){const r=t.samples.length;if(!r)return;const s=t.inputTimeScale;for(let n=0;n<r;n++){const r=t.samples[n];r.pts=As(r.pts-i.baseTime*s/i.timescale,e*s)/s}t.samples.sort(((t,e)=>t.pts-e.pts));const n=t.samples;return t.samples=[],{samples:n}}class bs{constructor(t,e,i,r){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=e,this.size=i,this.cts=r,this.flags={isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1}}}function ks(t,e){const i=null==t?void 0:t.codec;if(i&&i.length>4)return i;if(e===U){if("ec-3"===i||"ac-3"===i||"alac"===i)return i;if("fLaC"===i||"Opus"===i){return ce(i,!1)}const t="mp4a.40.5";return _.info(`Parsed audio codec "${i}" or audio object type not handled. Using "${t}"`),t}return _.warn(`Unhandled video codec "${i}"`),"hvc1"===i||"hev1"===i?"hvc1.1.6.L120.90":"av01"===i?"av01.0.04M.08":"avc1.42e01e"}try{ys=self.performance.now.bind(self.performance)}catch(t){_.debug("Unable to use Performance API on this environment"),ys=null==q?void 0:q.Date.now}const Ds=[{demux:class{constructor(t,e){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=e}resetTimeStamp(){}resetInitSegment(t,e,i,r){const s=this.videoTrack=wr("video",1),n=this.audioTrack=wr("audio",1),a=this.txtTrack=wr("text",1);if(this.id3Track=wr("id3",1),this.timeOffset=0,null==t||!t.byteLength)return;const o=Ft(t);if(o.video){const{id:t,timescale:e,codec:i}=o.video;s.id=t,s.timescale=a.timescale=e,s.codec=i}if(o.audio){const{id:t,timescale:e,codec:i}=o.audio;n.id=t,n.timescale=e,n.codec=i}a.id=Dt.text,s.sampleDuration=0,s.duration=n.duration=r}resetContiguity(){this.remainderData=null}static probe(t){return function(t){const e=t.byteLength;for(let i=0;i<e;){const r=Ct(t,i);if(r>8&&109===t[i+4]&&111===t[i+5]&&111===t[i+6]&&102===t[i+7])return!0;i=r>1?i+r:e}return!1}(t)}demux(t,e){this.timeOffset=e;let i=t;const r=this.videoTrack,s=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=$t(this.remainderData,t));const e=function(t){const e={valid:null,remainder:null},i=Mt(t,["moof"]);if(i.length<2)return e.remainder=t,e;const r=i[i.length-1];return e.valid=at(t,0,r.byteOffset-8),e.remainder=at(t,r.byteOffset-8),e}(i);this.remainderData=e.remainder,r.samples=e.valid||new Uint8Array}else r.samples=i;const n=this.extractID3Track(r,e);return s.samples=Vt(e,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const t=this.timeOffset,e=this.videoTrack,i=this.txtTrack;e.samples=this.remainderData||new Uint8Array,this.remainderData=null;const r=this.extractID3Track(e,this.timeOffset);return i.samples=Vt(t,e),{videoTrack:e,audioTrack:wr(),id3Track:r,textTrack:wr()}}extractID3Track(t,e){const i=this.id3Track;if(t.samples.length){const r=Mt(t.samples,["emsg"]);r&&r.forEach((t=>{const r=function(t){const e=t[0];let i="",r="",s=0,n=0,a=0,o=0,l=0,h=0;if(0===e){for(;"\0"!==It(t.subarray(h,h+1));)i+=It(t.subarray(h,h+1)),h+=1;for(i+=It(t.subarray(h,h+1)),h+=1;"\0"!==It(t.subarray(h,h+1));)r+=It(t.subarray(h,h+1)),h+=1;r+=It(t.subarray(h,h+1)),h+=1,s=Ct(t,12),n=Ct(t,16),o=Ct(t,20),l=Ct(t,24),h=28}else if(1===e){h+=4,s=Ct(t,h),h+=4;const e=Ct(t,h);h+=4;const n=Ct(t,h);for(h+=4,a=2**32*e+n,A(a)||(a=Number.MAX_SAFE_INTEGER,_.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=Ct(t,h),h+=4,l=Ct(t,h),h+=4;"\0"!==It(t.subarray(h,h+1));)i+=It(t.subarray(h,h+1)),h+=1;for(i+=It(t.subarray(h,h+1)),h+=1;"\0"!==It(t.subarray(h,h+1));)r+=It(t.subarray(h,h+1)),h+=1;r+=It(t.subarray(h,h+1)),h+=1}return{schemeIdUri:i,value:r,timeScale:s,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:t.subarray(h,t.byteLength)}}(t);if(zr.test(r.schemeIdUri)){const t=S(r.presentationTime)?r.presentationTime/r.timeScale:e+r.presentationTimeDelta/r.timeScale;let s=4294967295===r.eventDuration?Number.POSITIVE_INFINITY:r.eventDuration/r.timeScale;s<=.001&&(s=Number.POSITIVE_INFINITY);const n=r.payload;i.samples.push({data:n,len:n.byteLength,dts:t,pts:t,type:Ve,duration:s})}}))}return i}demuxSampleAes(t,e,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}},remux:class{constructor(){this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null}destroy(){}resetTimeStamp(t){this.initPTS=t,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(t,e,i,r){this.audioCodec=e,this.videoCodec=i,this.generateInitSegment(function(t,e){if(!t||!e)return t;const i=e.keyId;i&&e.isCommonEncryption&&Mt(t,["moov","trak"]).forEach((t=>{const e=Mt(t,["mdia","minf","stbl","stsd"])[0].subarray(8);let r=Mt(e,["enca"]);const s=r.length>0;s||(r=Mt(e,["encv"])),r.forEach((t=>{Mt(s?t.subarray(28):t.subarray(78),["sinf"]).forEach((t=>{const e=Kt(t);if(e){const t=e.subarray(8,24);t.some((t=>0!==t))||(_.log(`[eme] Patching keyId in 'enc${s?"a":"v"}>sinf>>tenc' box: ${Rt(t)} -> ${Rt(i)}`),e.set(i,8))}}))}))}));return t}(t,r)),this.emitInitSegment=!0}generateInitSegment(t){let{audioCodec:e,videoCodec:i}=this;if(null==t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const r=this.initData=Ft(t);r.audio&&(e=ks(r.audio,U)),r.video&&(i=ks(r.video,B));const s={};r.audio&&r.video?s.audiovideo={container:"video/mp4",codec:e+","+i,initSegment:t,id:"main"}:r.audio?s.audio={container:"audio/mp4",codec:e,initSegment:t,id:"audio"}:r.video?s.video={container:"video/mp4",codec:i,initSegment:t,id:"main"}:_.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=s}remux(t,e,i,r,s,n){var a,o;let{initPTS:l,lastEndTime:h}=this;const d={audio:void 0,video:void 0,text:r,id3:i,initSegment:void 0};S(h)||(h=this.lastEndTime=s||0);const u=e.samples;if(null==u||!u.length)return d;const c={initPTS:void 0,timescale:1};let f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(u),f=this.initData),null==(o=f)||!o.length)return _.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),d;this.emitInitSegment&&(c.tracks=this.initTracks,this.emitInitSegment=!1);const g=function(t,e){let i=0,r=0,s=0;const n=Mt(t,["moof","traf"]);for(let t=0;t<n.length;t++){const a=n[t],o=Mt(a,["tfhd"])[0],l=e[Ct(o,4)];if(!l)continue;const h=l.default,d=Ct(o,0)|(null==h?void 0:h.flags);let u=null==h?void 0:h.duration;8&d&&(u=Ct(o,2&d?12:8));const c=l.timescale||9e4,f=Mt(a,["trun"]);for(let t=0;t<f.length;t++)i=Ht(f[t]),!i&&u&&(i=u*Ct(f[t],4)),l.type===B?r+=i/c:l.type===U&&(s+=i/c)}if(0===r&&0===s){let e=1/0,i=0,r=0;const s=Mt(t,["sidx"]);for(let t=0;t<s.length;t++){const n=Ot(s[t]);if(null!=n&&n.references){e=Math.min(e,n.earliestPresentationTime/n.timescale);const t=n.references.reduce(((t,e)=>t+e.info.duration||0),0);i=Math.max(i,t+n.earliestPresentationTime/n.timescale),r=i-e}}if(r&&S(r))return r}return r||s}(u,f),m=function(t,e){return Mt(e,["moof","traf"]).reduce(((e,i)=>{const r=Mt(i,["tfdt"])[0],s=r[0],n=Mt(i,["tfhd"]).reduce(((e,i)=>{const n=Ct(i,4),a=t[n];if(a){let t=Ct(r,4);if(1===s){if(t===bt)return _.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),e;t*=bt+1,t+=Ct(r,8)}const i=t/(a.timescale||9e4);if(S(i)&&(null===e||i<e))return i}return e}),null);return null!==n&&S(n)&&(null===e||n<e)?n:e}),null)}(f,u),p=null===m?s:m;(function(t,e,i,r){if(null===t)return!0;const s=Math.max(r,1),n=e-t.baseTime/t.timescale;return Math.abs(n-i)>s}(l,p,s,g)||c.timescale!==l.timescale&&n)&&(c.initPTS=p-s,l&&1===l.timescale&&_.warn("Adjusting initPTS by "+(c.initPTS-l.baseTime)),this.initPTS=l={baseTime:c.initPTS,timescale:1});const v=t?p-l.baseTime/l.timescale:h,y=v+g;!function(t,e,i){Mt(e,["moof","traf"]).forEach((e=>{Mt(e,["tfhd"]).forEach((r=>{const s=Ct(r,4),n=t[s];if(!n)return;const a=n.timescale||9e4;Mt(e,["tfdt"]).forEach((t=>{const e=t[0],r=i*a;if(r){let i=Ct(t,4);if(0===e)i-=r,i=Math.max(i,0),xt(t,4,i);else{i*=Math.pow(2,32),i+=Ct(t,8),i-=r,i=Math.max(i,0);const e=Math.floor(i/(bt+1)),s=Math.floor(i%(bt+1));xt(t,4,e),xt(t,8,s)}}}))}))}))}(f,u,l.baseTime/l.timescale),g>0?this.lastEndTime=y:(_.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const E=!!f.audio,T=!!f.video;let A="";E&&(A+="audio"),T&&(A+="video");const L={data1:u,startPTS:v,startDTS:v,endPTS:y,endDTS:y,type:A,hasAudio:E,hasVideo:T,nb:1,dropped:0};return d.audio="audio"===L.type?L:void 0,d.video="audio"!==L.type?L:void 0,d.initSegment=c,d.id3=Ls(i,s,l,l),r.samples.length&&(d.text=Rs(r,s,l)),d}}},{demux:ns,remux:Ss},{demux:class extends Cr{constructor(t,e){super(),this.observer=void 0,this.config=void 0,this.observer=t,this.config=e}resetInitSegment(t,e,i,r){super.resetInitSegment(t,e,i,r),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:e,duration:r,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const e=ht(t,0);let i=(null==e?void 0:e.length)||0;if(Xr(t,i))return!1;for(let e=t.length;i<e;i++)if(Fr(t,i))return _.log("ADTS sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return function(t,e){return e+5<t.length}(t,e)&&Pr(t,e)&&Mr(t,e)<=t.length-e}(t,e)}appendFrame(t,e,i){Nr(t,this.observer,e,i,t.manifestCodec);const r=Br(t,e,i,this.basePTS,this.frameIndex);if(r&&0===r.missing)return r}},remux:Ss},{demux:class extends Cr{resetInitSegment(t,e,i,r){super.resetInitSegment(t,e,i,r),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:e,duration:r,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const e=ht(t,0);let i=(null==e?void 0:e.length)||0;if(e&&11===t[i]&&119===t[i+1]&&void 0!==ct(e)&&Qr(t,i)<=16)return!1;for(let e=t.length;i<e;i++)if(Xr(t,i))return _.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return jr(t,e)&&4<=t.length-e}(t,e)}appendFrame(t,e,i){if(null!==this.basePTS)return Yr(t,e,i,this.basePTS,this.frameIndex)}},remux:Ss}];Ds.splice(2,0,{demux:Jr,remux:Ss});class Is{constructor(t,e,i,r,s){this.async=!1,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=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=e,this.config=i,this.vendor=r,this.id=s}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,e,i,r){const s=i.transmuxing;s.executeStart=ys();let n=new Uint8Array(t);const{currentTransmuxState:a,transmuxConfig:o}=this;r&&(this.currentTransmuxState=r);const{contiguous:l,discontinuity:h,trackSwitch:d,accurateTimeOffset:u,timeOffset:c,initSegmentChange:f}=r||a,{audioCodec:g,videoCodec:m,defaultInitPts:p,duration:v,initSegmentData:y}=o,E=function(t,e){let i=null;t.byteLength>0&&null!=(null==e?void 0:e.key)&&null!==e.iv&&null!=e.method&&(i=e);return i}(n,e);if(E&&"AES-128"===E.method){const t=this.getDecrypter();if(!t.isSync())return this.decryptionPromise=t.webCryptoDecrypt(n,E.key.buffer,E.iv.buffer).then((t=>{const e=this.push(t,null,i);return this.decryptionPromise=null,e})),this.decryptionPromise;{let e=t.softwareDecrypt(n,E.key.buffer,E.iv.buffer);if(i.part>-1&&(e=t.flush()),!e)return s.executeEnd=ys(),ws(i);n=new Uint8Array(e)}}const T=this.needsProbing(h,d);if(T){const t=this.configureTransmuxer(n);if(t)return _.warn(`[transmuxer] ${t.message}`),this.observer.emit(R.ERROR,R.ERROR,{type:b.MEDIA_ERROR,details:k.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message}),s.executeEnd=ys(),ws(i)}(h||d||f||T)&&this.resetInitSegment(y,g,m,v,e),(h||f||T)&&this.resetInitialTimestamp(p),l||this.resetContiguity();const S=this.transmux(n,E,c,u,i),A=this.currentTransmuxState;return A.contiguous=!0,A.discontinuity=!1,A.trackSwitch=!1,s.executeEnd=ys(),S}flush(t){const e=t.transmuxing;e.executeStart=ys();const{decrypter:i,currentTransmuxState:r,decryptionPromise:s}=this;if(s)return s.then((()=>this.flush(t)));const n=[],{timeOffset:a}=r;if(i){const e=i.flush();e&&n.push(this.push(e,null,t))}const{demuxer:o,remuxer:l}=this;if(!o||!l)return e.executeEnd=ys(),[ws(t)];const h=o.flush(a);return Cs(h)?h.then((e=>(this.flushRemux(n,e,t),n))):(this.flushRemux(n,h,t),n)}flushRemux(t,e,i){const{audioTrack:r,videoTrack:s,id3Track:n,textTrack:a}=e,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;_.log(`[transmuxer.ts]: Flushed fragment ${i.sn}${i.part>-1?" p: "+i.part:""} of level ${i.level}`);const h=this.remuxer.remux(r,s,n,a,l,o,!0,this.id);t.push({remuxResult:h,chunkMeta:i}),i.transmuxing.executeEnd=ys()}resetInitialTimestamp(t){const{demuxer:e,remuxer:i}=this;e&&i&&(e.resetTimeStamp(t),i.resetTimeStamp(t))}resetContiguity(){const{demuxer:t,remuxer:e}=this;t&&e&&(t.resetContiguity(),e.resetNextTimestamp())}resetInitSegment(t,e,i,r,s){const{demuxer:n,remuxer:a}=this;n&&a&&(n.resetInitSegment(t,e,i,r),a.resetInitSegment(t,e,i,s))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(t,e,i,r,s){let n;return n=e&&"SAMPLE-AES"===e.method?this.transmuxSampleAes(t,e,i,r,s):this.transmuxUnencrypted(t,i,r,s),n}transmuxUnencrypted(t,e,i,r){const{audioTrack:s,videoTrack:n,id3Track:a,textTrack:o}=this.demuxer.demux(t,e,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(s,n,a,o,e,i,!1,this.id),chunkMeta:r}}transmuxSampleAes(t,e,i,r,s){return this.demuxer.demuxSampleAes(t,e,i).then((t=>({remuxResult:this.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,i,r,!1,this.id),chunkMeta:s})))}configureTransmuxer(t){const{config:e,observer:i,typeSupported:r,vendor:s}=this;let n;for(let e=0,i=Ds.length;e<i;e++){var a;if(null!=(a=Ds[e].demux)&&a.probe(t)){n=Ds[e];break}}if(!n)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,l=this.remuxer,h=n.remux,d=n.demux;l&&l instanceof h||(this.remuxer=new h(i,e,r,s)),o&&o instanceof d||(this.demuxer=new d(i,e,r),this.probe=d.probe)}needsProbing(t,e){return!this.demuxer||!this.remuxer||t||e}getDecrypter(){let t=this.decrypter;return t||(t=this.decrypter=new fr(this.config)),t}}const ws=t=>({remuxResult:{},chunkMeta:t});function Cs(t){return"then"in t&&t.then instanceof Function}class _s{constructor(t,e,i,r,s){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=e,this.initSegmentData=i,this.duration=r,this.defaultInitPts=s||null}}class Ps{constructor(t,e,i,r,s,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=t,this.contiguous=e,this.accurateTimeOffset=i,this.trackSwitch=r,this.timeOffset=s,this.initSegmentChange=n}}var xs={exports:{}};!function(module){var t=Object.prototype.hasOwnProperty,e="~";function i(){}function r(t,e,i){this.fn=t,this.context=e,this.once=i||!1}function s(t,i,s,n,a){if("function"!=typeof s)throw new TypeError("The listener must be a function");var o=new r(s,n||t,a),l=e?e+i:i;return t._events[l]?t._events[l].fn?t._events[l]=[t._events[l],o]:t._events[l].push(o):(t._events[l]=o,t._eventsCount++),t}function n(t,e){0==--t._eventsCount?t._events=new i:delete t._events[e]}function a(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(e=!1)),a.prototype.eventNames=function(){var i,r,s=[];if(0===this._eventsCount)return s;for(r in i=this._events)t.call(i,r)&&s.push(e?r.slice(1):r);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(i)):s},a.prototype.listeners=function(t){var i=e?e+t:t,r=this._events[i];if(!r)return[];if(r.fn)return[r.fn];for(var s=0,n=r.length,a=new Array(n);s<n;s++)a[s]=r[s].fn;return a},a.prototype.listenerCount=function(t){var i=e?e+t:t,r=this._events[i];return r?r.fn?1:r.length:0},a.prototype.emit=function(t,i,r,s,n,a){var o=e?e+t:t;if(!this._events[o])return!1;var l,h,d=this._events[o],u=arguments.length;if(d.fn){switch(d.once&&this.removeListener(t,d.fn,void 0,!0),u){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,i),!0;case 3:return d.fn.call(d.context,i,r),!0;case 4:return d.fn.call(d.context,i,r,s),!0;case 5:return d.fn.call(d.context,i,r,s,n),!0;case 6:return d.fn.call(d.context,i,r,s,n,a),!0}for(h=1,l=new Array(u-1);h<u;h++)l[h-1]=arguments[h];d.fn.apply(d.context,l)}else{var c,f=d.length;for(h=0;h<f;h++)switch(d[h].once&&this.removeListener(t,d[h].fn,void 0,!0),u){case 1:d[h].fn.call(d[h].context);break;case 2:d[h].fn.call(d[h].context,i);break;case 3:d[h].fn.call(d[h].context,i,r);break;case 4:d[h].fn.call(d[h].context,i,r,s);break;default:if(!l)for(c=1,l=new Array(u-1);c<u;c++)l[c-1]=arguments[c];d[h].fn.apply(d[h].context,l)}}return!0},a.prototype.on=function(t,e,i){return s(this,t,e,i,!1)},a.prototype.once=function(t,e,i){return s(this,t,e,i,!0)},a.prototype.removeListener=function(t,i,r,s){var a=e?e+t:t;if(!this._events[a])return this;if(!i)return n(this,a),this;var o=this._events[a];if(o.fn)o.fn!==i||s&&!o.once||r&&o.context!==r||n(this,a);else{for(var l=0,h=[],d=o.length;l<d;l++)(o[l].fn!==i||s&&!o[l].once||r&&o[l].context!==r)&&h.push(o[l]);h.length?this._events[a]=1===h.length?h[0]:h:n(this,a)}return this},a.prototype.removeAllListeners=function(t){var r;return t?(r=e?e+t:t,this._events[r]&&n(this,r)):(this._events=new i,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=e,a.EventEmitter=a,module.exports=a}(xs);var Ms=l(xs.exports);class Os{constructor(t,e,i,r){this.error=null,this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0;const s=t.config;this.hls=t,this.id=e,this.useWorker=!!s.enableWorker,this.onTransmuxComplete=i,this.onFlush=r;const n=(t,e)=>{(e=e||{}).frag=this.frag,e.id=this.id,t===R.ERROR&&(this.error=e.error),this.hls.trigger(t,e)};this.observer=new Ms,this.observer.on(R.FRAG_DECRYPTED,n),this.observer.on(R.ERROR,n);const a=re(s.preferManagedMediaSource)||{isTypeSupported:()=>!1},o={mpeg:a.isTypeSupported("audio/mpeg"),mp3:a.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:a.isTypeSupported('audio/mp4; codecs="ac-3"')};if(this.useWorker&&"undefined"!=typeof Worker){if(s.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{s.workerPath?(_.log(`loading Web Worker ${s.workerPath} for "${e}"`),this.workerContext=function(t){const e=new self.URL(t,self.location.href).href;return{worker:new self.Worker(e),scriptURL:e}}(s.workerPath)):(_.log(`injecting Web Worker for "${e}"`),this.workerContext=function(){const t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),e=self.URL.createObjectURL(t);return{worker:new self.Worker(e),objectURL:e}}()),this.onwmsg=t=>this.onWorkerMessage(t);const{worker:t}=this.workerContext;t.addEventListener("message",this.onwmsg),t.onerror=t=>{const i=new Error(`${t.message} (${t.filename}:${t.lineno})`);s.enableWorker=!1,_.warn(`Error in "${e}" Web Worker, fallback to inline`),this.hls.trigger(R.ERROR,{type:b.OTHER_ERROR,details:k.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:i})},t.postMessage({cmd:"init",typeSupported:o,vendor:"",id:e,config:JSON.stringify(s)})}catch(t){_.warn(`Error setting up "${e}" Web Worker, fallback to inline`,t),this.resetWorker(),this.error=null,this.transmuxer=new Is(this.observer,o,s,"",e)}return}}this.transmuxer=new Is(this.observer,o,s,"",e)}resetWorker(){if(this.workerContext){const{worker:t,objectURL:e}=this.workerContext;e&&self.URL.revokeObjectURL(e),t.removeEventListener("message",this.onwmsg),t.onerror=null,t.terminate(),this.workerContext=null}}destroy(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null}push(t,e,i,r,s,n,a,o,l,h){var d,u;l.transmuxing.start=self.performance.now();const{transmuxer:c}=this,f=n?n.start:s.start,g=s.decryptdata,m=this.frag,p=!(m&&s.cc===m.cc),v=!(m&&l.level===m.level),y=m?l.sn-m.sn:-1,E=this.part?l.part-this.part.index:-1,T=0===y&&l.id>1&&l.id===(null==m?void 0:m.stats.chunkCount),S=!v&&(1===y||0===y&&(1===E||T&&E<=0)),A=self.performance.now();(v||y||0===s.stats.parsing.start)&&(s.stats.parsing.start=A),!n||!E&&S||(n.stats.parsing.start=A);const L=!(m&&(null==(d=s.initSegment)?void 0:d.url)===(null==(u=m.initSegment)?void 0:u.url)),R=new Ps(p,S,o,v,f,L);if(!S||p||L){_.log(`[transmuxer-interface, ${s.type}]: Starting new transmux session for sn: ${l.sn} p: ${l.part} level: ${l.level} id: ${l.id}\n discontinuity: ${p}\n trackSwitch: ${v}\n contiguous: ${S}\n accurateTimeOffset: ${o}\n timeOffset: ${f}\n initSegmentChange: ${L}`);const t=new _s(i,r,e,a,h);this.configureTransmuxer(t)}if(this.frag=s,this.part=n,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:t,decryptdata:g,chunkMeta:l,state:R},t instanceof ArrayBuffer?[t]:[]);else if(c){const e=c.push(t,g,l,R);Cs(e)?(c.async=!0,e.then((t=>{this.handleTransmuxComplete(t)})).catch((t=>{this.transmuxerError(t,l,"transmuxer-interface push error")}))):(c.async=!1,this.handleTransmuxComplete(e))}}flush(t){t.transmuxing.start=self.performance.now();const{transmuxer:e}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:t});else if(e){let i=e.flush(t);Cs(i)||e.async?(Cs(i)||(i=Promise.resolve(i)),i.then((e=>{this.handleFlushResult(e,t)})).catch((e=>{this.transmuxerError(e,t,"transmuxer-interface flush error")}))):this.handleFlushResult(i,t)}}transmuxerError(t,e,i){this.hls&&(this.error=t,this.hls.trigger(R.ERROR,{type:b.MEDIA_ERROR,details:k.FRAG_PARSING_ERROR,chunkMeta:e,frag:this.frag||void 0,fatal:!1,error:t,err:t,reason:i}))}handleFlushResult(t,e){t.forEach((t=>{this.handleTransmuxComplete(t)})),this.onFlush(e)}onWorkerMessage(t){const e=t.data;if(null==e||!e.event)return void _.warn("worker message received with no "+(e?"event name":"data"));const i=this.hls;if(this.hls)switch(e.event){case"init":{var r;const t=null==(r=this.workerContext)?void 0:r.objectURL;t&&self.URL.revokeObjectURL(t);break}case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;case"workerLog":_[e.data.logType]&&_[e.data.logType](e.data.message);break;default:e.data=e.data||{},e.data.frag=this.frag,e.data.id=this.id,i.trigger(e.event,e.data)}}configureTransmuxer(t){const{transmuxer:e}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:t}):e&&e.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}function Fs(t,e){if(t.length!==e.length)return!1;for(let i=0;i<t.length;i++)if(!Ns(t[i].attrs,e[i].attrs))return!1;return!0}function Ns(t,e,i){const r=t["STABLE-RENDITION-ID"];return r&&!i?r===e["STABLE-RENDITION-ID"]:!(i||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some((i=>t[i]!==e[i]))}function Us(t,e){return e.label.toLowerCase()===t.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(t.lang||"").toLowerCase())}class Bs{constructor(t){this.buffered=void 0;const e=(e,i,r)=>{if((i>>>=0)>r-1)throw new DOMException(`Failed to execute '${e}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${r})`);return t[i][e]};this.buffered={get length(){return t.length},end:i=>e("end",i,t.length),start:i=>e("start",i,t.length)}}}class Gs{constructor(t){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=t}append(t,e,i){const r=this.queues[e];r.push(t),1!==r.length||i||this.executeNext(e)}insertAbort(t,e){this.queues[e].unshift(t),this.executeNext(e)}appendBlocker(t){let e;const i=new Promise((t=>{e=t})),r={execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(r,t),i}executeNext(t){const e=this.queues[t];if(e.length){const i=e[0];try{i.execute()}catch(e){_.warn(`[buffer-operation-queue]: Exception executing "${t}" SourceBuffer operation: ${e}`),i.onError(e);const r=this.buffers[t];null!=r&&r.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){this.queues[t].shift(),this.executeNext(t)}current(t){return this.queues[t][0]}}const Ks=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;function Hs(t){const e=t.querySelectorAll("source");[].slice.call(e).forEach((e=>{t.removeChild(e)}))}const $s={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},Vs=t=>String.fromCharCode($s[t]||t),Ys=15,Ws=100,js={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},qs={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Xs={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},zs={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Qs=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Js{constructor(){this.time=null,this.verboseLevel=0}log(t,e){if(this.verboseLevel>=t){const i="function"==typeof e?e():e;_.log(`${this.time} [${t}] ${i}`)}}}const Zs=function(t){const e=[];for(let i=0;i<t.length;i++)e.push(t[i].toString(16));return e};class tn{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(t){const e=["foreground","underline","italics","background","flash"];for(let i=0;i<e.length;i++){const r=e[i];t.hasOwnProperty(r)&&(this[r]=t[r])}}isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}equals(t){return this.foreground===t.foreground&&this.underline===t.underline&&this.italics===t.italics&&this.background===t.background&&this.flash===t.flash}copy(t){this.foreground=t.foreground,this.underline=t.underline,this.italics=t.italics,this.background=t.background,this.flash=t.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class en{constructor(){this.uchar=" ",this.penState=new tn}reset(){this.uchar=" ",this.penState.reset()}setChar(t,e){this.uchar=t,this.penState.copy(e)}setPenState(t){this.penState.copy(t)}equals(t){return this.uchar===t.uchar&&this.penState.equals(t.penState)}copy(t){this.uchar=t.uchar,this.penState.copy(t.penState)}isEmpty(){return" "===this.uchar&&this.penState.isDefault()}}class rn{constructor(t){this.chars=[],this.pos=0,this.currPenState=new tn,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Ws;t++)this.chars.push(new en);this.logger=t}equals(t){for(let e=0;e<Ws;e++)if(!this.chars[e].equals(t.chars[e]))return!1;return!0}copy(t){for(let e=0;e<Ws;e++)this.chars[e].copy(t.chars[e])}isEmpty(){let t=!0;for(let e=0;e<Ws;e++)if(!this.chars[e].isEmpty()){t=!1;break}return t}setCursor(t){this.pos!==t&&(this.pos=t),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>Ws&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Ws)}moveCursor(t){const e=this.pos+t;if(t>1)for(let t=this.pos+1;t<e+1;t++)this.chars[t].setPenState(this.currPenState);this.setCursor(e)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(t){t>=144&&this.backSpace();const e=Vs(t);this.pos>=Ws?this.logger.log(0,(()=>"Cannot insert "+t.toString(16)+" ("+e+") at position "+this.pos+". Skipping it!")):(this.chars[this.pos].setChar(e,this.currPenState),this.moveCursor(1))}clearFromPos(t){let e;for(e=t;e<Ws;e++)this.chars[e].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const t=[];let e=!0;for(let i=0;i<Ws;i++){const r=this.chars[i].uchar;" "!==r&&(e=!1),t.push(r)}return e?"":t.join("")}setPenStyles(t){this.currPenState.setStyles(t);this.chars[this.pos].setPenState(this.currPenState)}}class sn{constructor(t){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let e=0;e<Ys;e++)this.rows.push(new rn(t));this.logger=t}reset(){for(let t=0;t<Ys;t++)this.rows[t].clear();this.currRow=14}equals(t){let e=!0;for(let i=0;i<Ys;i++)if(!this.rows[i].equals(t.rows[i])){e=!1;break}return e}copy(t){for(let e=0;e<Ys;e++)this.rows[e].copy(t.rows[e])}isEmpty(){let t=!0;for(let e=0;e<Ys;e++)if(!this.rows[e].isEmpty()){t=!1;break}return t}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(t){this.rows[this.currRow].insertChar(t)}setPen(t){this.rows[this.currRow].setPenStyles(t)}moveCursor(t){this.rows[this.currRow].moveCursor(t)}setCursor(t){this.logger.log(2,"setCursor: "+t);this.rows[this.currRow].setCursor(t)}setPAC(t){this.logger.log(2,(()=>"pacData = "+JSON.stringify(t)));let e=t.row-1;if(this.nrRollUpRows&&e<this.nrRollUpRows-1&&(e=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==e){for(let t=0;t<Ys;t++)this.rows[t].clear();const t=this.currRow+1-this.nrRollUpRows,i=this.lastOutputScreen;if(i){const r=i.rows[t].cueStartTime,s=this.logger.time;if(null!==r&&null!==s&&r<s)for(let r=0;r<this.nrRollUpRows;r++)this.rows[e-this.nrRollUpRows+r+1].copy(i.rows[t+r])}}this.currRow=e;const i=this.rows[this.currRow];if(null!==t.indent){const e=t.indent,r=Math.max(e-1,0);i.setCursor(t.indent),t.color=i.chars[r].penState.foreground}const r={foreground:t.color,underline:t.underline,italics:t.italics,background:"black",flash:!1};this.setPen(r)}setBkgData(t){this.logger.log(2,(()=>"bkgData = "+JSON.stringify(t))),this.backSpace(),this.setPen(t),this.insertChar(32)}setRollUpRows(t){this.nrRollUpRows=t}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,(()=>this.getDisplayText()));const t=this.currRow+1-this.nrRollUpRows,e=this.rows.splice(t,1)[0];e.clear(),this.rows.splice(this.currRow,0,e),this.logger.log(2,"Rolling up")}getDisplayText(t){t=t||!1;const e=[];let i="",r=-1;for(let i=0;i<Ys;i++){const s=this.rows[i].getTextString();s&&(r=i+1,t?e.push("Row "+r+": '"+s+"'"):e.push(s.trim()))}return e.length>0&&(i=t?"["+e.join(" | ")+"]":e.join("\n")),i}getTextAndFormat(){return this.rows}}class nn{constructor(t,e,i){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=t,this.outputFilter=e,this.mode=null,this.verbose=0,this.displayedMemory=new sn(i),this.nonDisplayedMemory=new sn(i),this.lastOutputScreen=new sn(i),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(t){this.outputFilter=t}setPAC(t){this.writeScreen.setPAC(t)}setBkgData(t){this.writeScreen.setBkgData(t)}setMode(t){t!==this.mode&&(this.mode=t,this.logger.log(2,(()=>"MODE="+t)),"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=t)}insertChars(t){for(let e=0;e<t.length;e++)this.writeScreen.insertChar(t[e]);const e=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,(()=>e+": "+this.writeScreen.getDisplayText(!0))),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,(()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0))),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(t){this.logger.log(2,"RU("+t+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(t)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){const t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,(()=>"DISP: "+this.displayedMemory.getDisplayText()))}this.outputDataUpdate(!0)}ccTO(t){this.logger.log(2,"TO("+t+") - Tab Offset"),this.writeScreen.moveCursor(t)}ccMIDROW(t){const e={flash:!1};if(e.underline=t%2==1,e.italics=t>=46,e.italics)e.foreground="white";else{const i=Math.floor(t/2)-16,r=["white","green","blue","cyan","red","yellow","magenta"];e.foreground=r[i]}this.logger.log(2,"MIDROW: "+JSON.stringify(e)),this.writeScreen.setPen(e)}outputDataUpdate(t=!1){const e=this.logger.time;null!==e&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,e,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:e):this.cueStartTime=e,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))}}class an{constructor(t,e,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;const r=this.logger=new Js;this.channels=[null,new nn(t,e,r),new nn(t+1,i,r)]}getHandler(t){return this.channels[t].getHandler()}setHandler(t,e){this.channels[t].setHandler(e)}addData(t,e){this.logger.time=t;for(let t=0;t<e.length;t+=2){const i=127&e[t],r=127&e[t+1];let s=!1,n=null;if(0===i&&0===r)continue;this.logger.log(3,(()=>"["+Zs([e[t],e[t+1]])+"] -> ("+Zs([i,r])+")"));const a=this.cmdHistory;if(i>=16&&i<=31){if(ln(i,r,a)){on(null,null,a),this.logger.log(3,(()=>"Repeated command ("+Zs([i,r])+") is dropped"));continue}on(i,r,this.cmdHistory),s=this.parseCmd(i,r),s||(s=this.parseMidrow(i,r)),s||(s=this.parsePAC(i,r)),s||(s=this.parseBackgroundAttributes(i,r))}else on(null,null,a);if(!s&&(n=this.parseChars(i,r),n)){const t=this.currentChannel;if(t&&t>0){this.channels[t].insertChars(n)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}s||n||this.logger.log(2,(()=>"Couldn't parse cleaned data "+Zs([i,r])+" orig: "+Zs([e[t],e[t+1]])))}}parseCmd(t,e){if(!((20===t||28===t||21===t||29===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=33&&e<=35))return!1;const i=20===t||21===t||23===t?1:2,r=this.channels[i];return 20===t||21===t||28===t||29===t?32===e?r.ccRCL():33===e?r.ccBS():34===e?r.ccAOF():35===e?r.ccAON():36===e?r.ccDER():37===e?r.ccRU(2):38===e?r.ccRU(3):39===e?r.ccRU(4):40===e?r.ccFON():41===e?r.ccRDC():42===e?r.ccTR():43===e?r.ccRTD():44===e?r.ccEDM():45===e?r.ccCR():46===e?r.ccENM():47===e&&r.ccEOC():r.ccTO(e-32),this.currentChannel=i,!0}parseMidrow(t,e){let i=0;if((17===t||25===t)&&e>=32&&e<=47){if(i=17===t?1:2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const r=this.channels[i];return!!r&&(r.ccMIDROW(e),this.logger.log(3,(()=>"MIDROW ("+Zs([t,e])+")")),!0)}return!1}parsePAC(t,e){let i;if(!((t>=17&&t<=23||t>=25&&t<=31)&&e>=64&&e<=127)&&!((16===t||24===t)&&e>=64&&e<=95))return!1;const r=t<=23?1:2;i=e>=64&&e<=95?1===r?js[t]:Xs[t]:1===r?qs[t]:zs[t];const s=this.channels[r];return!!s&&(s.setPAC(this.interpretPAC(i,e)),this.currentChannel=r,!0)}interpretPAC(t,e){let i;const r={color:null,italics:!1,indent:null,underline:!1,row:t};return i=e>95?e-96:e-64,r.underline=!(1&~i),i<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(r.italics=!0,r.color="white"):r.indent=4*Math.floor((i-16)/2),r}parseChars(t,e){let i,r=null,s=null;if(t>=25?(i=2,s=t-8):(i=1,s=t),s>=17&&s<=19){let t;t=17===s?e+80:18===s?e+112:e+144,this.logger.log(2,(()=>"Special char '"+Vs(t)+"' in channel "+i)),r=[t]}else t>=32&&t<=127&&(r=0===e?[t]:[t,e]);return r&&this.logger.log(3,(()=>"Char codes = "+Zs(r).join(","))),r}parseBackgroundAttributes(t,e){if(!((16===t||24===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=45&&e<=47))return!1;let i;const r={};16===t||24===t?(i=Math.floor((e-32)/2),r.background=Qs[i],e%2==1&&(r.background=r.background+"_semi")):45===e?r.background="transparent":(r.foreground="black",47===e&&(r.underline=!0));const s=t<=23?1:2;return this.channels[s].setBkgData(r),!0}reset(){for(let t=0;t<Object.keys(this.channels).length;t++){const e=this.channels[t];e&&e.reset()}on(null,null,this.cmdHistory)}cueSplitAtTime(t){for(let e=0;e<this.channels.length;e++){const i=this.channels[e];i&&i.cueSplitAtTime(t)}}}function on(t,e,i){i.a=t,i.b=e}function ln(t,e,i){return i.a===t&&i.b===e}class hn{constructor(t,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=e}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(t,e,i){(null===this.startTime||this.startTime>t)&&(this.startTime=t),this.endTime=e,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}var dn=function(){if(null!=q&&q.VTTCue)return self.VTTCue;const t=["","lr","rl"],e=["start","middle","end","left","right"];function i(t,e){if("string"!=typeof e)return!1;if(!Array.isArray(t))return!1;const i=e.toLowerCase();return!!~t.indexOf(i)&&i}function r(t){return i(e,t)}function s(t,...e){let i=1;for(;i<arguments.length;i++){const e=arguments[i];for(const i in e)t[i]=e[i]}return t}function n(e,n,a){const o=this,l={enumerable:!0};o.hasBeenReset=!1;let h="",d=!1,u=e,c=n,f=a,g=null,m="",p=!0,v="auto",y="start",E=50,T="middle",S=50,A="middle";Object.defineProperty(o,"id",s({},l,{get:function(){return h},set:function(t){h=""+t}})),Object.defineProperty(o,"pauseOnExit",s({},l,{get:function(){return d},set:function(t){d=!!t}})),Object.defineProperty(o,"startTime",s({},l,{get:function(){return u},set:function(t){if("number"!=typeof t)throw new TypeError("Start time must be set to a number.");u=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",s({},l,{get:function(){return c},set:function(t){if("number"!=typeof t)throw new TypeError("End time must be set to a number.");c=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",s({},l,{get:function(){return f},set:function(t){f=""+t,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",s({},l,{get:function(){return g},set:function(t){g=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",s({},l,{get:function(){return m},set:function(e){const r=function(e){return i(t,e)}(e);if(!1===r)throw new SyntaxError("An invalid or illegal string was specified.");m=r,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",s({},l,{get:function(){return p},set:function(t){p=!!t,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",s({},l,{get:function(){return v},set:function(t){if("number"!=typeof t&&"auto"!==t)throw new SyntaxError("An invalid number or illegal string was specified.");v=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",s({},l,{get:function(){return y},set:function(t){const e=r(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");y=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",s({},l,{get:function(){return E},set:function(t){if(t<0||t>100)throw new Error("Position must be between 0 and 100.");E=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",s({},l,{get:function(){return T},set:function(t){const e=r(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",s({},l,{get:function(){return S},set:function(t){if(t<0||t>100)throw new Error("Size must be between 0 and 100.");S=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",s({},l,{get:function(){return A},set:function(t){const e=r(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");A=e,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}();class un{decode(t,e){if(!t)return"";if("string"!=typeof t)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function cn(t){function e(t,e,i,r){return 3600*(0|t)+60*(0|e)+(0|i)+parseFloat(r||0)}const i=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return i?parseFloat(i[2])>59?e(i[2],i[3],0,i[4]):e(i[1],i[2],i[3],i[4]):null}class fn{constructor(){this.values=Object.create(null)}set(t,e){this.get(t)||""===e||(this.values[t]=e)}get(t,e,i){return i?this.has(t)?this.values[t]:e[i]:this.has(t)?this.values[t]:e}has(t){return t in this.values}alt(t,e,i){for(let r=0;r<i.length;++r)if(e===i[r]){this.set(t,e);break}}integer(t,e){/^-?\d+$/.test(e)&&this.set(t,parseInt(e,10))}percent(t,e){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(e)){const i=parseFloat(e);if(i>=0&&i<=100)return this.set(t,i),!0}return!1}}function gn(t,e,i,r){const s=r?t.split(r):[t];for(const t in s){if("string"!=typeof s[t])continue;const r=s[t].split(i);if(2!==r.length)continue;e(r[0],r[1])}}const mn=new dn(0,0,""),pn="middle"===mn.align?"middle":"center";function vn(t,e,i){const r=t;function s(){const e=cn(t);if(null===e)throw new Error("Malformed timestamp: "+r);return t=t.replace(/^[^\sa-zA-Z-]+/,""),e}function n(){t=t.replace(/^\s+/,"")}if(n(),e.startTime=s(),n(),"--\x3e"!==t.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+r);t=t.slice(3),n(),e.endTime=s(),n(),function(t,e){const r=new fn;gn(t,(function(t,e){let s;switch(t){case"region":for(let s=i.length-1;s>=0;s--)if(i[s].id===e){r.set(t,i[s].region);break}break;case"vertical":r.alt(t,e,["rl","lr"]);break;case"line":s=e.split(","),r.integer(t,s[0]),r.percent(t,s[0])&&r.set("snapToLines",!1),r.alt(t,s[0],["auto"]),2===s.length&&r.alt("lineAlign",s[1],["start",pn,"end"]);break;case"position":s=e.split(","),r.percent(t,s[0]),2===s.length&&r.alt("positionAlign",s[1],["start",pn,"end","line-left","line-right","auto"]);break;case"size":r.percent(t,e);break;case"align":r.alt(t,e,["start",pn,"end","left","right"])}}),/:/,/\s/),e.region=r.get("region",null),e.vertical=r.get("vertical","");let s=r.get("line","auto");"auto"===s&&-1===mn.line&&(s=-1),e.line=s,e.lineAlign=r.get("lineAlign","start"),e.snapToLines=r.get("snapToLines",!0),e.size=r.get("size",100),e.align=r.get("align",pn);let n=r.get("position","auto");"auto"===n&&50===mn.position&&(n="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=n}(t,e)}function yn(t){return t.replace(/<br(?: \/)?>/gi,"\n")}class En{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new un,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(t){const e=this;function i(){let t=e.buffer,i=0;for(t=yn(t);i<t.length&&"\r"!==t[i]&&"\n"!==t[i];)++i;const r=t.slice(0,i);return"\r"===t[i]&&++i,"\n"===t[i]&&++i,e.buffer=t.slice(i),r}t&&(e.buffer+=e.decoder.decode(t,{stream:!0}));try{let t="";if("INITIAL"===e.state){if(!/\r\n|\n/.test(e.buffer))return this;t=i();const r=t.match(/^()?WEBVTT([ \t].*)?$/);if(null==r||!r[0])throw new Error("Malformed WebVTT signature.");e.state="HEADER"}let r=!1;for(;e.buffer;){if(!/\r\n|\n/.test(e.buffer))return this;switch(r?r=!1:t=i(),e.state){case"HEADER":/:/.test(t)?gn(t,(function(t,e){}),/:/):t||(e.state="ID");continue;case"NOTE":t||(e.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(t)){e.state="NOTE";break}if(!t)continue;if(e.cue=new dn(0,0,""),e.state="CUE",-1===t.indexOf("--\x3e")){e.cue.id=t;continue}case"CUE":if(!e.cue){e.state="BADCUE";continue}try{vn(t,e.cue,e.regionList)}catch(t){e.cue=null,e.state="BADCUE";continue}e.state="CUETEXT";continue;case"CUETEXT":{const i=-1!==t.indexOf("--\x3e");if(!t||i&&(r=!0)){e.oncue&&e.cue&&e.oncue(e.cue),e.cue=null,e.state="ID";continue}if(null===e.cue)continue;e.cue.text&&(e.cue.text+="\n"),e.cue.text+=t}continue;case"BADCUE":t||(e.state="ID")}}}catch(t){"CUETEXT"===e.state&&e.cue&&e.oncue&&e.oncue(e.cue),e.cue=null,e.state="INITIAL"===e.state?"BADWEBVTT":"BADCUE"}return this}flush(){const t=this;try{if((t.cue||"HEADER"===t.state)&&(t.buffer+="\n\n",t.parse()),"INITIAL"===t.state||"BADWEBVTT"===t.state)throw new Error("Malformed WebVTT signature.")}catch(e){t.onparsingerror&&t.onparsingerror(e)}return t.onflush&&t.onflush(),this}}const Tn=/\r\n|\n\r|\n|\r/g,Sn=function(t,e,i=0){return t.slice(i,i+e.length)===e},An=function(t){let e=5381,i=t.length;for(;i;)e=33*e^t.charCodeAt(--i);return(e>>>0).toString()};function Ln(t,e,i){return An(t.toString())+An(e.toString())+An(i)}function Rn(t,e,i,r,s,n,a){const o=new En,l=St(new Uint8Array(t)).trim().replace(Tn,"\n").split("\n"),h=[],d=e?function(t,e=1){return ps(t,ms,1/e)}(e.baseTime,e.timescale):0;let u,c="00:00.000",f=0,g=0,m=!0;o.oncue=function(t){const n=i[r];let a=i.ccOffset;const o=(f-d)/9e4;if(null!=n&&n.new&&(void 0!==g?a=i.ccOffset=n.start:function(t,e,i){let r=t[e],s=t[r.prevCC];if(!s||!s.new&&r.new)return t.ccOffset=t.presentationOffset=r.start,void(r.new=!1);for(;null!=(n=s)&&n.new;){var n;t.ccOffset+=r.start-s.start,r.new=!1,r=s,s=t[r.prevCC]}t.presentationOffset=i}(i,r,o)),o){if(!e)return void(u=new Error("Missing initPTS for VTT MPEGTS"));a=o-i.presentationOffset}const l=t.endTime-t.startTime,c=As(9e4*(t.startTime+a-g),9e4*s)/9e4;t.startTime=Math.max(c,0),t.endTime=Math.max(c+l,0);const m=t.text.trim();t.text=decodeURIComponent(encodeURIComponent(m)),t.id||(t.id=Ln(t.startTime,t.endTime,m)),t.endTime>0&&h.push(t)},o.onparsingerror=function(t){u=t},o.onflush=function(){u?a(u):n(h)},l.forEach((t=>{if(m){if(Sn(t,"X-TIMESTAMP-MAP=")){m=!1,t.slice(16).split(",").forEach((t=>{Sn(t,"LOCAL:")?c=t.slice(6):Sn(t,"MPEGTS:")&&(f=parseInt(t.slice(7)))}));try{g=function(t){let e=parseInt(t.slice(-3));const i=parseInt(t.slice(-6,-4)),r=parseInt(t.slice(-9,-7)),s=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!(S(e)&&S(i)&&S(r)&&S(s)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return e+=1e3*i,e+=6e4*r,e+=36e5*s,e}(c)/1e3}catch(t){u=t}return}""===t&&(m=!1)}o.parse(t+"\n")})),o.flush()}const bn="stpp.ttml.im1t",kn=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Dn=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,In={left:"start",center:"center",right:"end",start:"start",end:"end"};function wn(t,e,i,r){const s=Mt(new Uint8Array(t),["mdat"]);if(0===s.length)return void r(new Error("Could not parse IMSC1 mdat"));const n=s.map((t=>St(t))),a=function(t,e,i=1,r=!1){return ps(t,e,1/i,r)}(e.baseTime,1,e.timescale);try{n.forEach((t=>i(function(t,e){const i=(new DOMParser).parseFromString(t,"text/xml"),r=i.getElementsByTagName("tt")[0];if(!r)throw new Error("Invalid ttml");const s={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(s).reduce(((t,e)=>(t[e]=r.getAttribute(`ttp:${e}`)||s[e],t)),{}),a="preserve"!==r.getAttribute("xml:space"),o=_n(Cn(r,"styling","style")),l=_n(Cn(r,"layout","region")),h=Cn(r,"body","[begin]");return[].map.call(h,(t=>{const i=Pn(t,a);if(!i||!t.hasAttribute("begin"))return null;const r=On(t.getAttribute("begin"),n),s=On(t.getAttribute("dur"),n);let h=On(t.getAttribute("end"),n);if(null===r)throw Mn(t);if(null===h){if(null===s)throw Mn(t);h=r+s}const d=new dn(r-e,h-e,i);d.id=Ln(d.startTime,d.endTime,d.text);const u=function(t,e,i){const r="http://www.w3.org/ns/ttml#styling";let s=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=t&&t.hasAttribute("style")?t.getAttribute("style"):null;a&&i.hasOwnProperty(a)&&(s=i[a]);return n.reduce(((i,n)=>{const a=xn(e,r,n)||xn(t,r,n)||xn(s,r,n);return a&&(i[n]=a),i}),{})}(l[t.getAttribute("region")],o[t.getAttribute("style")],o),{textAlign:c}=u;if(c){const t=In[c];t&&(d.lineAlign=t),d.align=c}return T(d,u),d})).filter((t=>null!==t))}(t,a))))}catch(t){r(t)}}function Cn(t,e,i){const r=t.getElementsByTagName(e)[0];return r?[].slice.call(r.querySelectorAll(i)):[]}function _n(t){return t.reduce(((t,e)=>{const i=e.getAttribute("xml:id");return i&&(t[i]=e),t}),{})}function Pn(t,e){return[].slice.call(t.childNodes).reduce(((t,i,r)=>{var s;return"br"===i.nodeName&&r?t+"\n":null!=(s=i.childNodes)&&s.length?Pn(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent}),"")}function xn(t,e,i){return t&&t.hasAttributeNS(e,i)?t.getAttributeNS(e,i):null}function Mn(t){return new Error(`Could not parse ttml timestamp ${t}`)}function On(t,e){if(!t)return null;let i=cn(t);return null===i&&(kn.test(t)?i=function(t,e){const i=kn.exec(t),r=(0|i[4])+(0|i[5])/e.subFrameRate;return 3600*(0|i[1])+60*(0|i[2])+(0|i[3])+r/e.frameRate}(t,e):Dn.test(t)&&(i=function(t,e){const i=Dn.exec(t),r=Number(i[1]);switch(i[2]){case"h":return 3600*r;case"m":return 60*r;case"ms":return 1e3*r;case"f":return r/e.frameRate;case"t":return r/e.tickRate}return r}(t,e))),i}function Fn(t){return t.characteristics&&/transcribes-spoken-dialog/gi.test(t.characteristics)&&/describes-music-and-sound/gi.test(t.characteristics)?"captions":"subtitles"}function Nn(t,e){return!!t&&t.kind===Fn(e)&&Us(e,t)}class Un{constructor(t){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(t){this.streamController=t}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:t}=this;t.on(R.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(R.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(R.MANIFEST_PARSED,this.onManifestParsed,this),t.on(R.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(R.BUFFER_CODECS,this.onBufferCodecs,this),t.on(R.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(R.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(R.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(R.MANIFEST_PARSED,this.onManifestParsed,this),t.off(R.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(R.BUFFER_CODECS,this.onBufferCodecs,this),t.off(R.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,e){const i=this.hls.levels[e.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(t,e){this.media=e.media instanceof HTMLVideoElement?e.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(t,e){const i=this.hls;this.restrictedLevels=[],this.firstLevel=e.firstLevel,i.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onLevelsUpdated(t,e){this.timer&&S(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(t,e){this.hls.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);const t=this.hls.levels;if(t.length){const e=this.hls,i=this.getMaxLevel(t.length-1);i!==this.autoLevelCapping&&_.log(`Setting autoLevelCapping to ${i}: ${t[i].height}p@${t[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),e.autoLevelCapping=i,e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}}}getMaxLevel(t){const e=this.hls.levels;if(!e.length)return-1;const i=e.filter(((e,i)=>this.isLevelAllowed(e)&&i<=t));return this.clientRect=null,Un.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const t=this.media,e={width:0,height:0};if(t){const i=t.getBoundingClientRect();e.width=i.width,e.height=i.height,e.width||e.height||(e.width=i.right-i.left||t.width||0,e.height=i.bottom-i.top||t.height||0)}return this.clientRect=e,e}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let t=1;if(!this.hls.config.ignoreDevicePixelRatio)try{t=self.devicePixelRatio}catch(t){}return t}isLevelAllowed(t){return!this.restrictedLevels.some((e=>t.bitrate===e.bitrate&&t.width===e.width&&t.height===e.height))}static getMaxLevelByMediaSize(t,e,i){if(null==t||!t.length)return-1;let r=t.length-1;const s=Math.max(e,i);for(let e=0;e<t.length;e+=1){const i=t[e];if((i.width>=s||i.height>=s)&&(n=i,!(a=t[e+1])||n.width!==a.width||n.height!==a.height)){r=e;break}}var n,a;return r}}const Bn="[eme]";class Gn{constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=Gn.CDMCleanupPromise?[Gn.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=_.debug.bind(_,Bn),this.log=_.log.bind(_,Bn),this.warn=_.warn.bind(_,Bn),this.error=_.error.bind(_,Bn),this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null}registerListeners(){this.hls.on(R.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(R.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(R.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(R.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(R.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(R.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(R.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(R.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(t){const{drmSystems:e,widevineLicenseUrl:i}=this.config,r=e[t];if(r)return r.licenseUrl;if(t===X.WIDEVINE&&i)return i;throw new Error(`no license server URL configured for key-system "${t}"`)}getServerCertificateUrl(t){const{drmSystems:e}=this.config,i=e[t];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${t}"]`)}attemptKeySystemAccess(t){const e=this.hls.levels,i=(t,e,i)=>!!t&&i.indexOf(t)===e,r=e.map((t=>t.audioCodec)).filter(i),s=e.map((t=>t.videoCodec)).filter(i);return r.length+s.length===0&&s.push("avc1.42e01e"),new Promise(((e,i)=>{const n=t=>{const a=t.shift();this.getMediaKeysPromise(a,r,s).then((t=>e({keySystem:a,mediaKeys:t}))).catch((e=>{t.length?n(t):i(e instanceof Kn?e:new Kn({type:b.KEY_SYSTEM_ERROR,details:k.KEY_SYSTEM_NO_ACCESS,error:e,fatal:!0},e.message))}))};n(t)}))}requestMediaKeySystemAccess(t,e){const{requestMediaKeySystemAccessFunc:i}=this.config;if("function"!=typeof i){let t=`Configured requestMediaKeySystemAccess is not a function ${i}`;return null===st&&"http:"===self.location.protocol&&(t=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(t))}return i(t,e)}getMediaKeysPromise(t,e,i){const r=function(t,e,i,r){let s;switch(t){case X.FAIRPLAY:s=["cenc","sinf"];break;case X.WIDEVINE:case X.PLAYREADY:s=["cenc"];break;case X.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${t}`)}return function(t,e,i,r){return[{initDataTypes:t,persistentState:r.persistentState||"optional",distinctiveIdentifier:r.distinctiveIdentifier||"optional",sessionTypes:r.sessionTypes||[r.sessionType||"temporary"],audioCapabilities:e.map((t=>({contentType:`audio/mp4; codecs="${t}"`,robustness:r.audioRobustness||"",encryptionScheme:r.audioEncryptionScheme||null}))),videoCapabilities:i.map((t=>({contentType:`video/mp4; codecs="${t}"`,robustness:r.videoRobustness||"",encryptionScheme:r.videoEncryptionScheme||null})))}]}(s,e,i,r)}(t,e,i,this.config.drmSystemOptions),s=this.keySystemAccessPromises[t];let n=null==s?void 0:s.keySystemAccess;if(!n){this.log(`Requesting encrypted media "${t}" key-system access with config: ${JSON.stringify(r)}`),n=this.requestMediaKeySystemAccess(t,r);const e=this.keySystemAccessPromises[t]={keySystemAccess:n};return n.catch((e=>{this.log(`Failed to obtain access to key-system "${t}": ${e}`)})),n.then((i=>{this.log(`Access for key-system "${i.keySystem}" obtained`);const r=this.fetchServerCertificate(t);return this.log(`Create media-keys for "${t}"`),e.mediaKeys=i.createMediaKeys().then((e=>(this.log(`Media-keys created for "${t}"`),r.then((i=>i?this.setMediaKeysServerCertificate(e,t,i):e))))),e.mediaKeys.catch((e=>{this.error(`Failed to create media-keys for "${t}"}: ${e}`)})),e.mediaKeys}))}return n.then((()=>s.mediaKeys))}createMediaKeySessionContext({decryptdata:t,keySystem:e,mediaKeys:i}){this.log(`Creating key-system session "${e}" keyId: ${Rt(t.keyId||[])}`);const r=i.createSession(),s={decryptdata:t,keySystem:e,mediaKeys:i,mediaKeysSession:r,keyStatus:"status-pending"};return this.mediaKeySessions.push(s),s}renewKeySession(t){const e=t.decryptdata;if(e.pssh){const i=this.createMediaKeySessionContext(t),r=this.getKeyIdString(e),s="cenc";this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(i,s,e.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)}getKeyIdString(t){if(!t)throw new Error("Could not read keyId of undefined decryptdata");if(null===t.keyId)throw new Error("keyId is null");return Rt(t.keyId)}updateKeySession(t,e){var i;const r=t.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyID ${Rt((null==(i=t.decryptdata)?void 0:i.keyId)||[])}\n } (data length: ${e?e.byteLength:e})`),r.update(e)}selectKeySystemFormat(t){const e=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${t.sn} ${t.type}: ${t.level}) key formats ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)),this.keyFormatPromise}getKeyFormatPromise(t){return new Promise(((e,i)=>{const r=rt(this.config),s=t.map(tt).filter((t=>!!t&&-1!==r.indexOf(t)));return this.getKeySystemSelectionPromise(s).then((({keySystem:t})=>{const r=it(t);r?e(r):i(new Error(`Unable to find format for key-system "${t}"`))})).catch(i)}))}loadKey(t){const e=t.keyInfo.decryptdata,i=this.getKeyIdString(e),r=`(keyId: ${i} format: "${e.keyFormat}" method: ${e.method} uri: ${e.uri})`;this.log(`Starting session for key ${r}`);let s=this.keyIdToKeySessionPromise[i];return s||(s=this.keyIdToKeySessionPromise[i]=this.getKeySystemForKeyPromise(e).then((({keySystem:i,mediaKeys:s})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${r}`),this.attemptSetMediaKeys(i,s).then((()=>{this.throwIfDestroyed();const t=this.createMediaKeySessionContext({keySystem:i,mediaKeys:s,decryptdata:e});return this.generateRequestWithPreferredKeySession(t,"cenc",e.pssh,"playlist-key")}))))),s.catch((t=>this.handleError(t)))),s}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t){this.hls&&(this.error(t.message),t instanceof Kn?this.hls.trigger(R.ERROR,t.data):this.hls.trigger(R.ERROR,{type:b.KEY_SYSTEM_ERROR,details:k.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0}))}getKeySystemForKeyPromise(t){const e=this.getKeyIdString(t),i=this.keyIdToKeySessionPromise[e];if(!i){const e=tt(t.keyFormat),i=e?[e]:rt(this.config);return this.attemptKeySystemAccess(i)}return i}getKeySystemSelectionPromise(t){if(t.length||(t=rt(this.config)),0===t.length)throw new Kn({type:b.KEY_SYSTEM_ERROR,details:k.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}_onMediaEncrypted(t){const{initDataType:e,initData:i}=t;if(this.debug(`"${t.type}" event: init data type: "${e}"`),null===i)return;let r,s;if("sinf"===e&&this.config.drmSystems[X.FAIRPLAY]){const t=It(new Uint8Array(i));try{const e=Y(JSON.parse(t).sinf),i=Kt(new Uint8Array(e));if(!i)return;r=i.subarray(8,24),s=X.FAIRPLAY}catch(t){return void this.warn('Failed to parse sinf "encrypted" event message initData')}}else{const t=function(t){if(!(t instanceof ArrayBuffer)||t.byteLength<32)return null;const e={version:0,systemId:"",kids:null,data:null},i=new DataView(t),r=i.getUint32(0);if(t.byteLength!==r&&r>44)return null;if(1886614376!==i.getUint32(4))return null;if(e.version=i.getUint32(8)>>>24,e.version>1)return null;e.systemId=Rt(new Uint8Array(t,12,16));const s=i.getUint32(28);if(0===e.version){if(r-32<s)return null;e.data=new Uint8Array(t,32,s)}else if(1===e.version){e.kids=[];for(let i=0;i<s;i++)e.kids.push(new Uint8Array(t,32+16*i,16))}return e}(i);if(null===t)return;0===t.version&&t.systemId===et&&t.data&&(r=t.data.subarray(8,24)),s=function(t){if(t===et)return X.WIDEVINE}(t.systemId)}if(!s||!r)return;const n=Rt(r),{keyIdToKeySessionPromise:a,mediaKeySessions:o}=this;let l=a[n];for(let t=0;t<o.length;t++){const s=o[t],h=s.decryptdata;if(h.pssh||!h.keyId)continue;const d=Rt(h.keyId);if(n===d||-1!==h.uri.replace(/-/g,"").indexOf(n)){l=a[d],delete a[d],h.pssh=new Uint8Array(i),h.keyId=r,l=a[n]=l.then((()=>this.generateRequestWithPreferredKeySession(s,e,i,"encrypted-event-key-match")));break}}l||(l=a[n]=this.getKeySystemSelectionPromise([s]).then((({keySystem:t,mediaKeys:s})=>{var a;this.throwIfDestroyed();const o=new zt("ISO-23001-7",n,null!=(a=it(t))?a:"");return o.pssh=new Uint8Array(i),o.keyId=r,this.attemptSetMediaKeys(t,s).then((()=>{this.throwIfDestroyed();const r=this.createMediaKeySessionContext({decryptdata:o,keySystem:t,mediaKeys:s});return this.generateRequestWithPreferredKeySession(r,e,i,"encrypted-event-no-match")}))}))),l.catch((t=>this.handleError(t)))}_onWaitingForKey(t){this.log(`"${t.type}" event`)}attemptSetMediaKeys(t,e){const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const r=Promise.all(i).then((()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(e)}));return this.setMediaKeysQueue.push(r),r.then((()=>{this.log(`Media-keys set for "${t}"`),i.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter((t=>-1===i.indexOf(t)))}))}generateRequestWithPreferredKeySession(t,e,i,r){var s,n;const a=null==(s=this.config.drmSystems)||null==(n=s[t.keySystem])?void 0:n.generateRequest;if(a)try{const r=a.call(this.hls,e,i,t);if(!r)throw new Error("Invalid response from configured generateRequest filter");e=r.initDataType,i=t.decryptdata.pssh=r.initData?new Uint8Array(r.initData):null}catch(t){var o;if(this.warn(t.message),null!=(o=this.hls)&&o.config.debug)throw t}if(null===i)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(t);const l=this.getKeyIdString(t.decryptdata);this.log(`Generating key-session request for "${r}": ${l} (init data type: ${e} length: ${i?i.byteLength:null})`);const h=new Ms,d=t._onmessage=e=>{const i=t.mediaKeysSession;if(!i)return void h.emit("error",new Error("invalid state"));const{messageType:r,message:s}=e;this.log(`"${r}" message event for session "${i.sessionId}" message size: ${s.byteLength}`),"license-request"===r||"license-renewal"===r?this.renewLicense(t,s).catch((t=>{this.handleError(t),h.emit("error",t)})):"license-release"===r?t.keySystem===X.FAIRPLAY&&(this.updateKeySession(t,j("acknowledged")),this.removeSession(t)):this.warn(`unhandled media key message type "${r}"`)},u=t._onkeystatuseschange=e=>{if(!t.mediaKeysSession)return void h.emit("error",new Error("invalid state"));this.onKeyStatusChange(t);const i=t.keyStatus;h.emit("keyStatus",i),"expired"===i&&(this.warn(`${t.keySystem} expired for key ${l}`),this.renewKeySession(t))};t.mediaKeysSession.addEventListener("message",d),t.mediaKeysSession.addEventListener("keystatuseschange",u);const c=new Promise(((t,e)=>{h.on("error",e),h.on("keyStatus",(i=>{i.startsWith("usable")?t():"output-restricted"===i?e(new Kn({type:b.KEY_SYSTEM_ERROR,details:k.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===i?e(new Kn({type:b.KEY_SYSTEM_ERROR,details:k.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${i}"`)):"expired"===i?e(new Error("key expired while generating request")):this.warn(`unhandled key status change "${i}"`)}))}));return t.mediaKeysSession.generateRequest(e,i).then((()=>{var e;this.log(`Request generated for key-session "${null==(e=t.mediaKeysSession)?void 0:e.sessionId}" keyId: ${l}`)})).catch((t=>{throw new Kn({type:b.KEY_SYSTEM_ERROR,details:k.KEY_SYSTEM_NO_SESSION,error:t,fatal:!1},`Error generating key-session request: ${t}`)})).then((()=>c)).catch((e=>{throw h.removeAllListeners(),this.removeSession(t),e})).then((()=>(h.removeAllListeners(),t)))}onKeyStatusChange(t){t.mediaKeysSession.keyStatuses.forEach(((e,i)=>{this.log(`key status change "${e}" for keyStatuses keyId: ${Rt("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${Rt(new Uint8Array(t.decryptdata.keyId||[]))} uri: ${t.decryptdata.uri}`),t.keyStatus=e}))}fetchServerCertificate(t){const e=this.config,i=new(0,e.loader)(e),r=this.getServerCertificateUrl(t);return r?(this.log(`Fetching server certificate for "${t}"`),new Promise(((s,n)=>{const a={responseType:"arraybuffer",url:r},o=e.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(t,e,i,r)=>{s(t.data)},onError:(e,i,s,o)=>{n(new Kn({type:b.KEY_SYSTEM_ERROR,details:k.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:v({url:a.url,data:void 0},e)},`"${t}" certificate request failed (${r}). Status: ${e.code} (${e.text})`))},onTimeout:(e,i,s)=>{n(new Kn({type:b.KEY_SYSTEM_ERROR,details:k.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:{url:a.url,data:void 0}},`"${t}" certificate request timed out (${r})`))},onAbort:(t,e,i)=>{n(new Error("aborted"))}};i.load(a,l,h)}))):Promise.resolve()}setMediaKeysServerCertificate(t,e,i){return new Promise(((r,s)=>{t.setServerCertificate(i).then((s=>{this.log(`setServerCertificate ${s?"success":"not supported by CDM"} (${null==i?void 0:i.byteLength}) on "${e}"`),r(t)})).catch((t=>{s(new Kn({type:b.KEY_SYSTEM_ERROR,details:k.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:t,fatal:!0},t.message))}))}))}renewLicense(t,e){return this.requestLicense(t,new Uint8Array(e)).then((e=>this.updateKeySession(t,new Uint8Array(e)).catch((t=>{throw new Kn({type:b.KEY_SYSTEM_ERROR,details:k.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:t,fatal:!0},t.message)}))))}unpackPlayReadyKeyMessage(t,e){const i=String.fromCharCode.apply(null,new Uint16Array(e.buffer));if(!i.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),e;const r=(new DOMParser).parseFromString(i,"application/xml"),s=r.querySelectorAll("HttpHeader");if(s.length>0){let e;for(let i=0,r=s.length;i<r;i++){var n,a;e=s[i];const r=null==(n=e.querySelector("name"))?void 0:n.textContent,o=null==(a=e.querySelector("value"))?void 0:a.textContent;r&&o&&t.setRequestHeader(r,o)}}const o=r.querySelector("Challenge"),l=null==o?void 0:o.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return j(atob(l))}setupLicenseXHR(t,e,i,r){const s=this.config.licenseXhrSetup;return s?Promise.resolve().then((()=>{if(!i.decryptdata)throw new Error("Key removed");return s.call(this.hls,t,e,i,r)})).catch((n=>{if(!i.decryptdata)throw n;return t.open("POST",e,!0),s.call(this.hls,t,e,i,r)})).then((i=>{t.readyState||t.open("POST",e,!0);return{xhr:t,licenseChallenge:i||r}})):(t.open("POST",e,!0),Promise.resolve({xhr:t,licenseChallenge:r}))}requestLicense(t,e){const i=this.config.keyLoadPolicy.default;return new Promise(((r,s)=>{const n=this.getLicenseServerUrl(t.keySystem);this.log(`Sending license request to URL: ${n}`);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return s(new Error("invalid state"));if(4===a.readyState)if(200===a.status){this._requestLicenseFailureCount=0;let e=a.response;this.log(`License received ${e instanceof ArrayBuffer?e.byteLength:e}`);const i=this.config.licenseResponseCallback;if(i)try{e=i.call(this.hls,a,n,t)}catch(t){this.error(t)}r(e)}else{const o=i.errorRetry,l=o?o.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||a.status>=400&&a.status<500)s(new Kn({type:b.KEY_SYSTEM_ERROR,details:k.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:a,response:{url:n,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${n}). Status: ${a.status} (${a.statusText})`));else{const i=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${i} attempts left`),this.requestLicense(t,e).then(r,s)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=a,this.setupLicenseXHR(a,n,t,e).then((({xhr:e,licenseChallenge:i})=>{t.keySystem==X.PLAYREADY&&(i=this.unpackPlayReadyKeyMessage(e,i)),e.send(i)}))}))}onMediaAttached(t,e){if(!this.config.emeEnabled)return;const i=e.media;this.media=i,i.addEventListener("encrypted",this.onMediaEncrypted),i.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const t=this.media,e=this.mediaKeySessions;t&&(t.removeEventListener("encrypted",this.onMediaEncrypted),t.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},zt.clearKeyUriToKeyIdMap();const i=e.length;Gn.CDMCleanupPromise=Promise.all(e.map((t=>this.removeSession(t))).concat(null==t?void 0:t.setMediaKeys(null).catch((t=>{this.log(`Could not clear media keys: ${t}`)})))).then((()=>{i&&(this.log("finished closing key sessions and clearing media keys"),e.length=0)})).catch((t=>{this.log(`Could not close sessions and clear media keys: ${t}`)}))}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(t,{sessionKeys:e}){if(e&&this.config.emeEnabled&&!this.keyFormatPromise){const t=e.reduce(((t,e)=>(-1===t.indexOf(e.keyFormat)&&t.push(e.keyFormat),t)),[]);this.log(`Selecting key-system from session-keys ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)}}removeSession(t){const{mediaKeysSession:e,licenseXhr:i}=t;if(e){this.log(`Remove licenses and keys and close session ${e.sessionId}`),t._onmessage&&(e.removeEventListener("message",t._onmessage),t._onmessage=void 0),t._onkeystatuseschange&&(e.removeEventListener("keystatuseschange",t._onkeystatuseschange),t._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(t);return r>-1&&this.mediaKeySessions.splice(r,1),e.remove().catch((t=>{this.log(`Could not remove session: ${t}`)})).then((()=>e.close())).catch((t=>{this.log(`Could not close session: ${t}`)}))}}}Gn.CDMCleanupPromise=void 0;class Kn extends Error{constructor(t,e){super(e),this.data=void 0,t.error||(t.error=new Error(e)),this.data=t,t.err=t.error}}var Hn,$n,Vn;!function(t){t.MANIFEST="m",t.AUDIO="a",t.VIDEO="v",t.MUXED="av",t.INIT="i",t.CAPTION="c",t.TIMED_TEXT="tt",t.KEY="k",t.OTHER="o"}(Hn||(Hn={})),function(t){t.DASH="d",t.HLS="h",t.SMOOTH="s",t.OTHER="o"}($n||($n={})),function(t){t.OBJECT="CMCD-Object",t.REQUEST="CMCD-Request",t.SESSION="CMCD-Session",t.STATUS="CMCD-Status"}(Vn||(Vn={}));const Yn={[Vn.OBJECT]:["br","d","ot","tb"],[Vn.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[Vn.SESSION]:["cid","pr","sf","sid","st","v"],[Vn.STATUS]:["bs","rtp"]};class Wn{constructor(t,e){this.value=void 0,this.params=void 0,Array.isArray(t)&&(t=t.map((t=>t instanceof Wn?t:new Wn(t)))),this.value=t,this.params=e}}class jn{constructor(t){this.description=void 0,this.description=t}}const qn="Dict";function Xn(t,e,i,r){return new Error(`failed to ${t} "${s=e,Array.isArray(s)?JSON.stringify(s):s instanceof Map?"Map{}":s instanceof Set?"Set{}":"object"==typeof s?JSON.stringify(s):String(s)}" as ${i}`,{cause:r});var s}const zn="Bare Item",Qn="Boolean",Jn="Byte Sequence",Zn="Decimal",ta="Integer";const ea=/[\x00-\x1f\x7f]+/,ia="Token",ra="Key";function sa(t,e,i){return Xn("serialize",t,e,i)}function na(t){if(!1===ArrayBuffer.isView(t))throw sa(t,Jn);return`:${e=t,btoa(String.fromCharCode(...e))}:`;var e}function aa(t){if(function(t){return t<-999999999999999||999999999999999<t}(t))throw sa(t,ta);return t.toString()}function oa(t,e){if(t<0)return-oa(-t,e);const i=Math.pow(10,e);if(Math.abs(t*i%1-.5)<Number.EPSILON){const e=Math.floor(t*i);return(e%2==0?e:e+1)/i}return Math.round(t*i)/i}function la(t){const e=oa(t,3);if(Math.floor(Math.abs(e)).toString().length>12)throw sa(t,Zn);const i=e.toString();return i.includes(".")?i:`${i}.0`}const ha="String";function da(t){const e=(i=t).description||i.toString().slice(7,-1);var i;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e))throw sa(e,ia);return e}function ua(t){switch(typeof t){case"number":if(!S(t))throw sa(t,zn);return Number.isInteger(t)?aa(t):la(t);case"string":return function(t){if(ea.test(t))throw sa(t,ha);return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(t);case"symbol":return da(t);case"boolean":return function(t){if("boolean"!=typeof t)throw sa(t,Qn);return t?"?1":"?0"}(t);case"object":if(t instanceof Date)return function(t){return`@${aa(t.getTime()/1e3)}`}(t);if(t instanceof Uint8Array)return na(t);if(t instanceof jn)return da(t);default:throw sa(t,zn)}}function ca(t){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(t))throw sa(t,ra);return t}function fa(t){return null==t?"":Object.entries(t).map((([t,e])=>!0===e?`;${ca(t)}`:`;${ca(t)}=${ua(e)}`)).join("")}function ga(t){return t instanceof Wn?`${ua(t.value)}${fa(t.params)}`:ua(t)}function ma(t,e={whitespace:!0}){if("object"!=typeof t)throw sa(t,qn);const i=t instanceof Map?t.entries():Object.entries(t),r=null!=e&&e.whitespace?" ":"";return Array.from(i).map((([t,e])=>{e instanceof Wn==!1&&(e=new Wn(e));let i=ca(t);var r;return!0===e.value?i+=fa(e.params):(i+="=",Array.isArray(e.value)?i+=`(${(r=e).value.map(ga).join(" ")})${fa(r.params)}`:i+=ga(e)),i})).join(`,${r}`)}const pa=t=>"ot"===t||"sf"===t||"st"===t,va=t=>"number"==typeof t?S(t):null!=t&&""!==t&&!1!==t;const ya=t=>Math.round(t),Ea=t=>100*ya(t/100),Ta={br:ya,d:ya,bl:Ea,dl:Ea,mtp:Ea,nor:(t,e)=>(null!=e&&e.baseUrl&&(t=function(t,e){const i=new URL(t),r=new URL(e);if(i.origin!==r.origin)return t;const s=i.pathname.split("/").slice(1),n=r.pathname.split("/").slice(1,-1);for(;s[0]===n[0];)s.shift(),n.shift();for(;n.length;)n.shift(),s.unshift("..");return s.join("/")}(t,e.baseUrl)),encodeURIComponent(t)),rtp:Ea,tb:ya};function Sa(t,e={}){return t?function(t,e){return ma(t,e)}(function(t,e){const i={};if(null==t||"object"!=typeof t)return i;const r=Object.keys(t).sort(),s=T({},Ta,null==e?void 0:e.formatters),n=null==e?void 0:e.filter;return r.forEach((r=>{if(null!=n&&n(r))return;let a=t[r];const o=s[r];o&&(a=o(a,e)),"v"===r&&1===a||"pr"==r&&1===a||va(a)&&(pa(r)&&"string"==typeof a&&(a=new jn(a)),i[r]=a)})),i}(t,e),T({whitespace:!1},e)):""}function Aa(t,e,i){return T(t,function(t,e={}){if(!t)return{};const i=Object.entries(t),r=Object.entries(Yn).concat(Object.entries((null==e?void 0:e.customHeaderMap)||{})),s=i.reduce(((t,e)=>{var i;const[s,n]=e,a=(null==(i=r.find((t=>t[1].includes(s))))?void 0:i[0])||Vn.REQUEST;return null!=t[a]||(t[a]={}),t[a][s]=n,t}),{});return Object.entries(s).reduce(((t,[i,r])=>(t[i]=Sa(r,e),t)),{})}(e,i))}const La="CMCD";const Ra=/CMCD=[^&#]+/;function ba(t,e,i){const r=function(t,e={}){if(!t)return"";const i=Sa(t,e);return`${La}=${encodeURIComponent(i)}`}(e,i);if(!r)return t;if(Ra.test(t))return t.replace(Ra,r);const s=t.includes("?")?"&":"?";return`${t}${s}${r}`}function ka(t,e,i,r){t&&Object.keys(e).forEach((s=>{const n=t.filter((t=>t.groupId===s)).map((t=>{const n=T({},t);return n.details=void 0,n.attrs=new M(n.attrs),n.url=n.attrs.URI=Da(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),n.groupId=n.attrs["GROUP-ID"]=e[s],n.attrs["PATHWAY-ID"]=r,n}));t.push(...n)}))}function Da(t,e,i,r){const{HOST:s,PARAMS:n,[i]:a}=r;let o;e&&(o=null==a?void 0:a[e],o&&(t=o));const l=new self.URL(t);return s&&!o&&(l.host=s),n&&Object.keys(n).sort().forEach((t=>{t&&l.searchParams.set(t,n[t])})),l.href}const Ia=/^age:\s*[\d.]+\s*$/im;class wa{constructor(t){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=t&&t.xhrSetup||null,this.stats=new N,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,4!==t.readyState&&(this.stats.aborted=!0,t.abort()))}abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(t,e,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=t,this.config=e,this.callbacks=i,this.loadInternal()}loadInternal(){const{config:t,context:e}=this;if(!t||!e)return;const i=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;const s=this.xhrSetup;s?Promise.resolve().then((()=>{if(this.loader===i&&!this.stats.aborted)return s(i,e.url)})).catch((t=>{if(this.loader===i&&!this.stats.aborted)return i.open("GET",e.url,!0),s(i,e.url)})).then((()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,e,t)})).catch((t=>{this.callbacks.onError({code:i.status,text:t.message},e,i,r)})):this.openAndSendXhr(i,e,t)}openAndSendXhr(t,e,i){t.readyState||t.open("GET",e.url,!0);const r=e.headers,{maxTimeToFirstByteMs:s,maxLoadTimeMs:n}=i.loadPolicy;if(r)for(const e in r)t.setRequestHeader(e,r[e]);e.rangeEnd&&t.setRequestHeader("Range","bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=e.responseType,self.clearTimeout(this.requestTimeout),i.timeout=s&&S(s)?s:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),t.send()}readystatechange(){const{context:t,loader:e,stats:i}=this;if(!t||!e)return;const r=e.readyState,s=this.config;if(!i.aborted&&r>=2&&(0===i.loading.first&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),s.timeout!==s.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),s.timeout=s.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),4===r)){self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;const r=e.status,n="text"!==e.responseType;if(r>=200&&r<300&&(n&&e.response||null!==e.responseText)){i.loading.end=Math.max(self.performance.now(),i.loading.first);const s=n?e.response:e.responseText,a="arraybuffer"===e.responseType?s.byteLength:s.length;if(i.loaded=i.total=a,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first),!this.callbacks)return;const o=this.callbacks.onProgress;if(o&&o(i,t,s,e),!this.callbacks)return;const l={url:e.responseURL,data:s,code:r};this.callbacks.onSuccess(l,i,t,e)}else{const n=s.loadPolicy.errorRetry;yi(n,i.retry,!1,{url:t.url,data:void 0,code:r})?this.retry(n):(_.error(`${r} while loading ${t.url}`),this.callbacks.onError({code:r,text:e.statusText},t,e,i))}}}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry;if(yi(t,this.stats.retry,!0))this.retry(t);else{var e;_.warn(`timeout while loading ${null==(e=this.context)?void 0:e.url}`);const t=this.callbacks;t&&(this.abortInternal(),t.onTimeout(this.stats,this.context,this.loader))}}retry(t){const{context:e,stats:i}=this;this.retryDelay=pi(t,i.retry),i.retry++,_.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==e?void 0:e.url}, retrying ${i.retry}/${t.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(t){const e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)}getCacheAge(){let t=null;if(this.loader&&Ia.test(this.loader.getAllResponseHeaders())){const e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.loader&&new RegExp(`^${t}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(t):null}}const Ca=/(\d+)-(\d+)\/(\d+)/;class _a{constructor(t){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=t.fetchSetup||Pa,this.controller=new self.AbortController,this.stats=new N}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(t,e,i){const r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now();const s=function(t,e){const i={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(T({},t.headers))};t.rangeEnd&&i.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1));return i}(t,this.controller.signal),n=i.onProgress,a="arraybuffer"===t.responseType,o=a?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:h}=e.loadPolicy;this.context=t,this.config=e,this.callbacks=i,this.request=this.fetchSetup(t,s),self.clearTimeout(this.requestTimeout),e.timeout=l&&S(l)?l:h,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),i.onTimeout(r,t,this.response)}),e.timeout),self.fetch(this.request).then((s=>{this.response=this.loader=s;const o=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=h,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),i.onTimeout(r,t,this.response)}),h-(o-r.loading.start)),!s.ok){const{status:t,statusText:e}=s;throw new xa(e||"fetch, bad network response",t,s)}return r.loading.first=o,r.total=function(t){const e=t.get("Content-Range");if(e){const t=function(t){const e=Ca.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}(e);if(S(t))return t}const i=t.get("Content-Length");if(i)return parseInt(i)}(s.headers)||r.total,n&&S(e.highWaterMark)?this.loadProgressively(s,r,t,e.highWaterMark,n):a?s.arrayBuffer():"json"===t.responseType?s.json():s.text()})).then((s=>{const a=this.response;if(!a)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);const l=s[o];l&&(r.loaded=r.total=l);const h={url:a.url,data:s,code:a.status};n&&!S(e.highWaterMark)&&n(r,t,s,a),i.onSuccess(h,r,t,a)})).catch((e=>{if(self.clearTimeout(this.requestTimeout),r.aborted)return;const s=e&&e.code||0,n=e?e.message:null;i.onError({code:s,text:n},t,e?e.details:null,r)}))}getCacheAge(){let t=null;if(this.response){const e=this.response.headers.get("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,e,i,r=0,s){const n=new Ir,a=t.body.getReader(),o=()=>a.read().then((a=>{if(a.done)return n.dataLength&&s(e,i,n.flush(),t),Promise.resolve(new ArrayBuffer(0));const l=a.value,h=l.length;return e.loaded+=h,h<r||n.dataLength?(n.push(l),n.dataLength>=r&&s(e,i,n.flush(),t)):s(e,i,l,t),o()})).catch((()=>Promise.reject()));return o()}}function Pa(t,e){return new self.Request(t.url,e)}class xa extends Error{constructor(t,e,i){super(t),this.code=void 0,this.details=void 0,this.code=e,this.details=i}}const Ma=/\s/,Oa={newCue(t,e,i,r){const s=[];let n,a,o,l,h;const d=self.VTTCue||self.TextTrackCue;for(let c=0;c<r.rows.length;c++)if(n=r.rows[c],o=!0,l=0,h="",!n.isEmpty()){var u;for(let t=0;t<n.chars.length;t++)Ma.test(n.chars[t].uchar)&&o?l++:(h+=n.chars[t].uchar,o=!1);n.cueStartTime=e,e===i&&(i+=1e-4),l>=16?l--:l++;const r=yn(h.trim()),f=Ln(e,i,r);null!=t&&null!=(u=t.cues)&&u.getCueById(f)||(a=new d(e,i,r),a.id=f,a.line=c+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),s.push(a))}return t&&s.length&&(s.sort(((t,e)=>"auto"===t.line||"auto"===e.line?0:t.line>8&&e.line>8?e.line-t.line:t.line-e.line)),s.forEach((e=>Ue(t,e)))),s}},Fa=v(v({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:6e7,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:wa,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class{constructor(t){this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this._abandonRulesCheck=()=>{const{fragCurrent:t,partCurrent:e,hls:i}=this,{autoLevelEnabled:r,media:s}=i;if(!t||!s)return;const n=performance.now(),a=e?e.stats:t.stats,o=e?e.duration:t.duration,l=n-a.loading.start,h=i.minAutoLevel;if(a.aborted||a.loaded&&a.loaded===a.total||t.level<=h)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!r||s.paused||!s.playbackRate||!s.readyState)return;const d=i.mainForwardBufferInfo;if(null===d)return;const u=this.bwEstimator.getEstimateTTFB(),c=Math.abs(s.playbackRate);if(l<=Math.max(u,o/(2*c)*1e3))return;const f=d.len/c,g=a.loading.first?a.loading.first-a.loading.start:-1,m=a.loaded&&g>-1,p=this.getBwEstimate(),v=i.levels,y=v[t.level],E=a.total||Math.max(a.loaded,Math.round(o*y.averageBitrate/8));let T=m?l-g:l;T<1&&m&&(T=Math.min(l,8*a.loaded/p));const A=m?1e3*a.loaded/T:0,L=A?(E-a.loaded)/A:8*E/p+u/1e3;if(L<=f)return;const b=A?8*A:p;let k,D=Number.POSITIVE_INFINITY;for(k=t.level-1;k>h;k--){const t=v[k].maxBitrate;if(D=this.getTimeToLoadFrag(u/1e3,b,o*t,!v[k].details),D<f)break}if(D>=L)return;if(D>10*o)return;i.nextLoadLevel=i.nextAutoLevel=k,m?this.bwEstimator.sample(l-Math.min(u,g),a.loaded):this.bwEstimator.sampleTTFB(l);const I=v[k].maxBitrate;this.getBwEstimate()*this.hls.config.abrBandWidthUpFactor>I&&this.resetEstimator(I),this.clearTimer(),_.warn(`[abr] Fragment ${t.sn}${e?" part "+e.index:""} of level ${t.level} is loading too slowly;\n Time to underbuffer: ${f.toFixed(3)} s\n Estimated load time for current fragment: ${L.toFixed(3)} s\n Estimated load time for down switch fragment: ${D.toFixed(3)} s\n TTFB estimate: ${0|g} ms\n Current BW estimate: ${S(p)?0|p:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${k} @ ${0|I} bps`),i.trigger(R.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:e,stats:a})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(t){t&&(_.log(`setting initial bwe to ${t}`),this.hls.config.abrEwmaDefaultEstimate=t),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const t=this.hls.config;return new Pi(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(R.MANIFEST_LOADING,this.onManifestLoading,this),t.on(R.FRAG_LOADING,this.onFragLoading,this),t.on(R.FRAG_LOADED,this.onFragLoaded,this),t.on(R.FRAG_BUFFERED,this.onFragBuffered,this),t.on(R.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(R.LEVEL_LOADED,this.onLevelLoaded,this),t.on(R.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(R.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(R.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(R.MANIFEST_LOADING,this.onManifestLoading,this),t.off(R.FRAG_LOADING,this.onFragLoading,this),t.off(R.FRAG_LOADED,this.onFragLoaded,this),t.off(R.FRAG_BUFFERED,this.onFragBuffered,this),t.off(R.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(R.LEVEL_LOADED,this.onLevelLoaded,this),t.off(R.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(R.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(R.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(t,e){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(t,e){const i=e.frag;if(!this.ignoreFragment(i)){var r;if(!i.bitrateTest)this.fragCurrent=i,this.partCurrent=null!=(r=e.part)?r:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(t,e){this.clearTimer()}onError(t,e){if(!e.fatal)switch(e.details){case k.BUFFER_ADD_CODEC_ERROR:case k.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case k.FRAG_LOAD_TIMEOUT:{const t=e.frag,{fragCurrent:i,partCurrent:r}=this;if(t&&i&&t.sn===i.sn&&t.level===i.level){const e=performance.now(),i=r?r.stats:t.stats,s=e-i.loading.start,n=i.loading.first?i.loading.first-i.loading.start:-1;if(i.loaded&&n>-1){const t=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(s-Math.min(t,n),i.loaded)}else this.bwEstimator.sampleTTFB(s)}break}}}getTimeToLoadFrag(t,e,i,r){return t+i/e+(r?this.lastLevelLoadSec:0)}onLevelLoaded(t,e){const i=this.hls.config,{loading:r}=e.stats,s=r.end-r.start;S(s)&&(this.lastLevelLoadSec=s/1e3),e.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD)}onFragLoaded(t,{frag:e,part:i}){const r=i?i.stats:e.stats;if(e.type===_e&&this.bwEstimator.sampleTTFB(r.loading.first-r.loading.start),!this.ignoreFragment(e)){if(this.clearTimer(),e.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const t=i?i.duration:e.duration,s=this.hls.levels[e.level],n=(s.loaded?s.loaded.bytes:0)+r.loaded,a=(s.loaded?s.loaded.duration:0)+t;s.loaded={bytes:n,duration:a},s.realBitrate=Math.round(8*n/a)}if(e.bitrateTest){const t={stats:r,frag:e,part:i,id:e.type};this.onFragBuffered(R.FRAG_BUFFERED,t),e.bitrateTest=!1}else this.lastLoadedFragLevel=e.level}}onFragBuffered(t,e){const{frag:i,part:r}=e,s=null!=r&&r.stats.loaded?r.stats:i.stats;if(s.aborted)return;if(this.ignoreFragment(i))return;const n=s.parsing.end-s.loading.start-Math.min(s.loading.first-s.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,s.loaded),s.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(t){return t.type!==_e||"initSegment"===t.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:t,minAutoLevel:e}=this.hls,i=this.getBwEstimate(),r=this.hls.config.maxStarvationDelay,s=this.findBestLevel(i,e,t,0,r,1,1);if(s>-1)return s;const n=this.hls.firstLevel,a=Math.min(Math.max(n,e),t);return _.warn(`[abr] Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const t=this.forcedAutoLevel,e=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(!(-1===t||e&&i&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return t;const r=e&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==t){const e=this.hls.levels;if(e.length>Math.max(t,r)&&e[t].loadError<=e[r].loadError)return t}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:e,hls:i}=this,{maxAutoLevel:r,config:s,minAutoLevel:n}=i,a=e?e.duration:t?t.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let h=s.abrBandWidthFactor,d=s.abrBandWidthUpFactor;if(l){const t=this.findBestLevel(o,n,r,l,0,h,d);if(t>=0)return t}let u=a?Math.min(a,s.maxStarvationDelay):s.maxStarvationDelay;if(!l){const t=this.bitrateTestDelay;if(t){u=(a?Math.min(a,s.maxLoadingDelay):s.maxLoadingDelay)-t,_.info(`[abr] bitrate test took ${Math.round(1e3*t)}ms, set first fragment max fetchDuration to ${Math.round(1e3*u)} ms`),h=d=1}}const c=this.findBestLevel(o,n,r,l,u,h,d);if(_.info(`[abr] ${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${c}`),c>-1)return c;const f=i.levels[n],g=i.levels[i.loadLevel];return(null==f?void 0:f.bitrate)<(null==g?void 0:g.bitrate)?n:i.loadLevel}getStarvationDelay(){const t=this.hls,e=t.media;if(!e)return 1/0;const i=e&&0!==e.playbackRate?Math.abs(e.playbackRate):1,r=t.mainForwardBufferInfo;return(r?r.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(t,e,i,r,s,n,a){var o;const l=r+s,h=this.lastLoadedFragLevel,d=-1===h?this.hls.firstLevel:h,{fragCurrent:u,partCurrent:c}=this,{levels:f,allAudioTracks:g,loadLevel:m,config:p}=this.hls;if(1===f.length)return 0;const v=f[d],y=!(null==v||null==(o=v.details)||!o.live),E=-1===m||-1===h;let T,A="SDR",L=(null==v?void 0:v.frameRate)||0;const{audioPreference:R,videoPreference:b}=p,k=this.audioTracksByGroup||(this.audioTracksByGroup=function(t){return t.reduce(((t,e)=>{let i=t.groups[e.groupId];i||(i=t.groups[e.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(e);const r=e.channels||"2";return i.channels[r]=(i.channels[r]||0)+1,i.hasDefault=i.hasDefault||e.default,i.hasAutoSelect=i.hasAutoSelect||e.autoselect,i.hasDefault&&(t.hasDefaultAudio=!0),i.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t}),{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}(g));if(E){if(-1!==this.firstSelection)return this.firstSelection;const r=this.codecTiers||(this.codecTiers=function(t,e,i,r){return t.slice(i,r+1).reduce(((t,i)=>{if(!i.codecSet)return t;const r=i.audioGroups;let s=t[i.codecSet];s||(t[i.codecSet]=s={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!r,fragmentError:0}),s.minBitrate=Math.min(s.minBitrate,i.bitrate);const n=Math.min(i.height,i.width);return s.minHeight=Math.min(s.minHeight,n),s.minFramerate=Math.min(s.minFramerate,i.frameRate),s.maxScore=Math.max(s.maxScore,i.score),s.fragmentError+=i.fragmentError,s.videoRanges[i.videoRange]=(s.videoRanges[i.videoRange]||0)+1,r&&r.forEach((t=>{if(!t)return;const i=e.groups[t];i&&(s.hasDefaultAudio=s.hasDefaultAudio||e.hasDefaultAudio?i.hasDefault:i.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(i.channels).forEach((t=>{s.channels[t]=(s.channels[t]||0)+i.channels[t]})))})),t}),{})}(f,k,e,i)),s=function(t,e,i,r,s){const n=Object.keys(t),a=null==r?void 0:r.channels,o=null==r?void 0:r.audioCodec,l=a&&2===parseInt(a);let h=!0,d=!1,u=1/0,c=1/0,f=1/0,g=0,m=[];const{preferHDR:p,allowedVideoRanges:v}=Ni(e,s);for(let e=n.length;e--;){const i=t[n[e]];h=i.channels[2]>0,u=Math.min(u,i.minHeight),c=Math.min(c,i.minFramerate),f=Math.min(f,i.minBitrate);const r=v.filter((t=>i.videoRanges[t]>0));r.length>0&&(d=!0,m=r)}u=S(u)?u:0,c=S(c)?c:0;const y=Math.max(1080,u),E=Math.max(30,c);return f=S(f)?f:i,i=Math.max(f,i),d||(e=void 0,m=[]),{codecSet:n.reduce(((e,r)=>{const s=t[r];if(r===e)return e;if(s.minBitrate>i)return Ui(r,`min bitrate of ${s.minBitrate} > current estimate of ${i}`),e;if(!s.hasDefaultAudio)return Ui(r,"no renditions with default or auto-select sound found"),e;if(o&&r.indexOf(o.substring(0,4))%5!=0)return Ui(r,`audio codec preference "${o}" not found`),e;if(a&&!l){if(!s.channels[a])return Ui(r,`no renditions with ${a} channel sound found (channels options: ${Object.keys(s.channels)})`),e}else if((!o||l)&&h&&0===s.channels[2])return Ui(r,"no renditions with stereo sound found"),e;return s.minHeight>y?(Ui(r,`min resolution of ${s.minHeight} > maximum of ${y}`),e):s.minFramerate>E?(Ui(r,`min framerate of ${s.minFramerate} > maximum of ${E}`),e):m.some((t=>s.videoRanges[t]>0))?s.maxScore<g?(Ui(r,`max score of ${s.maxScore} < selected max of ${g}`),e):e&&(he(r)>=he(e)||s.fragmentError>t[e].fragmentError)?e:(g=s.maxScore,r):(Ui(r,`no variants with VIDEO-RANGE of ${JSON.stringify(m)} found`),e)}),void 0),videoRanges:m,preferHDR:p,minFramerate:c,minBitrate:f}}(r,A,t,R,b),{codecSet:n,videoRanges:a,minFramerate:o,minBitrate:l,preferHDR:h}=s;T=n,A=h?a[a.length-1]:a[0],L=o,t=Math.max(t,l),_.log(`[abr] picked start tier ${JSON.stringify(s)}`)}else T=null==v?void 0:v.codecSet,A=null==v?void 0:v.videoRange;const D=c?c.duration:u?u.duration:0,I=this.bwEstimator.getEstimateTTFB()/1e3,w=[];for(let o=i;o>=e;o--){var C;const e=f[o],u=o>d;if(!e)continue;if(p.useMediaCapabilities&&!e.supportedResult&&!e.supportedPromise){const i=navigator.mediaCapabilities;"function"==typeof(null==i?void 0:i.decodingInfo)&&Oi(e,k,A,L,t,R)?(e.supportedPromise=Fi(e,k,i),e.supportedPromise.then((t=>{if(!this.hls)return;e.supportedResult=t;const i=this.hls.levels,r=i.indexOf(e);t.error?_.warn(`[abr] MediaCapabilities decodingInfo error: "${t.error}" for level ${r} ${JSON.stringify(t)}`):t.supported||(_.warn(`[abr] Unsupported MediaCapabilities decodingInfo result for level ${r} ${JSON.stringify(t)}`),r>-1&&i.length>1&&(_.log(`[abr] Removing unsupported level ${r}`),this.hls.removeLevel(r)))}))):e.supportedResult=xi}if(T&&e.codecSet!==T||A&&e.videoRange!==A||u&&L>e.frameRate||!u&&L>0&&L<e.frameRate||e.supportedResult&&(null==(C=e.supportedResult.decodingInfoResults)||!C[0].smooth)){w.push(o);continue}const g=e.details,b=(c?null==g?void 0:g.partTarget:null==g?void 0:g.averagetargetduration)||D;let P;P=u?a*t:n*t;const x=D&&r>=2*D&&0===s?f[o].averageBitrate:f[o].maxBitrate,M=this.getTimeToLoadFrag(I,P,x*b,void 0===g);if(P>=x&&(o===h||0===e.loadError&&0===e.fragmentError)&&(M<=I||!S(M)||y&&!this.bitrateTestDelay||M<l)){const t=this.forcedAutoLevel;return o===m||-1!==t&&t===m||(w.length&&_.trace(`[abr] Skipped level(s) ${w.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${f[w[0]].codecs}" ${f[w[0]].videoRange}; not compatible with "${v.codecs}" ${A}`),_.info(`[abr] switch candidate:${d}->${o} adjustedbw(${Math.round(P)})-bitrate=${Math.round(P-x)} ttfb:${I.toFixed(1)} avgDuration:${b.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${M.toFixed(1)} firstSelection:${E} codecSet:${T} videoRange:${A} hls.loadLevel:${m}`)),E&&(this.firstSelection=o),o}}return-1}set nextAutoLevel(t){const{maxAutoLevel:e,minAutoLevel:i}=this.hls,r=Math.min(Math.max(t,i),e);this._nextAutoLevel!==r&&(this.nextAutoLevelKey="",this._nextAutoLevel=r)}},bufferController:class{constructor(t){this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.appendSource=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this.log=void 0,this.warn=void 0,this.error=void 0,this._onEndStreaming=t=>{this.hls&&this.hls.pauseBuffering()},this._onStartStreaming=t=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=()=>{const{media:t,mediaSource:e}=this;this.log("Media source opened"),t&&(t.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(R.MEDIA_ATTACHED,{media:t,mediaSource:e})),e&&e.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:t,_objectUrl:e}=this;t!==e&&_.error(`Media element src was set while attaching MediaSource (${e} > ${t})`)},this.hls=t;const e="[buffer-controller]";var i;this.appendSource=(i=re(t.config.preferManagedMediaSource),"undefined"!=typeof self&&i===self.ManagedMediaSource),this.log=_.log.bind(_,e),this.warn=_.warn.bind(_,e),this.error=_.error.bind(_,e),this._initSourceBuffer(),this.registerListeners()}hasSourceTypes(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.hls=null}registerListeners(){const{hls:t}=this;t.on(R.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(R.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(R.MANIFEST_LOADING,this.onManifestLoading,this),t.on(R.MANIFEST_PARSED,this.onManifestParsed,this),t.on(R.BUFFER_RESET,this.onBufferReset,this),t.on(R.BUFFER_APPENDING,this.onBufferAppending,this),t.on(R.BUFFER_CODECS,this.onBufferCodecs,this),t.on(R.BUFFER_EOS,this.onBufferEos,this),t.on(R.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(R.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(R.FRAG_PARSED,this.onFragParsed,this),t.on(R.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:t}=this;t.off(R.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(R.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(R.MANIFEST_LOADING,this.onManifestLoading,this),t.off(R.MANIFEST_PARSED,this.onManifestParsed,this),t.off(R.BUFFER_RESET,this.onBufferReset,this),t.off(R.BUFFER_APPENDING,this.onBufferAppending,this),t.off(R.BUFFER_CODECS,this.onBufferCodecs,this),t.off(R.BUFFER_EOS,this.onBufferEos,this),t.off(R.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(R.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(R.FRAG_PARSED,this.onFragParsed,this),t.off(R.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new Gs(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.appendErrors={audio:0,video:0,audiovideo:0},this.lastMpegAudioChunk=null}onManifestLoading(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null}onManifestParsed(t,e){let i=2;(e.audio&&!e.video||!e.altAudio)&&(i=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=i,this.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(t,e){const i=this.media=e.media,r=re(this.appendSource);if(i&&r){var s;const t=this.mediaSource=new r;this.log(`created media source: ${null==(s=t.constructor)?void 0:s.name}`),t.addEventListener("sourceopen",this._onMediaSourceOpen),t.addEventListener("sourceended",this._onMediaSourceEnded),t.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(t.addEventListener("startstreaming",this._onStartStreaming),t.addEventListener("endstreaming",this._onEndStreaming));const e=this._objectUrl=self.URL.createObjectURL(t);if(this.appendSource)try{i.removeAttribute("src");const r=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||r&&t instanceof r,Hs(i),function(t,e){const i=self.document.createElement("source");i.type="video/mp4",i.src=e,t.appendChild(i)}(i,e),i.load()}catch(t){i.src=e}else i.src=e;i.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:t,mediaSource:e,_objectUrl:i}=this;if(e){if(this.log("media source detaching"),"open"===e.readyState)try{e.endOfStream()}catch(t){this.warn(`onMediaDetaching: ${t.message} while calling endOfStream`)}this.onBufferReset(),e.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("sourceended",this._onMediaSourceEnded),e.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.removeEventListener("startstreaming",this._onStartStreaming),e.removeEventListener("endstreaming",this._onEndStreaming)),t&&(t.removeEventListener("emptied",this._onMediaEmptied),i&&self.URL.revokeObjectURL(i),this.mediaSrc===i?(t.removeAttribute("src"),this.appendSource&&Hs(t),t.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(R.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach((t=>{this.resetBuffer(t)})),this._initSourceBuffer()}resetBuffer(t){const e=this.sourceBuffer[t];try{var i;if(e)this.removeBufferListeners(t),this.sourceBuffer[t]=void 0,null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(e)}catch(e){this.warn(`onBufferReset ${t}`,e)}}onBufferCodecs(t,e){const i=this.getSourceBufferTypes().length,r=Object.keys(e);if(r.forEach((t=>{if(i){const i=this.tracks[t];if(i&&"function"==typeof i.buffer.changeType){var r;const{id:s,codec:n,levelCodec:a,container:o,metadata:l}=e[t],h=fe(i.codec,i.levelCodec),d=null==h?void 0:h.replace(Ks,"$1");let u=fe(n,a);const c=null==(r=u)?void 0:r.replace(Ks,"$1");if(u&&d!==c){"audio"===t.slice(0,5)&&(u=ce(u,this.appendSource));const e=`${o};codecs=${u}`;this.appendChangeType(t,e),this.log(`switching codec ${h} to ${u}`),this.tracks[t]={buffer:i.buffer,codec:n,container:o,levelCodec:a,metadata:l,id:s}}}}else this.pendingTracks[t]=e[t]})),i)return;const s=Math.max(this.bufferCodecEventsExpected-1,0);this.bufferCodecEventsExpected!==s&&(this.log(`${s} bufferCodec event(s) expected ${r.join(",")}`),this.bufferCodecEventsExpected=s),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks()}appendChangeType(t,e){const{operationQueue:i}=this,r={execute:()=>{const r=this.sourceBuffer[t];r&&(this.log(`changing ${t} sourceBuffer type to ${e}`),r.changeType(e)),i.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn(`Failed to change ${t} SourceBuffer type`,e)}};i.append(r,t,!!this.pendingTracks[t])}onBufferAppending(t,e){const{hls:i,operationQueue:r,tracks:s}=this,{data:n,type:a,frag:o,part:l,chunkMeta:h}=e,d=h.buffering[a],u=self.performance.now();d.start=u;const c=o.stats.buffering,f=l?l.stats.buffering:null;0===c.start&&(c.start=u),f&&0===f.start&&(f.start=u);const g=s.audio;let m=!1;"audio"===a&&"audio/mpeg"===(null==g?void 0:g.container)&&(m=!this.lastMpegAudioChunk||1===h.id||this.lastMpegAudioChunk.sn!==h.sn,this.lastMpegAudioChunk=h);const p=o.start,v={execute:()=>{if(d.executeStart=self.performance.now(),m){const t=this.sourceBuffer[a];if(t){const e=p-t.timestampOffset;Math.abs(e)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${p} (delta: ${e}) sn: ${o.sn})`),t.timestampOffset=p)}}this.appendExecutor(n,a)},onStart:()=>{},onComplete:()=>{const t=self.performance.now();d.executeEnd=d.end=t,0===c.first&&(c.first=t),f&&0===f.first&&(f.first=t);const{sourceBuffer:e}=this,i={};for(const t in e)i[t]=Ji.getBuffered(e[t]);this.appendErrors[a]=0,"audio"===a||"video"===a?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(R.BUFFER_APPENDED,{type:a,frag:o,part:l,chunkMeta:h,parent:o.type,timeRanges:i})},onError:t=>{const e={type:b.MEDIA_ERROR,parent:o.type,details:k.BUFFER_APPEND_ERROR,sourceBufferName:a,frag:o,part:l,chunkMeta:h,error:t,err:t,fatal:!1};if(t.code===DOMException.QUOTA_EXCEEDED_ERR)e.details=k.BUFFER_FULL_ERROR;else{const t=++this.appendErrors[a];e.details=k.BUFFER_APPEND_ERROR,this.warn(`Failed ${t}/${i.config.appendErrorMaxRetry} times to append segment in "${a}" sourceBuffer`),t>=i.config.appendErrorMaxRetry&&(e.fatal=!0)}i.trigger(R.ERROR,e)}};r.append(v,a,!!this.pendingTracks[a])}onBufferFlushing(t,e){const{operationQueue:i}=this,r=t=>({execute:this.removeExecutor.bind(this,t,e.startOffset,e.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(R.BUFFER_FLUSHED,{type:t})},onError:e=>{this.warn(`Failed to remove from ${t} SourceBuffer`,e)}});e.type?i.append(r(e.type),e.type):this.getSourceBufferTypes().forEach((t=>{i.append(r(t),t)}))}onFragParsed(t,e){const{frag:i,part:r}=e,s=[],n=r?r.elementaryStreams:i.elementaryStreams;n[G]?s.push("audiovideo"):(n[U]&&s.push("audio"),n[B]&&s.push("video"));0===s.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers((()=>{const t=self.performance.now();i.stats.buffering.end=t,r&&(r.stats.buffering.end=t);const e=r?r.stats:i.stats;this.hls.trigger(R.FRAG_BUFFERED,{frag:i,part:r,stats:e,id:i.type})}),s)}onFragChanged(t,e){this.trimBuffers()}onBufferEos(t,e){this.getSourceBufferTypes().reduce(((t,i)=>{const r=this.sourceBuffer[i];return!r||e.type&&e.type!==i||(r.ending=!0,r.ended||(r.ended=!0,this.log(`${i} sourceBuffer now EOS`))),t&&!(r&&!r.ended)}),!0)&&(this.log("Queueing mediaSource.endOfStream()"),this.blockBuffers((()=>{this.getSourceBufferTypes().forEach((t=>{const e=this.sourceBuffer[t];e&&(e.ending=!1)}));const{mediaSource:t}=this;t&&"open"===t.readyState?(this.log("Calling mediaSource.endOfStream()"),t.endOfStream()):t&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${t.readyState}`)})))}onLevelUpdated(t,{details:e}){e.fragments.length&&(this.details=e,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}trimBuffers(){const{hls:t,details:e,media:i}=this;if(!i||null===e)return;if(!this.getSourceBufferTypes().length)return;const r=t.config,s=i.currentTime,n=e.levelTargetDuration,a=e.live&&null!==r.liveBackBufferLength?r.liveBackBufferLength:r.backBufferLength;if(S(a)&&a>0){const t=Math.max(a,n),e=Math.floor(s/n)*n-t;this.flushBackBuffer(s,n,e)}if(S(r.frontBufferFlushThreshold)&&r.frontBufferFlushThreshold>0){const t=Math.max(r.maxBufferLength,r.frontBufferFlushThreshold),e=Math.max(t,n),i=Math.floor(s/n)*n+e;this.flushFrontBuffer(s,n,i)}}flushBackBuffer(t,e,i){const{details:r,sourceBuffer:s}=this;this.getSourceBufferTypes().forEach((n=>{const a=s[n];if(a){const s=Ji.getBuffered(a);if(s.length>0&&i>s.start(0)){if(this.hls.trigger(R.BACK_BUFFER_REACHED,{bufferEnd:i}),null!=r&&r.live)this.hls.trigger(R.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(a.ended&&s.end(s.length-1)-t<2*e)return void this.log(`Cannot flush ${n} back buffer while SourceBuffer is in ended state`);this.hls.trigger(R.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:n})}}}))}flushFrontBuffer(t,e,i){const{sourceBuffer:r}=this;this.getSourceBufferTypes().forEach((s=>{const n=r[s];if(n){const r=Ji.getBuffered(n),a=r.length;if(a<2)return;const o=r.start(a-1),l=r.end(a-1);if(i>o||t>=o&&t<=l)return;if(n.ended&&t-l<2*e)return void this.log(`Cannot flush ${s} front buffer while SourceBuffer is in ended state`);this.hls.trigger(R.BUFFER_FLUSHING,{startOffset:o,endOffset:1/0,type:s})}}))}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||"open"!==this.mediaSource.readyState)return;const{details:t,hls:e,media:i,mediaSource:r}=this,s=t.fragments[0].start+t.totalduration,n=i.duration,a=S(r.duration)?r.duration:0;t.live&&e.config.liveDurationInfinity?(r.duration=1/0,this.updateSeekableRange(t)):(s>a&&s>n||!S(n))&&(this.log(`Updating Media Source duration to ${s.toFixed(3)}`),r.duration=s)}updateSeekableRange(t){const e=this.mediaSource,i=t.fragments;if(i.length&&t.live&&null!=e&&e.setLiveSeekableRange){const r=Math.max(0,i[0].start),s=Math.max(r,r+t.totalduration);this.log(`Media Source duration is set to ${e.duration}. Setting seekable range to ${r}-${s}.`),e.setLiveSeekableRange(r,s)}}checkPendingTracks(){const{bufferCodecEventsExpected:t,operationQueue:e,pendingTracks:i}=this,r=Object.keys(i).length;if(r&&(!t||2===r||"audiovideo"in i)){this.createSourceBuffers(i),this.pendingTracks={};const t=this.getSourceBufferTypes();if(t.length)this.hls.trigger(R.BUFFER_CREATED,{tracks:this.tracks}),t.forEach((t=>{e.executeNext(t)}));else{const t=new Error("could not create source buffer for media codec(s)");this.hls.trigger(R.ERROR,{type:b.MEDIA_ERROR,details:k.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}}createSourceBuffers(t){const{sourceBuffer:e,mediaSource:i}=this;if(!i)throw Error("createSourceBuffers called when mediaSource was null");for(const s in t)if(!e[s]){var r;const n=t[s];if(!n)throw Error(`source buffer exists for track ${s}, however track does not`);let a=-1===(null==(r=n.levelCodec)?void 0:r.indexOf(","))?n.levelCodec:n.codec;a&&"audio"===s.slice(0,5)&&(a=ce(a,this.appendSource));const o=`${n.container};codecs=${a}`;this.log(`creating sourceBuffer(${o})`);try{const t=e[s]=i.addSourceBuffer(o),r=s;this.addBufferListener(r,"updatestart",this._onSBUpdateStart),this.addBufferListener(r,"updateend",this._onSBUpdateEnd),this.addBufferListener(r,"error",this._onSBUpdateError),this.appendSource&&this.addBufferListener(r,"bufferedchange",((t,e)=>{const i=e.removedRanges;null!=i&&i.length&&this.hls.trigger(R.BUFFER_FLUSHED,{type:s})})),this.tracks[s]={buffer:t,codec:a,container:n.container,levelCodec:n.levelCodec,metadata:n.metadata,id:n.id}}catch(t){this.error(`error while trying to add sourceBuffer: ${t.message}`),this.hls.trigger(R.ERROR,{type:b.MEDIA_ERROR,details:k.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,sourceBufferName:s,mimeType:o})}}}get mediaSrc(){var t,e;const i=(null==(t=this.media)||null==(e=t.querySelector)?void 0:e.call(t,"source"))||this.media;return null==i?void 0:i.src}_onSBUpdateStart(t){const{operationQueue:e}=this;e.current(t).onStart()}_onSBUpdateEnd(t){var e;if("closed"===(null==(e=this.mediaSource)?void 0:e.readyState))return void this.resetBuffer(t);const{operationQueue:i}=this;i.current(t).onComplete(),i.shiftAndExecuteNext(t)}_onSBUpdateError(t,e){var i;const r=new Error(`${t} SourceBuffer error. MediaSource readyState: ${null==(i=this.mediaSource)?void 0:i.readyState}`);this.error(`${r}`,e),this.hls.trigger(R.ERROR,{type:b.MEDIA_ERROR,details:k.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:r,fatal:!1});const s=this.operationQueue.current(t);s&&s.onError(r)}removeExecutor(t,e,i){const{media:r,mediaSource:s,operationQueue:n,sourceBuffer:a}=this,o=a[t];if(!r||!s||!o)return this.warn(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`),void n.shiftAndExecuteNext(t);const l=S(r.duration)?r.duration:1/0,h=S(s.duration)?s.duration:1/0,d=Math.max(0,e),u=Math.min(i,l,h);u>d&&(!o.ending||o.ended)?(o.ended=!1,this.log(`Removing [${d},${u}] from the ${t} SourceBuffer`),o.remove(d,u)):n.shiftAndExecuteNext(t)}appendExecutor(t,e){const i=this.sourceBuffer[e];if(i)i.ended=!1,i.appendBuffer(t);else if(!this.pendingTracks[e])throw new Error(`Attempting to append to the ${e} SourceBuffer, but it does not exist`)}blockBuffers(t,e=this.getSourceBufferTypes()){if(!e.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),void Promise.resolve().then(t);const{operationQueue:i}=this,r=e.map((t=>i.appendBlocker(t)));Promise.all(r).then((()=>{t(),e.forEach((t=>{const e=this.sourceBuffer[t];null!=e&&e.updating||i.shiftAndExecuteNext(t)}))}))}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(t,e,i){const r=this.sourceBuffer[t];if(!r)return;const s=i.bind(this,t);this.listeners[t].push({event:e,listener:s}),r.addEventListener(e,s)}removeBufferListeners(t){const e=this.sourceBuffer[t];e&&this.listeners[t].forEach((t=>{e.removeEventListener(t.event,t.listener)}))}},capLevelController:Un,errorController:class{constructor(t){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=t,this.log=_.log.bind(_,"[info]:"),this.warn=_.warn.bind(_,"[warning]:"),this.error=_.error.bind(_,"[error]:"),this.registerListeners()}registerListeners(){const t=this.hls;t.on(R.ERROR,this.onError,this),t.on(R.MANIFEST_LOADING,this.onManifestLoading,this),t.on(R.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(R.ERROR,this.onError,this),t.off(R.ERROR,this.onErrorOut,this),t.off(R.MANIFEST_LOADING,this.onManifestLoading,this),t.off(R.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(t){}stopLoad(){this.playlistError=0}getVariantLevelIndex(t){return(null==t?void 0:t.type)===_e?t.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(t,e){var i,r;if(e.fatal)return;const s=this.hls,n=e.context;switch(e.details){case k.FRAG_LOAD_ERROR:case k.FRAG_LOAD_TIMEOUT:case k.KEY_LOAD_ERROR:case k.KEY_LOAD_TIMEOUT:return void(e.errorAction=this.getFragRetryOrSwitchAction(e));case k.FRAG_PARSING_ERROR:if(null!=(i=e.frag)&&i.gap)return void(e.errorAction={action:Li,flags:Di});case k.FRAG_GAP:case k.FRAG_DECRYPT_ERROR:return e.errorAction=this.getFragRetryOrSwitchAction(e),void(e.errorAction.action=Ri);case k.LEVEL_EMPTY_ERROR:case k.LEVEL_PARSING_ERROR:{var a,o;const t=e.parent===_e?e.level:s.loadLevel;e.details===k.LEVEL_EMPTY_ERROR&&null!=(a=e.context)&&null!=(o=a.levelDetails)&&o.live?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,t):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t))}return;case k.LEVEL_LOAD_ERROR:case k.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==n?void 0:n.level)&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,n.level)));case k.AUDIO_TRACK_LOAD_ERROR:case k.AUDIO_TRACK_LOAD_TIMEOUT:case k.SUBTITLE_LOAD_ERROR:case k.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){const t=s.levels[s.loadLevel];if(t&&(n.type===we&&t.hasAudioGroup(n.groupId)||n.type===Ce&&t.hasSubtitleGroup(n.groupId)))return e.errorAction=this.getPlaylistRetryOrSwitchAction(e,s.loadLevel),e.errorAction.action=Ri,void(e.errorAction.flags=Ii)}return;case k.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const t=s.levels[s.loadLevel],i=null==t?void 0:t.attrs["HDCP-LEVEL"];i?e.errorAction={action:Ri,flags:wi,hdcpLevel:i}:this.keySystemError(e)}return;case k.BUFFER_ADD_CODEC_ERROR:case k.REMUX_ALLOC_ERROR:case k.BUFFER_APPEND_ERROR:return void(e.errorAction=this.getLevelSwitchAction(e,null!=(r=e.level)?r:s.loadLevel));case k.INTERNAL_EXCEPTION:case k.BUFFER_APPENDING_ERROR:case k.BUFFER_FULL_ERROR:case k.LEVEL_SWITCH_ERROR:case k.BUFFER_STALLED_ERROR:case k.BUFFER_SEEK_OVER_HOLE:case k.BUFFER_NUDGE_ON_STALL:return void(e.errorAction={action:Li,flags:Di})}e.type===b.KEY_SYSTEM_ERROR&&this.keySystemError(e)}keySystemError(t){const e=this.getVariantLevelIndex(t.frag);t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e)}getPlaylistRetryOrSwitchAction(t,e){const i=mi(this.hls.config.playlistLoadPolicy,t),r=this.playlistError++;if(yi(i,r,gi(t),t.response))return{action:ki,flags:Di,retryConfig:i,retryCount:r};const s=this.getLevelSwitchAction(t,e);return i&&(s.retryConfig=i,s.retryCount=r),s}getFragRetryOrSwitchAction(t){const e=this.hls,i=this.getVariantLevelIndex(t.frag),r=e.levels[i],{fragLoadPolicy:s,keyLoadPolicy:n}=e.config,a=mi(t.details.startsWith("key")?n:s,t),o=e.levels.reduce(((t,e)=>t+e.fragmentError),0);if(r){t.details!==k.FRAG_GAP&&r.fragmentError++;if(yi(a,o,gi(t),t.response))return{action:ki,flags:Di,retryConfig:a,retryCount:o}}const l=this.getLevelSwitchAction(t,i);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(t,e){const i=this.hls;null==e&&(e=i.loadLevel);const r=this.hls.levels[e];if(r){var s,n;const e=t.details;r.loadError++,e===k.BUFFER_APPEND_ERROR&&r.fragmentError++;let l=-1;const{levels:h,loadLevel:d,minAutoLevel:u,maxAutoLevel:c}=i;i.autoLevelEnabled||(i.loadLevel=-1);const f=null==(s=t.frag)?void 0:s.type,g=(f===Pe&&e===k.FRAG_PARSING_ERROR||"audio"===t.sourceBufferName&&(e===k.BUFFER_ADD_CODEC_ERROR||e===k.BUFFER_APPEND_ERROR))&&h.some((({audioCodec:t})=>r.audioCodec!==t)),m="video"===t.sourceBufferName&&(e===k.BUFFER_ADD_CODEC_ERROR||e===k.BUFFER_APPEND_ERROR)&&h.some((({codecSet:t,audioCodec:e})=>r.codecSet!==t&&r.audioCodec===e)),{type:p,groupId:v}=null!=(n=t.context)?n:{};for(let i=h.length;i--;){const s=(i+d)%h.length;if(s!==d&&s>=u&&s<=c&&0===h[s].loadError){var a,o;const i=h[s];if(e===k.FRAG_GAP&&f===_e&&t.frag){const e=h[s].details;if(e){const i=Ti(t.frag,e.fragments,t.frag.start);if(null!=i&&i.gap)continue}}else{if(p===we&&i.hasAudioGroup(v)||p===Ce&&i.hasSubtitleGroup(v))continue;if(f===Pe&&null!=(a=r.audioGroups)&&a.some((t=>i.hasAudioGroup(t)))||f===xe&&null!=(o=r.subtitleGroups)&&o.some((t=>i.hasSubtitleGroup(t)))||g&&r.audioCodec===i.audioCodec||!g&&r.audioCodec!==i.audioCodec||m&&r.codecSet===i.codecSet)continue}l=s;break}}if(l>-1&&i.loadLevel!==l)return t.levelRetry=!0,this.playlistError=0,{action:Ri,flags:Di,nextAutoLevel:l}}return{action:Ri,flags:Ii}}onErrorOut(t,e){var i;switch(null==(i=e.errorAction)?void 0:i.action){case Li:break;case Ri:this.sendAlternateToPenaltyBox(e),e.errorAction.resolved||e.details===k.FRAG_GAP?/MediaSource readyState: ended/.test(e.error.message)&&(this.warn(`MediaSource ended after "${e.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):e.fatal=!0}e.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(t){const e=this.hls,i=t.errorAction;if(!i)return;const{flags:r,hdcpLevel:s,nextAutoLevel:n}=i;switch(r){case Di:this.switchLevel(t,n);break;case wi:s&&(e.maxHdcpLevel=Qe[Qe.indexOf(s)-1],i.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`)}i.resolved||this.switchLevel(t,n)}switchLevel(t,e){void 0!==e&&t.errorAction&&(this.warn(`switching to level ${e} after ${t.details}`),this.hls.nextAutoLevel=e,t.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)}},fpsController:class{constructor(t){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()}setStreamController(t){this.streamController=t}registerListeners(){this.hls.on(R.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(R.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,e){const i=this.hls.config;if(i.capLevelOnFPSDrop){const t=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=t,t&&"function"==typeof t.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}checkFPS(t,e,i){const r=performance.now();if(e){if(this.lastTime){const t=r-this.lastTime,s=i-this.lastDroppedFrames,n=e-this.lastDecodedFrames,a=1e3*s/t,o=this.hls;if(o.trigger(R.FPS_DROP,{currentDropped:s,currentDecoded:n,totalDroppedFrames:i}),a>0&&s>o.config.fpsDroppedMonitoringThreshold*n){let t=o.currentLevel;_.warn("drop FPS ratio greater than max allowed value for currentLevel: "+t),t>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=t)&&(t-=1,o.trigger(R.FPS_DROP_LEVEL_CAPPING,{level:t,droppedLevel:o.currentLevel}),o.autoLevelCapping=t,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=i,this.lastDecodedFrames=e}}checkFPSInterval(){const t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){const e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)}},stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:st,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!0,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},{cueHandler:Oa,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:class extends Dr{constructor(t,e,i){super(t,e,i,"[subtitle-stream-controller]",xe),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}_registerListeners(){const{hls:t}=this;t.on(R.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(R.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(R.MANIFEST_LOADING,this.onManifestLoading,this),t.on(R.LEVEL_LOADED,this.onLevelLoaded,this),t.on(R.ERROR,this.onError,this),t.on(R.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(R.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(R.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(R.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(R.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(R.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(R.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(R.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(R.MANIFEST_LOADING,this.onManifestLoading,this),t.off(R.LEVEL_LOADED,this.onLevelLoaded,this),t.off(R.ERROR,this.onError,this),t.off(R.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(R.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(R.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(R.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(R.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(R.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(t){this.stopLoad(),this.state=pr,this.setInterval(500),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()}onMediaDetaching(){this.tracksBuffered=[],super.onMediaDetaching()}onLevelLoaded(t,e){this.mainDetails=e.details}onSubtitleFragProcessed(t,e){const{frag:i,success:r}=e;if(this.fragPrevious=i,this.state=pr,!r)return;const s=this.tracksBuffered[this.currentTrackId];if(!s)return;let n;const a=i.start;for(let t=0;t<s.length;t++)if(a>=s[t].start&&a<=s[t].end){n=s[t];break}const o=i.start+i.duration;n?n.end=o:(n={start:a,end:o},s.push(n)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null)}onBufferFlushing(t,e){const{startOffset:i,endOffset:r}=e;if(0===i&&r!==Number.POSITIVE_INFINITY){const t=r-1;if(t<=0)return;e.endOffsetSubtitles=Math.max(0,t),this.tracksBuffered.forEach((e=>{for(let i=0;i<e.length;)if(e[i].end<=t)e.shift();else{if(!(e[i].start<t))break;e[i].start=t,i++}})),this.fragmentTracker.removeFragmentsInRange(i,t,xe)}}onFragBuffered(t,e){var i;this.loadedmetadata||e.frag.type!==_e||null!=(i=this.media)&&i.buffered.length&&(this.loadedmetadata=!0)}onError(t,e){const i=e.frag;(null==i?void 0:i.type)===xe&&(e.details===k.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==mr&&(this.state=pr))}onSubtitleTracksUpdated(t,{subtitleTracks:e}){this.levels&&Fs(this.levels,e)?this.levels=e.map((t=>new si(t))):(this.tracksBuffered=[],this.levels=e.map((t=>{const e=new si(t);return this.tracksBuffered[e.id]=[],e})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,xe),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(t,e){var i;if(this.currentTrackId=e.id,null==(i=this.levels)||!i.length||-1===this.currentTrackId)return void this.clearInterval();const r=this.levels[this.currentTrackId];null!=r&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.setInterval(500)}onSubtitleTrackLoaded(t,e){var i;const{currentTrackId:r,levels:s}=this,{details:n,id:a}=e;if(!s)return void this.warn(`Subtitle tracks were reset while loading level ${a}`);const o=s[a];if(a>=s.length||!o)return;this.log(`Subtitle track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(n.live||null!=(i=o.details)&&i.live){const t=this.mainDetails;if(n.deltaUpdateFailed||!t)return;const e=t.fragments[0];var h;if(o.details)l=this.alignPlaylists(n,o.details,null==(h=this.levelLastLoaded)?void 0:h.details),0===l&&e&&(l=e.start,di(n,l));else n.hasProgramDateTime&&t.hasProgramDateTime?(sr(n,t),l=n.fragments[0].start):e&&(l=e.start,di(n,l))}if(o.details=n,this.levelLastLoaded=o,a===r&&(this.startFragRequested||!this.mainDetails&&n.live||this.setStartPosition(this.mainDetails||n,l),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===pr)){Ti(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)}}_handleFragmentLoadComplete(t){const{frag:e,payload:i}=t,r=e.decryptdata,s=this.hls;if(!this.fragContextChanged(e)&&i&&i.byteLength>0&&null!=r&&r.key&&r.iv&&"AES-128"===r.method){const t=performance.now();this.decrypter.decrypt(new Uint8Array(i),r.key.buffer,r.iv.buffer).catch((t=>{throw s.trigger(R.ERROR,{type:b.MEDIA_ERROR,details:k.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e}),t})).then((i=>{const r=performance.now();s.trigger(R.FRAG_DECRYPTED,{frag:e,payload:i,stats:{tstart:t,tdecrypt:r}})})).catch((t=>{this.warn(`${t.name}: ${t.message}`),this.state=pr}))}}doTick(){if(this.media){if(this.state===pr){const{currentTrackId:t,levels:e}=this,i=null==e?void 0:e[t];if(!i||!e.length||!i.details)return;const{config:r}=this,s=this.getLoadPosition(),n=Ji.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],s,r.maxBufferHole),{end:a,len:o}=n,l=this.getFwdBufferInfo(this.media,_e),h=i.details;if(o>this.getMaxBufferLength(null==l?void 0:l.len)+h.levelTargetDuration)return;const d=h.fragments,u=d.length,c=h.edge;let f=null;const g=this.fragPrevious;if(a<c){const t=r.maxFragLookUpTolerance,e=a>c-t?0:t;f=Ti(g,d,Math.max(d[0].start,a),e),!f&&g&&g.start<d[0].start&&(f=d[0])}else f=d[u-1];if(!f)return;if(f=this.mapToInitFragWhenRequired(f),"initSegment"!==f.sn){const t=d[f.sn-h.startSN-1];t&&t.cc===f.cc&&this.fragmentTracker.getState(t)===Vi&&(f=t)}this.fragmentTracker.getState(f)===Vi&&this.loadFragment(f,i,a)}}else this.state=pr}getMaxBufferLength(t){const e=super.getMaxBufferLength();return t?Math.max(e,t):e}loadFragment(t,e,i){this.fragCurrent=t,"initSegment"===t.sn?this._loadInitSegment(t,e):(this.startFragRequested=!0,super.loadFragment(t,e,i))}get mediaBufferTimeRanges(){return new Bs(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class extends Ci{constructor(t){super(t,"[subtitle-track-controller]"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const e=Ke(this.media.textTracks);for(let i=0;i<e.length;i++)if("hidden"===e[i].mode)t=e[i];else if("showing"===e[i].mode){t=e[i];break}const i=this.findTrackForTextTrack(t);this.subtitleTrack!==i&&this.setSubtitleTrack(i)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(t){this._subtitleDisplay=t,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:t}=this;t.on(R.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(R.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(R.MANIFEST_LOADING,this.onManifestLoading,this),t.on(R.MANIFEST_PARSED,this.onManifestParsed,this),t.on(R.LEVEL_LOADING,this.onLevelLoading,this),t.on(R.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(R.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(R.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(R.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(R.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(R.MANIFEST_LOADING,this.onManifestLoading,this),t.off(R.MANIFEST_PARSED,this.onManifestParsed,this),t.off(R.LEVEL_LOADING,this.onLevelLoading,this),t.off(R.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(R.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(R.ERROR,this.onError,this)}onMediaAttached(t,e){this.media=e.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,t)}onMediaDetaching(){if(!this.media)return;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId);Ke(this.media.textTracks).forEach((t=>{Be(t)})),this.subtitleTrack=-1,this.media=null}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.subtitleTracks}onSubtitleTrackLoaded(t,e){const{id:i,groupId:r,details:s}=e,n=this.tracksInGroup[i];if(!n||n.groupId!==r)return void this.warn(`Subtitle track with id:${i} and group:${r} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=e.details,this.log(`Subtitle track ${i} "${n.name}" lang:${n.lang} group:${r} loaded [${s.startSN}-${s.endSN}]`),i===this.trackId&&this.playlistLoaded(i,e,a)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const i=e.subtitleGroups||null,r=this.groupIds;let s=this.currentTrack;if(!i||(null==r?void 0:r.length)!==(null==i?void 0:i.length)||null!=i&&i.some((t=>-1===(null==r?void 0:r.indexOf(t))))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter((t=>!i||-1!==i.indexOf(t.groupId)));if(t.length)this.selectDefaultTrack&&!t.some((t=>t.default))&&(this.selectDefaultTrack=!1),t.forEach(((t,e)=>{t.id=e}));else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const e=this.hls.config.subtitlePreference;if(!s&&e){this.selectDefaultTrack=!1;const i=Bi(e,t);if(i>-1)s=t[i];else{const t=Bi(e,this.tracks);s=this.tracks[t]}}let r=this.findTrackId(s);-1===r&&s&&(r=this.findTrackId(null));const n={subtitleTracks:t};this.log(`Updating subtitle tracks, ${t.length} track(s) found in "${null==i?void 0:i.join(",")}" group-id`),this.hls.trigger(R.SUBTITLE_TRACKS_UPDATED,n),-1!==r&&-1===this.trackId&&this.setSubtitleTrack(r)}else this.shouldReloadPlaylist(s)&&this.setSubtitleTrack(this.trackId)}findTrackId(t){const e=this.tracksInGroup,i=this.selectDefaultTrack;for(let r=0;r<e.length;r++){const s=e[r];if((!i||s.default)&&(i||t)&&(!t||Gi(s,t)))return r}if(t){for(let i=0;i<e.length;i++){const r=e[i];if(Ns(t.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<e.length;i++){const r=e[i];if(Ns(t.attrs,r.attrs,["LANGUAGE"]))return i}}return-1}findTrackForTextTrack(t){if(t){const e=this.tracksInGroup;for(let i=0;i<e.length;i++){if(Us(e[i],t))return i}}return-1}onError(t,e){!e.fatal&&e.context&&(e.context.type!==Ce||e.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(e.context.groupId)||this.checkRetry(e))}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(t){this.selectDefaultTrack=!1,this.setSubtitleTrack(t)}setSubtitleOption(t){if(this.hls.config.subtitlePreference=t,t){const e=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,e.length){const i=this.currentTrack;if(i&&Gi(t,i))return i;const r=Bi(t,this.tracksInGroup);if(r>-1){const t=this.tracksInGroup[r];return this.setSubtitleTrack(r),t}if(i)return null;{const i=Bi(t,e);if(i>-1)return e[i]}}}return null}loadPlaylist(t){super.loadPlaylist();const e=this.currentTrack;if(this.shouldLoadPlaylist(e)&&e){const i=e.id,r=e.groupId;let s=e.url;if(t)try{s=t.addDirectives(s)}catch(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}this.log(`Loading subtitle playlist for id ${i}`),this.hls.trigger(R.SUBTITLE_TRACK_LOADING,{url:s,id:i,groupId:r,deliveryDirectives:t||null})}}toggleTrackModes(){const{media:t}=this;if(!t)return;const e=Ke(t.textTracks),i=this.currentTrack;let r;if(i&&(r=e.filter((t=>Us(i,t)))[0],r||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(e).forEach((t=>{"disabled"!==t.mode&&t!==r&&(t.mode="disabled")})),r){const t=this.subtitleDisplay?"showing":"hidden";r.mode!==t&&(r.mode=t)}}setSubtitleTrack(t){const e=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=t);if(t<-1||t>=e.length||!S(t))return void this.warn(`Invalid subtitle track id: ${t}`);this.clearTimer(),this.selectDefaultTrack=!1;const i=this.currentTrack,r=e[t]||null;if(this.trackId=t,this.currentTrack=r,this.toggleTrackModes(),!r)return void this.hls.trigger(R.SUBTITLE_TRACK_SWITCH,{id:t});const s=!!r.details&&!r.details.live;if(t===this.trackId&&r===i&&s)return;this.log(`Switching to subtitle-track ${t}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));const{id:n,groupId:a="",name:o,type:l,url:h}=r;this.hls.trigger(R.SUBTITLE_TRACK_SWITCH,{id:n,groupId:a,name:o,type:l,url:h});const d=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(d)}},timelineController:class{constructor(t){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=t,this.config=t.config,this.Cues=t.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},t.on(R.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(R.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(R.MANIFEST_LOADING,this.onManifestLoading,this),t.on(R.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(R.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(R.FRAG_LOADING,this.onFragLoading,this),t.on(R.FRAG_LOADED,this.onFragLoaded,this),t.on(R.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(R.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(R.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(R.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(R.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(R.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(R.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(R.MANIFEST_LOADING,this.onManifestLoading,this),t.off(R.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(R.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(R.FRAG_LOADING,this.onFragLoading,this),t.off(R.FRAG_LOADED,this.onFragLoaded,this),t.off(R.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(R.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(R.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(R.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(R.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){if(this.config.enableCEA708Captions&&(!this.cea608Parser1||!this.cea608Parser2)){const t=new hn(this,"textTrack1"),e=new hn(this,"textTrack2"),i=new hn(this,"textTrack3"),r=new hn(this,"textTrack4");this.cea608Parser1=new an(1,t,e),this.cea608Parser2=new an(3,i,r)}}addCues(t,e,i,r,s){let n=!1;for(let t=s.length;t--;){const r=s[t],d=(a=r[0],o=r[1],l=e,h=i,Math.min(o,h)-Math.max(a,l));if(d>=0&&(r[0]=Math.min(r[0],e),r[1]=Math.max(r[1],i),n=!0,d/(i-e)>.5))return}var a,o,l,h;if(n||s.push([e,i]),this.config.renderTextTracksNatively){const s=this.captionsTracks[t];this.Cues.newCue(s,e,i,r)}else{const s=this.Cues.newCue(null,e,i,r);this.hls.trigger(R.CUES_PARSED,{type:"captions",cues:s,track:t})}}onInitPtsFound(t,{frag:e,id:i,initPTS:r,timescale:s}){const{unparsedVttFrags:n}=this;"main"===i&&(this.initPTS[e.cc]={baseTime:r,timescale:s}),n.length&&(this.unparsedVttFrags=[],n.forEach((t=>{this.onFragLoaded(R.FRAG_LOADED,t)})))}getExistingTrack(t,e){const{media:i}=this;if(i)for(let r=0;r<i.textTracks.length;r++){const s=i.textTracks[r];if(Nn(s,{name:t,lang:e,attrs:{}}))return s}return null}createCaptionsTrack(t){this.config.renderTextTracksNatively?this.createNativeTrack(t):this.createNonNativeTrack(t)}createNativeTrack(t){if(this.captionsTracks[t])return;const{captionsProperties:e,captionsTracks:i,media:r}=this,{label:s,languageCode:n}=e[t],a=this.getExistingTrack(s,n);if(a)i[t]=a,Be(i[t]),Ne(i[t],r);else{const e=this.createTextTrack("captions",s,n);e&&(e[t]=!0,i[t]=e)}}createNonNativeTrack(t){if(this.nonNativeCaptionsTracks[t])return;const e=this.captionsProperties[t];if(!e)return;const i={_id:t,label:e.label,kind:"captions",default:!!e.media&&!!e.media.default,closedCaptions:e.media};this.nonNativeCaptionsTracks[t]=i,this.hls.trigger(R.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}createTextTrack(t,e,i){const r=this.media;if(r)return r.addTextTrack(t,e,i)}onMediaAttaching(t,e){this.media=e.media,this._cleanTracks()}onMediaDetaching(){const{captionsTracks:t}=this;Object.keys(t).forEach((e=>{Be(t[e]),delete t[e]})),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:t}=this;if(!t)return;const e=t.textTracks;if(e)for(let t=0;t<e.length;t++)Be(e[t])}onSubtitleTracksUpdated(t,e){const i=e.subtitleTracks||[],r=i.some((t=>t.textCodec===bn));if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(Fs(this.tracks,i))return void(this.tracks=i);if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const t=this.media,e=t?Ke(t.textTracks):null;if(this.tracks.forEach(((t,i)=>{let r;if(e){let i=null;for(let r=0;r<e.length;r++)if(e[r]&&Nn(e[r],t)){i=e[r],e[r]=null;break}i&&(r=i)}if(r)Be(r);else{const e=Fn(t);r=this.createTextTrack(e,t.name,t.lang),r&&(r.mode="disabled")}r&&this.textTracks.push(r)})),null!=e&&e.length){const t=e.filter((t=>null!==t)).map((t=>t.label));t.length&&_.warn(`Media element contains unused subtitle tracks: ${t.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const t=this.tracks.map((t=>({label:t.name,kind:t.type.toLowerCase(),default:t.default,subtitleTrack:t})));this.hls.trigger(R.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:t})}}}onManifestLoaded(t,e){this.config.enableCEA708Captions&&e.captions&&e.captions.forEach((t=>{const e=/(?:CC|SERVICE)([1-4])/.exec(t.instreamId);if(!e)return;const i=`textTrack${e[1]}`,r=this.captionsProperties[i];r&&(r.label=t.name,t.lang&&(r.languageCode=t.lang),r.media=t)}))}closedCaptionsForLevel(t){const e=this.hls.levels[t.level];return null==e?void 0:e.attrs["CLOSED-CAPTIONS"]}onFragLoading(t,e){if(this.enabled&&e.frag.type===_e){var i,r;const{cea608Parser1:t,cea608Parser2:s,lastSn:n}=this,{cc:a,sn:o}=e.frag,l=null!=(i=null==(r=e.part)?void 0:r.index)?i:-1;t&&s&&(o!==n+1||o===n&&l!==this.lastPartIndex+1||a!==this.lastCc)&&(t.reset(),s.reset()),this.lastCc=a,this.lastSn=o,this.lastPartIndex=l}}onFragLoaded(t,e){const{frag:i,payload:r}=e;if(i.type===xe)if(r.byteLength){const t=i.decryptdata,s="stats"in e;if(null==t||!t.encrypted||s){const t=this.tracks[i.level],s=this.vttCCs;s[i.cc]||(s[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),t&&t.textCodec===bn?this._parseIMSC1(i,r):this._parseVTTs(e)}}else this.hls.trigger(R.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,e){const i=this.hls;wn(e,this.initPTS[t.cc],(e=>{this._appendCues(e,t.level),i.trigger(R.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})}),(e=>{_.log(`Failed to parse IMSC1: ${e}`),i.trigger(R.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:e})}))}_parseVTTs(t){var e;const{frag:i,payload:r}=t,{initPTS:s,unparsedVttFrags:n}=this,a=s.length-1;if(!s[i.cc]&&-1===a)return void n.push(t);const o=this.hls;Rn(null!=(e=i.initSegment)&&e.data?$t(i.initSegment.data,new Uint8Array(r)):r,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,(t=>{this._appendCues(t,i.level),o.trigger(R.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})}),(e=>{const s="Missing initPTS for VTT MPEGTS"===e.message;s?n.push(t):this._fallbackToIMSC1(i,r),_.log(`Failed to parse VTT cue: ${e}`),s&&a>i.cc||o.trigger(R.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:e})}))}_fallbackToIMSC1(t,e){const i=this.tracks[t.level];i.textCodec||wn(e,this.initPTS[t.cc],(()=>{i.textCodec=bn,this._parseIMSC1(t,e)}),(()=>{i.textCodec="wvtt"}))}_appendCues(t,e){const i=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[e];if(!i||"disabled"===i.mode)return;t.forEach((t=>Ue(i,t)))}else{const r=this.tracks[e];if(!r)return;const s=r.default?"default":"subtitles"+e;i.trigger(R.CUES_PARSED,{type:"subtitles",cues:t,track:s})}}onFragDecrypted(t,e){const{frag:i}=e;i.type===xe&&this.onFragLoaded(R.FRAG_LOADED,e)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,e){this.initCea608Parsers();const{cea608Parser1:i,cea608Parser2:r}=this;if(!this.enabled||!i||!r)return;const{frag:s,samples:n}=e;if(s.type!==_e||"NONE"!==this.closedCaptionsForLevel(s))for(let t=0;t<n.length;t++){const e=n[t].bytes;if(e){const s=this.extractCea608Data(e);i.addData(n[t].pts,s[0]),r.addData(n[t].pts,s[1])}}}onBufferFlushing(t,{startOffset:e,endOffset:i,endOffsetSubtitles:r,type:s}){const{media:n}=this;if(n&&!(n.currentTime<i)){if(!s||"video"===s){const{captionsTracks:t}=this;Object.keys(t).forEach((r=>Ge(t[r],e,i)))}if(this.config.renderTextTracksNatively&&0===e&&void 0!==r){const{textTracks:t}=this;Object.keys(t).forEach((i=>Ge(t[i],e,r)))}}}extractCea608Data(t){const e=[[],[]],i=31&t[0];let r=2;for(let s=0;s<i;s++){const i=t[r++],s=127&t[r++],n=127&t[r++];if(0===s&&0===n)continue;if(!!(4&i)){const t=3&i;0!==t&&1!==t||(e[t].push(s),e[t].push(n))}}return e}},audioStreamController:class extends Dr{constructor(t,e,i){super(t,e,i,"[audio-stream-controller]",Pe),this.videoBuffer=null,this.videoTrackCC=-1,this.waitingVideoCC=-1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null,this.bufferedTrack=null,this.switchingTrack=null}_registerListeners(){const{hls:t}=this;t.on(R.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(R.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(R.MANIFEST_LOADING,this.onManifestLoading,this),t.on(R.LEVEL_LOADED,this.onLevelLoaded,this),t.on(R.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(R.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(R.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(R.ERROR,this.onError,this),t.on(R.BUFFER_RESET,this.onBufferReset,this),t.on(R.BUFFER_CREATED,this.onBufferCreated,this),t.on(R.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(R.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(R.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(R.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(R.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(R.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(R.MANIFEST_LOADING,this.onManifestLoading,this),t.off(R.LEVEL_LOADED,this.onLevelLoaded,this),t.off(R.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(R.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(R.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(R.ERROR,this.onError,this),t.off(R.BUFFER_RESET,this.onBufferReset,this),t.off(R.BUFFER_CREATED,this.onBufferCreated,this),t.off(R.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(R.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(R.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(R.FRAG_BUFFERED,this.onFragBuffered,this)}onInitPtsFound(t,{frag:e,id:i,initPTS:r,timescale:s}){if("main"===i){const t=e.cc;this.initPTS[e.cc]={baseTime:r,timescale:s},this.log(`InitPTS for cc: ${t} found from main: ${r}`),this.videoTrackCC=t,this.state===br&&this.tick()}}startLoad(t){if(!this.levels)return this.startPosition=t,void(this.state=mr);const e=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),e>0&&-1===t?(this.log(`Override startPosition with lastCurrentTime @${e.toFixed(3)}`),t=e,this.state=pr):(this.loadedmetadata=!1,this.state=Tr),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}doTick(){switch(this.state){case pr:this.doTickIdle();break;case Tr:{var t;const{levels:e,trackId:i}=this,r=null==e||null==(t=e[i])?void 0:t.details;if(r){if(this.waitForCdnTuneIn(r))break;this.state=br}break}case Er:{var e;const t=performance.now(),i=this.retryDate;if(!i||t>=i||null!=(e=this.media)&&e.seeking){const{levels:t,trackId:e}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((null==t?void 0:t[e])||null),this.state=pr}break}case br:{const t=this.waitingData;if(t){const{frag:e,part:i,cache:r,complete:s}=t;if(void 0!==this.initPTS[e.cc]){this.waitingData=null,this.waitingVideoCC=-1,this.state=yr;const t={frag:e,part:i,payload:r.flush(),networkDetails:null};this._handleFragmentLoadProgress(t),s&&super._handleFragmentLoadComplete(t)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${e.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{const t=this.getLoadPosition(),i=Ji.bufferInfo(this.mediaBuffer,t,this.config.maxBufferHole);Si(i.end,this.config.maxFragLookUpTolerance,e)<0&&(this.log(`Waiting fragment cc (${e.cc}) @ ${e.start} cancelled because another fragment at ${i.end} is needed`),this.clearWaitingFragment())}}else this.state=pr}}this.onTickEnd()}clearWaitingFragment(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=pr)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:t}=this;null!=t&&t.readyState&&(this.lastCurrentTime=t.currentTime)}doTickIdle(){const{hls:t,levels:e,media:i,trackId:r}=this,s=t.config;if(!i&&(this.startFragRequested||!s.startFragPrefetch)||null==e||!e[r])return;const n=e[r],a=n.details;if(!a||a.live&&this.levelLastLoaded!==n||this.waitForCdnTuneIn(a))return void(this.state=Tr);const o=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&o&&(this.bufferFlushed=!1,this.afterBufferFlushed(o,U,Pe));const l=this.getFwdBufferInfo(o,Pe);if(null===l)return;const{bufferedTrack:h,switchingTrack:d}=this;if(!d&&this._streamEnded(l,a))return t.trigger(R.BUFFER_EOS,{type:"audio"}),void(this.state=Lr);const u=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,_e),c=l.len,f=this.getMaxBufferLength(null==u?void 0:u.len),g=a.fragments,m=g[0].start;let p=this.flushing?this.getLoadPosition():l.end;if(d&&i){const t=this.getLoadPosition();h&&!Ns(d.attrs,h.attrs)&&(p=t),a.PTSKnown&&t<m&&(l.end>m||l.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=m+.05)}if(c>=f&&!d&&p<g[g.length-1].start)return;let v=this.getNextFragment(p,a),y=!1;if(v&&this.isLoopLoading(v,p)&&(y=!!v.gap,v=this.getNextFragmentLoopLoading(v,a,l,_e,f)),!v)return void(this.bufferFlushed=!0);const E=u&&v.start>u.end+a.targetduration;if(E||(null==u||!u.len)&&l.len){const t=this.getAppendedFrag(v.start,_e);if(null===t)return;if(y||(y=!!t.gap||!!E&&0===u.len),E&&!y||y&&l.nextStart&&l.nextStart<t.end)return}this.loadFragment(v,n,p)}getMaxBufferLength(t){const e=super.getMaxBufferLength();return t?Math.min(Math.max(e,t),this.config.maxMaxBufferLength):e}onMediaDetaching(){this.videoBuffer=null,this.bufferFlushed=this.flushing=!1,super.onMediaDetaching()}onAudioTracksUpdated(t,{audioTracks:e}){this.resetTransmuxer(),this.levels=e.map((t=>new si(t)))}onAudioTrackSwitching(t,e){const i=!!e.url;this.trackId=e.id;const{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),i?this.setInterval(100):this.resetTransmuxer(),i?(this.switchingTrack=e,this.state=pr,this.flushAudioIfNeeded(e)):(this.switchingTrack=null,this.bufferedTrack=e,this.state=mr),this.tick()}onManifestLoading(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=this.flushing=!1,this.levels=this.mainDetails=this.waitingData=this.bufferedTrack=this.cachedTrackLoadedData=this.switchingTrack=null,this.startFragRequested=!1,this.trackId=this.videoTrackCC=this.waitingVideoCC=-1}onLevelLoaded(t,e){this.mainDetails=e.details,null!==this.cachedTrackLoadedData&&(this.hls.trigger(R.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(t,e){var i;if(null==this.mainDetails)return void(this.cachedTrackLoadedData=e);const{levels:r}=this,{details:s,id:n}=e;if(!r)return void this.warn(`Audio tracks were reset while loading level ${n}`);this.log(`Audio track ${n} loaded [${s.startSN},${s.endSN}]${s.lastPartSn?`[part-${s.lastPartSn}-${s.lastPartIndex}]`:""},duration:${s.totalduration}`);const a=r[n];let o=0;if(s.live||null!=(i=a.details)&&i.live){this.checkLiveUpdate(s);const t=this.mainDetails;if(s.deltaUpdateFailed||!t)return;var l;if(!a.details&&s.hasProgramDateTime&&t.hasProgramDateTime)sr(s,t),o=s.fragments[0].start;else o=this.alignPlaylists(s,a.details,null==(l=this.levelLastLoaded)?void 0:l.details)}a.details=s,this.levelLastLoaded=a,this.startFragRequested||!this.mainDetails&&s.live||this.setStartPosition(this.mainDetails||s,o),this.state!==Tr||this.waitForCdnTuneIn(s)||(this.state=pr),this.tick()}_handleFragmentLoadProgress(t){var e;const{frag:i,part:r,payload:s}=t,{config:n,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);const l=o[a];if(!l)return void this.warn("Audio track is undefined on fragment load progress");const h=l.details;if(!h)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(i.start);const d=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let u=this.transmuxer;u||(u=this.transmuxer=new Os(this.hls,Pe,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const c=this.initPTS[i.cc],f=null==(e=i.initSegment)?void 0:e.data;if(void 0!==c){const t=!1,e=r?r.index:-1,n=-1!==e,a=new Zi(i.level,i.sn,i.stats.chunkCount,s.byteLength,e,n);u.push(s,f,d,"",i,r,h.totalduration,t,a,c)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${h.startSN} ,${h.endSN}],track ${a}`);const{cache:t}=this.waitingData=this.waitingData||{frag:i,part:r,cache:new Ir,complete:!1};t.push(new Uint8Array(s)),this.waitingVideoCC=this.videoTrackCC,this.state=br}}_handleFragmentLoadComplete(t){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(t,e){const i=e.tracks.audio;i&&(this.mediaBuffer=i.buffer||null),e.tracks.video&&(this.videoBuffer=e.tracks.video.buffer||null)}onFragBuffered(t,e){const{frag:i,part:r}=e;if(i.type===Pe)if(this.fragContextChanged(i))this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if("initSegment"!==i.sn){this.fragPrevious=i;const t=this.switchingTrack;t&&(this.bufferedTrack=t,this.switchingTrack=null,this.hls.trigger(R.AUDIO_TRACK_SWITCHED,v({},t)))}this.fragBufferedComplete(i,r)}else if(!this.loadedmetadata&&i.type===_e){const t=this.videoBuffer||this.media;if(t){Ji.getBuffered(t).length&&(this.loadedmetadata=!0)}}}onError(t,e){var i;if(e.fatal)this.state=Rr;else switch(e.details){case k.FRAG_GAP:case k.FRAG_PARSING_ERROR:case k.FRAG_DECRYPT_ERROR:case k.FRAG_LOAD_ERROR:case k.FRAG_LOAD_TIMEOUT:case k.KEY_LOAD_ERROR:case k.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Pe,e);break;case k.AUDIO_TRACK_LOAD_ERROR:case k.AUDIO_TRACK_LOAD_TIMEOUT:case k.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==Tr||(null==(i=e.context)?void 0:i.type)!==we||(this.state=pr);break;case k.BUFFER_APPEND_ERROR:case k.BUFFER_FULL_ERROR:if(!e.parent||"audio"!==e.parent)return;if(e.details===k.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(e)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case k.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onBufferFlushing(t,{type:e}){e!==B&&(this.flushing=!0)}onBufferFlushed(t,{type:e}){if(e!==B){this.flushing=!1,this.bufferFlushed=!0,this.state===Lr&&(this.state=pr);const t=this.mediaBuffer||this.media;t&&(this.afterBufferFlushed(t,e,Pe),this.tick())}}_handleTransmuxComplete(t){var e;const i="audio",{hls:r}=this,{remuxResult:s,chunkMeta:n}=t,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:h}=a,{details:d}=h,{audio:u,text:c,id3:f,initSegment:g}=s;if(!this.fragContextChanged(o)&&d){if(this.state=Sr,this.switchingTrack&&u&&this.completeAudioSwitch(this.switchingTrack),null!=g&&g.tracks){const t=o.initSegment||o;this._bufferInitSegment(h,g.tracks,t,n),r.trigger(R.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:i,tracks:g.tracks})}if(u){const{startPTS:t,endPTS:e,startDTS:i,endDTS:r}=u;l&&(l.elementaryStreams[U]={startPTS:t,endPTS:e,startDTS:i,endDTS:r}),o.setElementaryStreamInfo(U,t,e,i,r),this.bufferFragmentData(u,o,l,n)}if(null!=f&&null!=(e=f.samples)&&e.length){const t=T({id:i,frag:o,details:d},f);r.trigger(R.FRAG_PARSING_METADATA,t)}if(c){const t=T({id:i,frag:o,details:d},c);r.trigger(R.FRAG_PARSING_USERDATA,t)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(t,e,i,r){if(this.state!==Sr)return;e.video&&delete e.video;const s=e.audio;if(!s)return;s.id="audio";const n=t.audioCodec;this.log(`Init audio buffer, container:${s.container}, codecs[level/parsed]=[${n}/${s.codec}]`),n&&1===n.split(",").length&&(s.levelCodec=n),this.hls.trigger(R.BUFFER_CODECS,e);const a=s.initSegment;if(null!=a&&a.byteLength){const t={type:"audio",frag:i,part:null,chunkMeta:r,parent:i.type,data:a};this.hls.trigger(R.BUFFER_APPENDING,t)}this.tickImmediate()}loadFragment(t,e,i){const r=this.fragmentTracker.getState(t);var s;if(this.fragCurrent=t,this.switchingTrack||r===Vi||r===Wi)if("initSegment"===t.sn)this._loadInitSegment(t,e);else if(null!=(s=e.details)&&s.live&&!this.initPTS[t.cc]){this.log(`Waiting for video PTS in continuity counter ${t.cc} of live stream before loading audio fragment ${t.sn} of level ${this.trackId}`),this.state=br;const i=this.mainDetails;i&&i.fragments[0].start!==e.details.fragments[0].start&&sr(e.details,i)}else this.startFragRequested=!0,super.loadFragment(t,e,i);else this.clearTrackerIfNeeded(t)}flushAudioIfNeeded(t){const{media:e,bufferedTrack:i}=this,r=null==i?void 0:i.attrs,s=t.attrs;e&&r&&(r.CHANNELS!==s.CHANNELS||i.name!==t.name||i.lang!==t.lang)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null)}completeAudioSwitch(t){const{hls:e}=this;this.flushAudioIfNeeded(t),this.bufferedTrack=t,this.switchingTrack=null,e.trigger(R.AUDIO_TRACK_SWITCHED,v({},t))}},audioTrackController:class extends Ci{constructor(t){super(t,"[audio-track-controller]"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:t}=this;t.on(R.MANIFEST_LOADING,this.onManifestLoading,this),t.on(R.MANIFEST_PARSED,this.onManifestParsed,this),t.on(R.LEVEL_LOADING,this.onLevelLoading,this),t.on(R.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(R.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(R.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(R.MANIFEST_LOADING,this.onManifestLoading,this),t.off(R.MANIFEST_PARSED,this.onManifestParsed,this),t.off(R.LEVEL_LOADING,this.onLevelLoading,this),t.off(R.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(R.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(R.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.audioTracks||[]}onAudioTrackLoaded(t,e){const{id:i,groupId:r,details:s}=e,n=this.tracksInGroup[i];if(!n||n.groupId!==r)return void this.warn(`Audio track with id:${i} and group:${r} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=e.details,this.log(`Audio track ${i} "${n.name}" lang:${n.lang} group:${r} loaded [${s.startSN}-${s.endSN}]`),i===this.trackId&&this.playlistLoaded(i,e,a)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const i=e.audioGroups||null,r=this.groupIds;let s=this.currentTrack;if(!i||(null==r?void 0:r.length)!==(null==i?void 0:i.length)||null!=i&&i.some((t=>-1===(null==r?void 0:r.indexOf(t))))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter((t=>!i||-1!==i.indexOf(t.groupId)));if(t.length)this.selectDefaultTrack&&!t.some((t=>t.default))&&(this.selectDefaultTrack=!1),t.forEach(((t,e)=>{t.id=e}));else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const e=this.hls.config.audioPreference;if(!s&&e){const i=Bi(e,t,Ki);if(i>-1)s=t[i];else{const t=Bi(e,this.tracks);s=this.tracks[t]}}let r=this.findTrackId(s);-1===r&&s&&(r=this.findTrackId(null));const a={audioTracks:t};this.log(`Updating audio tracks, ${t.length} track(s) found in group(s): ${null==i?void 0:i.join(",")}`),this.hls.trigger(R.AUDIO_TRACKS_UPDATED,a);const o=this.trackId;if(-1!==r&&-1===o)this.setAudioTrack(r);else if(t.length&&-1===o){var n;const e=new Error(`No audio track selected for current audio group-ID(s): ${null==(n=this.groupIds)?void 0:n.join(",")} track count: ${t.length}`);this.warn(e.message),this.hls.trigger(R.ERROR,{type:b.MEDIA_ERROR,details:k.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:e})}}else this.shouldReloadPlaylist(s)&&this.setAudioTrack(this.trackId)}onError(t,e){!e.fatal&&e.context&&(e.context.type!==we||e.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(e.context.groupId)||(this.requestScheduled=-1,this.checkRetry(e)))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t)}setAudioOption(t){const e=this.hls;if(e.config.audioPreference=t,t){const i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){const r=this.currentTrack;if(r&&Gi(t,r,Ki))return r;const s=Bi(t,this.tracksInGroup,Ki);if(s>-1){const t=this.tracksInGroup[s];return this.setAudioTrack(s),t}if(r){let r=e.loadLevel;-1===r&&(r=e.firstAutoLevel);const s=function(t,e,i,r,s){const n=e[r],a=e.reduce(((t,e,i)=>{const r=e.uri;return(t[r]||(t[r]=[])).push(i),t}),{})[n.uri];a.length>1&&(r=Math.max.apply(Math,a));const o=n.videoRange,l=n.frameRate,h=n.codecSet.substring(0,4),d=Hi(e,r,(e=>{if(e.videoRange!==o||e.frameRate!==l||e.codecSet.substring(0,4)!==h)return!1;const r=e.audioGroups,n=i.filter((t=>!r||-1!==r.indexOf(t.groupId)));return Bi(t,n,s)>-1}));return d>-1?d:Hi(e,r,(e=>{const r=e.audioGroups,n=i.filter((t=>!r||-1!==r.indexOf(t.groupId)));return Bi(t,n,s)>-1}))}(t,e.levels,i,r,Ki);if(-1===s)return null;e.nextLoadLevel=s}if(t.channels||t.audioCodec){const e=Bi(t,i);if(e>-1)return i[e]}}}return null}setAudioTrack(t){const e=this.tracksInGroup;if(t<0||t>=e.length)return void this.warn(`Invalid audio track id: ${t}`);this.clearTimer(),this.selectDefaultTrack=!1;const i=this.currentTrack,r=e[t],s=r.details&&!r.details.live;if(t===this.trackId&&r===i&&s)return;if(this.log(`Switching to audio-track ${t} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=t,this.currentTrack=r,this.hls.trigger(R.AUDIO_TRACK_SWITCHING,v({},r)),s)return;const n=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(n)}findTrackId(t){const e=this.tracksInGroup;for(let i=0;i<e.length;i++){const r=e[i];if((!this.selectDefaultTrack||r.default)&&(!t||Gi(t,r,Ki)))return i}if(t){const{name:i,lang:r,assocLang:s,characteristics:n,audioCodec:a,channels:o}=t;for(let t=0;t<e.length;t++){if(Gi({name:i,lang:r,assocLang:s,characteristics:n,audioCodec:a,channels:o},e[t],Ki))return t}for(let i=0;i<e.length;i++){const r=e[i];if(Ns(t.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<e.length;i++){const r=e[i];if(Ns(t.attrs,r.attrs,["LANGUAGE"]))return i}}return-1}loadPlaylist(t){const e=this.currentTrack;if(this.shouldLoadPlaylist(e)&&e){super.loadPlaylist();const i=e.id,r=e.groupId;let s=e.url;if(t)try{s=t.addDirectives(s)}catch(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}this.log(`loading audio-track playlist ${i} "${e.name}" lang:${e.lang} group:${r}`),this.clearTimer(),this.hls.trigger(R.AUDIO_TRACK_LOADING,{url:s,id:i,groupId:r,deliveryDirectives:t||null})}}},emeController:Gn,cmcdController:class{constructor(t){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=t=>{try{this.apply(t,{ot:Hn.MANIFEST,su:!this.initialized})}catch(t){_.warn("Could not generate manifest CMCD data.",t)}},this.applyFragmentData=t=>{try{const e=t.frag,i=this.hls.levels[e.level],r=this.getObjectType(e),s={d:1e3*e.duration,ot:r};r!==Hn.VIDEO&&r!==Hn.AUDIO&&r!=Hn.MUXED||(s.br=i.bitrate/1e3,s.tb=this.getTopBandwidth(r)/1e3,s.bl=this.getBufferLength(r)),this.apply(t,s)}catch(t){_.warn("Could not generate segment CMCD data.",t)}},this.hls=t;const e=this.config=t.config,{cmcd:i}=e;null!=i&&(e.pLoader=this.createPlaylistLoader(),e.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||function(){try{return crypto.randomUUID()}catch(t){try{const t=URL.createObjectURL(new Blob),e=t.toString();return URL.revokeObjectURL(t),e.slice(e.lastIndexOf("/")+1)}catch(t){let e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(t=>{const i=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?i:3&i|8).toString(16)}))}}}(),this.cid=i.contentId,this.useHeaders=!0===i.useHeaders,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const t=this.hls;t.on(R.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(R.MEDIA_DETACHED,this.onMediaDetached,this),t.on(R.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(R.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(R.MEDIA_DETACHED,this.onMediaDetached,this),t.off(R.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=null}onMediaAttached(t,e){this.media=e.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(t,e){var i,r;this.audioBuffer=null==(i=e.tracks.audio)?void 0:i.buffer,this.videoBuffer=null==(r=e.tracks.video)?void 0:r.buffer}createData(){var t;return{v:1,sf:$n.HLS,sid:this.sid,cid:this.cid,pr:null==(t=this.media)?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,e={}){T(e,this.createData());const i=e.ot===Hn.INIT||e.ot===Hn.VIDEO||e.ot===Hn.MUXED;this.starved&&i&&(e.bs=!0,e.su=!0,this.starved=!1),null==e.su&&(e.su=this.buffering);const{includeKeys:r}=this;r&&(e=Object.keys(e).reduce(((t,i)=>(r.includes(i)&&(t[i]=e[i]),t)),{})),this.useHeaders?(t.headers||(t.headers={}),Aa(t.headers,e)):t.url=ba(t.url,e)}getObjectType(t){const{type:e}=t;return"subtitle"===e?Hn.TIMED_TEXT:"initSegment"===t.sn?Hn.INIT:"audio"===e?Hn.AUDIO:"main"===e?this.hls.audioTracks.length?Hn.VIDEO:Hn.MUXED:void 0}getTopBandwidth(t){let e,i=0;const r=this.hls;if(t===Hn.AUDIO)e=r.audioTracks;else{const t=r.maxAutoLevel,i=t>-1?t+1:r.levels.length;e=r.levels.slice(0,i)}for(const t of e)t.bitrate>i&&(i=t.bitrate);return i>0?i:NaN}getBufferLength(t){const e=this.hls.media,i=t===Hn.AUDIO?this.audioBuffer:this.videoBuffer;if(!i||!e)return NaN;return 1e3*Ji.bufferInfo(i,e.currentTime,this.config.maxBufferHole).len}createPlaylistLoader(){const{pLoader:t}=this.config,e=this.applyPlaylistData,i=t||this.config.loader;return class{constructor(t){this.loader=void 0,this.loader=new i(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,i,r){e(t),this.loader.load(t,i,r)}}}createFragmentLoader(){const{fLoader:t}=this.config,e=this.applyFragmentData,i=t||this.config.loader;return class{constructor(t){this.loader=void 0,this.loader=new i(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,i,r){e(t),this.loader.load(t,i,r)}}}},contentSteeringController:class{constructor(t){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=t,this.log=_.log.bind(_,"[content-steering]:"),this.registerListeners()}registerListeners(){const t=this.hls;t.on(R.MANIFEST_LOADING,this.onManifestLoading,this),t.on(R.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(R.MANIFEST_PARSED,this.onManifestParsed,this),t.on(R.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(R.MANIFEST_LOADING,this.onManifestLoading,this),t.off(R.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(R.MANIFEST_PARSED,this.onManifestParsed,this),t.off(R.ERROR,this.onError,this))}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const t=1e3*this.timeToLoad-(performance.now()-this.updated);if(t>0)return void this.scheduleRefresh(this.uri,t)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(t){const e=this.levels;e&&(this.levels=e.filter((e=>e!==t)))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(t,e){const{contentSteering:i}=e;null!==i&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(t,e){this.audioTracks=e.audioTracks,this.subtitleTracks=e.subtitleTracks}onError(t,e){const{errorAction:i}=e;if((null==i?void 0:i.action)===Ri&&i.flags===Ii){const t=this.levels;let r=this.pathwayPriority,s=this.pathwayId;if(e.context){const{groupId:i,pathwayId:r,type:n}=e.context;i&&t?s=this.getPathwayForGroupId(i,n,s):r&&(s=r)}s in this.penalizedPathways||(this.penalizedPathways[s]=performance.now()),!r&&t&&(r=t.reduce(((t,e)=>(-1===t.indexOf(e.pathwayId)&&t.push(e.pathwayId),t)),[])),r&&r.length>1&&(this.updatePathwayPriority(r),i.resolved=this.pathwayId!==s),i.resolved||_.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${s} levels: ${t?t.length:t} priorities: ${JSON.stringify(r)} penalized: ${JSON.stringify(this.penalizedPathways)}`)}}filterParsedLevels(t){this.levels=t;let e=this.getLevelsForPathway(this.pathwayId);if(0===e.length){const i=t[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),e=this.getLevelsForPathway(i),this.pathwayId=i}return e.length!==t.length?(this.log(`Found ${e.length}/${t.length} levels in Pathway "${this.pathwayId}"`),e):t}getLevelsForPathway(t){return null===this.levels?[]:this.levels.filter((e=>t===e.pathwayId))}updatePathwayPriority(t){let e;this.pathwayPriority=t;const i=this.penalizedPathways,r=performance.now();Object.keys(i).forEach((t=>{r-i[t]>3e5&&delete i[t]}));for(let r=0;r<t.length;r++){const s=t[r];if(s in i)continue;if(s===this.pathwayId)return;const n=this.hls.nextLoadLevel,a=this.hls.levels[n];if(e=this.getLevelsForPathway(s),e.length>0){this.log(`Setting Pathway to "${s}"`),this.pathwayId=s,fi(e),this.hls.trigger(R.LEVELS_UPDATED,{levels:e});const t=this.hls.levels[n];a&&t&&this.levels&&(t.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&t.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${t.bitrate}`),this.hls.nextLoadLevel=n);break}}}getPathwayForGroupId(t,e,i){const r=this.getLevelsForPathway(i).concat(this.levels||[]);for(let i=0;i<r.length;i++)if(e===we&&r[i].hasAudioGroup(t)||e===Ce&&r[i].hasSubtitleGroup(t))return r[i].pathwayId;return i}clonePathways(t){const e=this.levels;if(!e)return;const i={},r={};t.forEach((t=>{const{ID:s,"BASE-ID":n,"URI-REPLACEMENT":a}=t;if(e.some((t=>t.pathwayId===s)))return;const o=this.getLevelsForPathway(n).map((t=>{const e=new M(t.attrs);e["PATHWAY-ID"]=s;const n=e.AUDIO&&`${e.AUDIO}_clone_${s}`,o=e.SUBTITLES&&`${e.SUBTITLES}_clone_${s}`;n&&(i[e.AUDIO]=n,e.AUDIO=n),o&&(r[e.SUBTITLES]=o,e.SUBTITLES=o);const l=Da(t.uri,e["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),h=new si({attrs:e,audioCodec:t.audioCodec,bitrate:t.bitrate,height:t.height,name:t.name,url:l,videoCodec:t.videoCodec,width:t.width});if(t.audioGroups)for(let e=1;e<t.audioGroups.length;e++)h.addGroupId("audio",`${t.audioGroups[e]}_clone_${s}`);if(t.subtitleGroups)for(let e=1;e<t.subtitleGroups.length;e++)h.addGroupId("text",`${t.subtitleGroups[e]}_clone_${s}`);return h}));e.push(...o),ka(this.audioTracks,i,a,s),ka(this.subtitleTracks,r,a,s)}))}loadSteeringManifest(t){const e=this.hls.config,i=e.loader;let r;this.loader&&this.loader.destroy(),this.loader=new i(e);try{r=new self.URL(t)}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${t}`)}if("data:"!==r.protocol){const t=0|(this.hls.bandwidthEstimate||e.abrEwmaDefaultEstimate);r.searchParams.set("_HLS_pathway",this.pathwayId),r.searchParams.set("_HLS_throughput",""+t)}const s={responseType:"json",url:r.href},n=e.steeringManifestLoadPolicy.default,a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(t,e,i,s)=>{this.log(`Loaded steering manifest: "${r}"`);const n=t.data;if(1!==n.VERSION)return void this.log(`Steering VERSION ${n.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=n.TTL;const{"RELOAD-URI":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":l}=n;if(a)try{this.uri=new self.URL(a,r).href}catch(t){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||i.url),o&&this.clonePathways(o);const h={steeringManifest:n,url:r.toString()};this.hls.trigger(R.STEERING_MANIFEST_LOADED,h),l&&this.updatePathwayPriority(l)},onError:(t,e,i,r)=>{if(this.log(`Error loading steering manifest: ${t.code} ${t.text} (${e.url})`),this.stopLoad(),410===t.code)return this.enabled=!1,void this.log(`Steering manifest ${e.url} no longer available`);let s=1e3*this.timeToLoad;if(429!==t.code)this.scheduleRefresh(this.uri||e.url,s);else{const t=this.loader;if("function"==typeof(null==t?void 0:t.getResponseHeader)){const e=t.getResponseHeader("Retry-After");e&&(s=1e3*parseFloat(e))}this.log(`Steering manifest ${e.url} rate limited`)}},onTimeout:(t,e,i)=>{this.log(`Timeout loading steering manifest (${e.url})`),this.scheduleRefresh(this.uri||e.url)}};this.log(`Requesting steering manifest: ${r}`),this.loader.load(s,o,l)}scheduleRefresh(t,e=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout((()=>{var e;const i=null==(e=this.hls)?void 0:e.media;!i||i.ended?this.scheduleRefresh(t,1e3*this.timeToLoad):this.loadSteeringManifest(t)}),e)}}});function Na(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(Na):Object.keys(t).reduce(((e,i)=>(e[i]=Na(t[i]),e)),{}):t}function Ua(t){const e=t.loader;if(e!==_a&&e!==wa)_.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1;else{(function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(t){}return!1})()&&(t.loader=_a,t.progressive=!0,t.enableSoftwareAES=!0,_.log("[config]: Progressive streaming enabled, using FetchLoader"))}}let Ba;class Ga extends Ci{constructor(t,e){super(t,"[level-controller]"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=e,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(R.MANIFEST_LOADING,this.onManifestLoading,this),t.on(R.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(R.LEVEL_LOADED,this.onLevelLoaded,this),t.on(R.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(R.FRAG_BUFFERED,this.onFragBuffered,this),t.on(R.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(R.MANIFEST_LOADING,this.onManifestLoading,this),t.off(R.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(R.LEVEL_LOADED,this.onLevelLoaded,this),t.off(R.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(R.FRAG_BUFFERED,this.onFragBuffered,this),t.off(R.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach((t=>{t.loadError=0,t.fragmentError=0})),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(t,e){this.resetLevels()}onManifestLoaded(t,e){const i=this.hls.config.preferManagedMediaSource,r=[],s={},n={};let a=!1,o=!1,l=!1;e.levels.forEach((t=>{var e,h;const d=t.attrs;let{audioCodec:u,videoCodec:c}=t;-1!==(null==(e=u)?void 0:e.indexOf("mp4a.40.34"))&&(Ba||(Ba=/chrome|firefox/i.test(navigator.userAgent)),Ba&&(t.audioCodec=u=void 0)),u&&(t.audioCodec=u=ce(u,i)),0===(null==(h=c)?void 0:h.indexOf("avc1"))&&(c=t.videoCodec=function(t){const e=t.split(",");for(let t=0;t<e.length;t++){const i=e[t].split(".");if(i.length>2){let r=i.shift()+".";r+=parseInt(i.shift()).toString(16),r+=("000"+parseInt(i.shift()).toString(16)).slice(-4),e[t]=r}}return e.join(",")}(c));const{width:f,height:g,unknownCodecs:m}=t;if(a||(a=!(!f||!g)),o||(o=!!c),l||(l=!!u),null!=m&&m.length||u&&!ne(u,"audio",i)||c&&!ne(c,"video",i))return;const{CODECS:p,"FRAME-RATE":v,"HDCP-LEVEL":y,"PATHWAY-ID":E,RESOLUTION:T,"VIDEO-RANGE":S}=d,A=`${`${E||"."}-`}${t.bitrate}-${T}-${v}-${p}-${S}-${y}`;if(s[A])if(s[A].uri===t.url||t.attrs["PATHWAY-ID"])s[A].addGroupId("audio",d.AUDIO),s[A].addGroupId("text",d.SUBTITLES);else{const e=n[A]+=1;t.attrs["PATHWAY-ID"]=new Array(e+1).join(".");const i=new si(t);s[A]=i,r.push(i)}else{const e=new si(t);s[A]=e,n[A]=1,r.push(e)}})),this.filterAndSortMediaOptions(r,e,a,o,l)}filterAndSortMediaOptions(t,e,i,r,s){let n=[],a=[],o=t;if((i||r)&&s&&(o=o.filter((({videoCodec:t,videoRange:e,width:i,height:r})=>{return(!!t||!(!i||!r))&&(!!(s=e)&&Je.indexOf(s)>-1);var s}))),0===o.length)return void Promise.resolve().then((()=>{if(this.hls){e.levels.length&&this.warn(`One or more CODECS in variant not supported: ${JSON.stringify(e.levels[0].attrs)}`);const t=new Error("no level with compatible codecs found in manifest");this.hls.trigger(R.ERROR,{type:b.MEDIA_ERROR,details:k.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:t,reason:t.message})}}));if(e.audioTracks){const{preferManagedMediaSource:t}=this.hls.config;n=e.audioTracks.filter((e=>!e.audioCodec||ne(e.audioCodec,"audio",t))),Ka(n)}e.subtitles&&(a=e.subtitles,Ka(a));const l=o.slice(0);o.sort(((t,e)=>{if(t.attrs["HDCP-LEVEL"]!==e.attrs["HDCP-LEVEL"])return(t.attrs["HDCP-LEVEL"]||"")>(e.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&t.height!==e.height)return t.height-e.height;if(t.frameRate!==e.frameRate)return t.frameRate-e.frameRate;if(t.videoRange!==e.videoRange)return Je.indexOf(t.videoRange)-Je.indexOf(e.videoRange);if(t.videoCodec!==e.videoCodec){const i=le(t.videoCodec),r=le(e.videoCodec);if(i!==r)return r-i}if(t.uri===e.uri&&t.codecSet!==e.codecSet){const i=he(t.codecSet),r=he(e.codecSet);if(i!==r)return r-i}return t.averageBitrate!==e.averageBitrate?t.averageBitrate-e.averageBitrate:0}));let h=l[0];if(this.steering&&(o=this.steering.filterParsedLevels(o),o.length!==l.length))for(let t=0;t<l.length;t++)if(l[t].pathwayId===o[0].pathwayId){h=l[t];break}this._levels=o;for(let t=0;t<o.length;t++)if(o[t]===h){var d;this._firstLevel=t;const e=h.bitrate,i=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${o.length} level(s) found, first bitrate: ${e}`),void 0===(null==(d=this.hls.userConfig)?void 0:d.abrEwmaDefaultEstimate)){const t=Math.min(e,this.hls.config.abrEwmaDefaultEstimateMax);t>i&&i===Fa.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=t)}break}const u=s&&!r,c={levels:o,audioTracks:n,subtitleTracks:a,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:s,video:r,altAudio:!u&&n.some((t=>!!t.url))};this.hls.trigger(R.MANIFEST_PARSED,c),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return 0===this._levels.length?null:this._levels}get level(){return this.currentLevelIndex}set level(t){const e=this._levels;if(0===e.length)return;if(t<0||t>=e.length){const i=new Error("invalid level idx"),r=t<0;if(this.hls.trigger(R.ERROR,{type:b.OTHER_ERROR,details:k.LEVEL_SWITCH_ERROR,level:t,fatal:r,error:i,reason:i.message}),r)return;t=Math.min(t,e.length-1)}const i=this.currentLevelIndex,r=this.currentLevel,s=r?r.attrs["PATHWAY-ID"]:void 0,n=e[t],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=n,i===t&&n.details&&r&&s===a)return;this.log(`Switching to level ${t} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${a?" with Pathway "+a:""} from level ${i}${s?" with Pathway "+s:""}`);const o={level:t,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(R.LEVEL_SWITCHING,o);const l=n.details;if(!l||l.live){const t=this.switchParams(n.uri,null==r?void 0:r.details,l);this.loadPlaylist(t)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(t){this.manualLevelIndex=t,void 0===this._startLevel&&(this._startLevel=t),-1!==t&&(this.level=t)}get firstLevel(){return this._firstLevel}set firstLevel(t){this._firstLevel=t}get startLevel(){if(void 0===this._startLevel){const t=this.hls.config.startLevel;return void 0!==t?t:this.hls.firstAutoLevel}return this._startLevel}set startLevel(t){this._startLevel=t}onError(t,e){!e.fatal&&e.context&&e.context.type===Ie&&e.context.level===this.level&&this.checkRetry(e)}onFragBuffered(t,{frag:e}){if(void 0!==e&&e.type===_e){const t=e.elementaryStreams;if(!Object.keys(t).some((e=>!!t[e])))return;const i=this._levels[e.level];null!=i&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(t,e){var i;const{level:r,details:s}=e,n=this._levels[r];var a;if(!n)return this.warn(`Invalid level index ${r}`),void(null!=(a=e.deliveryDirectives)&&a.skip&&(s.deltaUpdateFailed=!0));r===this.currentLevelIndex?(0===n.fragmentError&&(n.loadError=0),this.playlistLoaded(r,e,n.details)):null!=(i=e.deliveryDirectives)&&i.skip&&(s.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist();const e=this.currentLevelIndex,i=this.currentLevel;if(i&&this.shouldLoadPlaylist(i)){let r=i.uri;if(t)try{r=t.addDirectives(r)}catch(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}const s=i.attrs["PATHWAY-ID"];this.log(`Loading level index ${e}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""} with${s?" Pathway "+s:""} ${r}`),this.clearTimer(),this.hls.trigger(R.LEVEL_LOADING,{url:r,level:e,pathwayId:i.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(t){this.level=t,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=t)}removeLevel(t){var e;const i=this._levels.filter(((e,i)=>i!==t||(this.steering&&this.steering.removeLevel(e),e===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,e.details&&e.details.fragments.forEach((t=>t.level=-1))),!1)));fi(i),this._levels=i,this.currentLevelIndex>-1&&null!=(e=this.currentLevel)&&e.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(R.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(t,{levels:e}){this._levels=e}checkMaxAutoUpdated(){const{autoLevelCapping:t,maxAutoLevel:e,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==e&&(this._maxAutoLevel=e,this.hls.trigger(R.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:e,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function Ka(t){const e={};t.forEach((t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++}))}class Ha{constructor(t){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=t}abort(t){for(const i in this.keyUriToKeyInfo){const r=this.keyUriToKeyInfo[i].loader;if(r){var e;if(t&&t!==(null==(e=r.context)?void 0:e.frag.type))return;r.abort()}}}detach(){for(const t in this.keyUriToKeyInfo){const e=this.keyUriToKeyInfo[t];(e.mediaKeySessionContext||e.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[t]}}destroy(){this.detach();for(const t in this.keyUriToKeyInfo){const e=this.keyUriToKeyInfo[t].loader;e&&e.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(t,e=k.KEY_LOAD_ERROR,i,r,s){return new hr({type:b.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:s,error:i,networkDetails:r})}loadClear(t,e){if(this.emeController&&this.config.emeEnabled){const{sn:i,cc:r}=t;for(let t=0;t<e.length;t++){const s=e[t];if(r<=s.cc&&("initSegment"===i||"initSegment"===s.sn||i<s.sn)){this.emeController.selectKeySystemFormat(s).then((t=>{s.setKeyFormat(t)}));break}}}}load(t){return!t.decryptdata&&t.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(t).then((e=>this.loadInternal(t,e))):this.loadInternal(t)}loadInternal(t,e){var i,r;e&&t.setKeyFormat(e);const s=t.decryptdata;if(!s){const i=new Error(e?`Expected frag.decryptdata to be defined after setting format ${e}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(t,k.KEY_LOAD_ERROR,i))}const n=s.uri;if(!n)return Promise.reject(this.createKeyLoadError(t,k.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));let a=this.keyUriToKeyInfo[n];if(null!=(i=a)&&i.decryptdata.key)return s.key=a.decryptdata.key,Promise.resolve({frag:t,keyInfo:a});var o;if(null!=(r=a)&&r.keyLoadPromise)switch(null==(o=a.mediaKeySessionContext)?void 0:o.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return a.keyLoadPromise.then((e=>(s.key=e.keyInfo.decryptdata.key,{frag:t,keyInfo:a})))}switch(a=this.keyUriToKeyInfo[n]={decryptdata:s,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},s.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===s.keyFormat?this.loadKeyHTTP(a,t):this.loadKeyEME(a,t);case"AES-128":return this.loadKeyHTTP(a,t);default:return Promise.reject(this.createKeyLoadError(t,k.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${s.method}"`)))}}loadKeyEME(t,e){const i={frag:e,keyInfo:t};if(this.emeController&&this.config.emeEnabled){const e=this.emeController.loadKey(i);if(e)return(t.keyLoadPromise=e.then((e=>(t.mediaKeySessionContext=e,i)))).catch((e=>{throw t.keyLoadPromise=null,e}))}return Promise.resolve(i)}loadKeyHTTP(t,e){const i=this.config,r=new(0,i.loader)(i);return e.keyLoader=t.loader=r,t.keyLoadPromise=new Promise(((s,n)=>{const a={keyInfo:t,frag:e,responseType:"arraybuffer",url:t.decryptdata.uri},o=i.keyLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(t,e,i,r)=>{const{frag:a,keyInfo:o,url:l}=i;if(!a.decryptdata||o!==this.keyUriToKeyInfo[l])return n(this.createKeyLoadError(a,k.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),r));o.decryptdata.key=a.decryptdata.key=new Uint8Array(t.data),a.keyLoader=null,o.loader=null,s({frag:a,keyInfo:o})},onError:(t,i,r,s)=>{this.resetLoader(i),n(this.createKeyLoadError(e,k.KEY_LOAD_ERROR,new Error(`HTTP Error ${t.code} loading key ${t.text}`),r,v({url:a.url,data:void 0},t)))},onTimeout:(t,i,r)=>{this.resetLoader(i),n(this.createKeyLoadError(e,k.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),r))},onAbort:(t,i,r)=>{this.resetLoader(i),n(this.createKeyLoadError(e,k.INTERNAL_ABORTED,new Error("key loading aborted"),r))}};r.load(a,l,h)}))}resetLoader(t){const{frag:e,keyInfo:i,url:r}=t,s=i.loader;e.keyLoader===s&&(e.keyLoader=null,i.loader=null),delete this.keyUriToKeyInfo[r],s&&s.destroy()}}function $a(){return self.SourceBuffer||self.WebKitSourceBuffer}function Va(){if(!re())return!1;const t=$a();return!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove}class Ya{constructor(t,e,i,r){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=t,this.media=e,this.fragmentTracker=i,this.hls=r}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(t,e){const{config:i,media:r,stalled:s}=this;if(null===r)return;const{currentTime:n,seeking:a}=r,o=this.seeking&&!a,l=!this.seeking&&a;if(this.seeking=a,n!==t){if(this.moved=!0,a||(this.nudgeRetry=0),null!==s){if(this.stallReported){const t=self.performance.now()-s;_.warn(`playback not stuck anymore @${n}, after ${Math.round(t)}ms`),this.stallReported=!1}this.stalled=null}return}if(l||o)return void(this.stalled=null);if(r.paused&&!a||r.ended||0===r.playbackRate||!Ji.getBuffered(r).length)return void(this.nudgeRetry=0);const h=Ji.bufferInfo(r,n,0),d=h.nextStart||0;if(a){const t=h.len>2,i=!d||e&&e.start<=n||d-n>2&&!this.fragmentTracker.getPartialFragment(n);if(t||i)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var u;if(!(h.len>0)&&!d)return;const t=Math.max(d,h.start||0)-n,e=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,i=(null==e||null==(u=e.details)?void 0:u.live)?2*e.details.targetduration:2,s=this.fragmentTracker.getPartialFragment(n);if(t>0&&(t<=i||s))return void(r.paused||this._trySkipBufferHole(s))}const c=self.performance.now();if(null===s)return void(this.stalled=c);const f=c-s;if(!a&&f>=250&&(this._reportStall(h),!this.media))return;const g=Ji.bufferInfo(r,n,i.maxBufferHole);this._tryFixBufferStall(g,f)}_tryFixBufferStall(t,e){const{config:i,fragmentTracker:r,media:s}=this;if(null===s)return;const n=s.currentTime,a=r.getPartialFragment(n);if(a){if(this._trySkipBufferHole(a)||!this.media)return}(t.len>i.maxBufferHole||t.nextStart&&t.nextStart-n<i.maxBufferHole)&&e>1e3*i.highBufferWatchdogPeriod&&(_.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(t){const{hls:e,media:i,stallReported:r}=this;if(!r&&i){this.stallReported=!0;const r=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${JSON.stringify(t)})`);_.warn(r.message),e.trigger(R.ERROR,{type:b.MEDIA_ERROR,details:k.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:t.len})}}_trySkipBufferHole(t){const{config:e,hls:i,media:r}=this;if(null===r)return 0;const s=r.currentTime,n=Ji.bufferInfo(r,s,0),a=s<n.start?n.start:n.nextStart;if(a){const o=n.len<=e.maxBufferHole,l=n.len>0&&n.len<1&&r.readyState<3,h=a-s;if(h>0&&(o||l)){if(h>e.maxBufferHole){const{fragmentTracker:e}=this;let i=!1;if(0===s){const t=e.getAppendedFrag(0,_e);t&&a<t.end&&(i=!0)}if(!i){const i=t||e.getAppendedFrag(s,_e);if(i){let t=!1,r=i.end;for(;r<a;){const i=e.getPartialFragment(r);if(!i){t=!0;break}r+=i.duration}if(t)return 0}}}const n=Math.max(a+.05,s+.1);if(_.warn(`skipping hole, adjusting currentTime from ${s} to ${n}`),this.moved=!0,this.stalled=null,r.currentTime=n,t&&!t.gap){const e=new Error(`fragment loaded with buffer holes, seeking from ${s} to ${n}`);i.trigger(R.ERROR,{type:b.MEDIA_ERROR,details:k.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:e,reason:e.message,frag:t})}return n}}return 0}_tryNudgeBuffer(){const{config:t,hls:e,media:i,nudgeRetry:r}=this;if(null===i)return;const s=i.currentTime;if(this.nudgeRetry++,r<t.nudgeMaxRetry){const n=s+(r+1)*t.nudgeOffset,a=new Error(`Nudging 'currentTime' from ${s} to ${n}`);_.warn(a.message),i.currentTime=n,e.trigger(R.ERROR,{type:b.MEDIA_ERROR,details:k.BUFFER_NUDGE_ON_STALL,error:a,fatal:!1})}else{const i=new Error(`Playhead still not moving while enough data buffered @${s} after ${t.nudgeMaxRetry} nudges`);_.error(i.message),e.trigger(R.ERROR,{type:b.MEDIA_ERROR,details:k.BUFFER_STALLED_ERROR,error:i,fatal:!0})}}}class Wa extends Dr{constructor(t,e,i){super(t,e,i,"[stream-controller]",_e),this.audioCodecSwap=!1,this.gapController=null,this.level=-1,this._forceStartLoad=!1,this.altAudio=!1,this.audioOnly=!1,this.fragPlaying=null,this.onvplaying=null,this.onvseeked=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(R.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(R.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(R.MANIFEST_LOADING,this.onManifestLoading,this),t.on(R.MANIFEST_PARSED,this.onManifestParsed,this),t.on(R.LEVEL_LOADING,this.onLevelLoading,this),t.on(R.LEVEL_LOADED,this.onLevelLoaded,this),t.on(R.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(R.ERROR,this.onError,this),t.on(R.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(R.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(R.BUFFER_CREATED,this.onBufferCreated,this),t.on(R.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(R.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(R.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(R.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(R.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(R.MANIFEST_LOADING,this.onManifestLoading,this),t.off(R.MANIFEST_PARSED,this.onManifestParsed,this),t.off(R.LEVEL_LOADED,this.onLevelLoaded,this),t.off(R.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(R.ERROR,this.onError,this),t.off(R.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(R.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(R.BUFFER_CREATED,this.onBufferCreated,this),t.off(R.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(R.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(R.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying()}startLoad(t){if(this.levels){const{lastCurrentTime:e,hls:i}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let t=i.startLevel;-1===t&&(i.config.testBandwidth&&this.levels.length>1?(t=0,this.bitrateTest=!0):t=i.firstAutoLevel),i.nextLoadLevel=t,this.level=i.loadLevel,this.loadedmetadata=!1}e>0&&-1===t&&(this.log(`Override startPosition with lastCurrentTime @${e.toFixed(3)}`),t=e),this.state=pr,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}else this._forceStartLoad=!0,this.state=mr}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case kr:{const{levels:t,level:e}=this,i=null==t?void 0:t[e],r=null==i?void 0:i.details;if(r&&(!r.live||this.levelLastLoaded===i)){if(this.waitForCdnTuneIn(r))break;this.state=pr;break}if(this.hls.nextLoadLevel!==this.level){this.state=pr;break}break}case Er:{var t;const e=self.performance.now(),i=this.retryDate;if(!i||e>=i||null!=(t=this.media)&&t.seeking){const{levels:t,level:e}=this,i=null==t?void 0:t[e];this.resetStartWhenNotLoaded(i||null),this.state=pr}}}this.state===pr&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:e,levels:i,media:r}=this;if(null===e||!r&&(this.startFragRequested||!t.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const s=t.nextLoadLevel;if(null==i||!i[s])return;const n=i[s],a=this.getMainFwdBufferInfo();if(null===a)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const t={};return this.altAudio&&(t.type="video"),this.hls.trigger(R.BUFFER_EOS,t),void(this.state=Lr)}t.loadLevel!==s&&-1===t.manualLevel&&this.log(`Adapting to level ${s} from level ${this.level}`),this.level=t.nextLoadLevel=s;const l=n.details;if(!l||this.state===kr||l.live&&this.levelLastLoaded!==n)return this.level=s,void(this.state=kr);const h=a.len,d=this.getMaxBufferLength(n.maxBitrate);if(h>=d)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const u=this.backtrackFragment?this.backtrackFragment.start:a.end;let c=this.getNextFragment(u,l);if(this.couldBacktrack&&!this.fragPrevious&&c&&"initSegment"!==c.sn&&this.fragmentTracker.getState(c)!==ji){var f;const t=(null!=(f=this.backtrackFragment)?f:c).sn-l.startSN,e=l.fragments[t-1];e&&c.cc===e.cc&&(c=e,this.fragmentTracker.removeFragment(e))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(c&&this.isLoopLoading(c,u)){if(!c.gap){const t=this.audioOnly&&!this.altAudio?U:B,e=(t===B?this.videoBuffer:this.mediaBuffer)||this.media;e&&this.afterBufferFlushed(e,t,_e)}c=this.getNextFragmentLoopLoading(c,l,a,_e,d)}c&&(!c.initSegment||c.initSegment.data||this.bitrateTest||(c=c.initSegment),this.loadFragment(c,n,u))}loadFragment(t,e,i){const r=this.fragmentTracker.getState(t);this.fragCurrent=t,r===Vi||r===Wi?"initSegment"===t.sn?this._loadInitSegment(t,e):this.bitrateTest?(this.log(`Fragment ${t.sn} of level ${t.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(t,e)):(this.startFragRequested=!0,super.loadFragment(t,e,i)):this.clearTrackerIfNeeded(t)}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,_e)}followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:t,media:e}=this;if(null!=e&&e.readyState){let i;const r=this.getAppendedFrag(e.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);const s=this.getLevelDetails();if(null!=s&&s.live){const t=this.getMainFwdBufferInfo();if(!t||t.len<2*s.targetduration)return}if(!e.paused&&t){const e=t[this.hls.nextLoadLevel],r=this.fragLastKbps;i=r&&this.fragCurrent?this.fragCurrent.duration*e.maxBitrate/(1e3*r)+1:0}else i=0;const n=this.getBufferedFrag(e.currentTime+i);if(n){const t=this.followingBufferedFrag(n);if(t){this.abortCurrentFrag();const e=t.maxStartPTS?t.maxStartPTS:t.start,i=t.duration,r=Math.max(n.end,e+Math.min(Math.max(i-this.config.maxFragLookUpTolerance,i*(this.couldBacktrack?.5:.125)),i*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(r,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const t=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,t&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.state){case vr:case yr:case Er:case Sr:case Ar:this.state=pr}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(t,e){super.flushMainBuffer(t,e,this.altAudio?"video":null)}onMediaAttached(t,e){super.onMediaAttached(t,e);const i=e.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),i.addEventListener("playing",this.onvplaying),i.addEventListener("seeked",this.onvseeked),this.gapController=new Ya(this.config,i,this.fragmentTracker,this.hls)}onMediaDetaching(){const{media:t}=this;t&&this.onvplaying&&this.onvseeked&&(t.removeEventListener("playing",this.onvplaying),t.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),super.onMediaDetaching()}onMediaPlaying(){this.tick()}onMediaSeeked(){const t=this.media,e=t?t.currentTime:null;S(e)&&this.log(`Media seeked to ${e.toFixed(3)}`);const i=this.getMainFwdBufferInfo();null!==i&&0!==i.len?this.tick():this.warn(`Main forward buffer length on "seeked" event ${i?i.len:"empty"})`)}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(R.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=this.fragLastKbps=0,this.levels=this.fragPlaying=this.backtrackFragment=this.levelLastLoaded=null,this.altAudio=this.audioOnly=this.startFragRequested=!1}onManifestParsed(t,e){let i=!1,r=!1;e.levels.forEach((t=>{const e=t.audioCodec;e&&(i=i||-1!==e.indexOf("mp4a.40.2"),r=r||-1!==e.indexOf("mp4a.40.5"))})),this.audioCodecSwitch=i&&r&&!function(){var t;const e=$a();return"function"==typeof(null==e||null==(t=e.prototype)?void 0:t.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startFragRequested=!1}onLevelLoading(t,e){const{levels:i}=this;if(!i||this.state!==pr)return;const r=i[e.level];(!r.details||r.details.live&&this.levelLastLoaded!==r||this.waitForCdnTuneIn(r.details))&&(this.state=kr)}onLevelLoaded(t,e){var i;const{levels:r}=this,s=e.level,n=e.details,a=n.totalduration;if(!r)return void this.warn(`Levels were reset while loading level ${s}`);this.log(`Level ${s} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""}, cc [${n.startCC}, ${n.endCC}] duration:${a}`);const o=r[s],l=this.fragCurrent;!l||this.state!==yr&&this.state!==Er||l.level!==e.level&&l.loader&&this.abortCurrentFrag();let h=0;if(n.live||null!=(i=o.details)&&i.live){var d;if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;h=this.alignPlaylists(n,o.details,null==(d=this.levelLastLoaded)?void 0:d.details)}if(o.details=n,this.levelLastLoaded=o,this.hls.trigger(R.LEVEL_UPDATED,{details:n,level:s}),this.state===kr){if(this.waitForCdnTuneIn(n))return;this.state=pr}this.startFragRequested?n.live&&this.synchronizeToLiveEdge(n):this.setStartPosition(n,h),this.tick()}_handleFragmentLoadProgress(t){var e;const{frag:i,part:r,payload:s}=t,{levels:n}=this;if(!n)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);const a=n[i.level],o=a.details;if(!o)return this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),void this.fragmentTracker.removeFragment(i);const l=a.videoCodec,h=o.PTSKnown||!o.live,d=null==(e=i.initSegment)?void 0:e.data,u=this._getAudioCodec(a),c=this.transmuxer=this.transmuxer||new Os(this.hls,_e,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=r?r.index:-1,g=-1!==f,m=new Zi(i.level,i.sn,i.stats.chunkCount,s.byteLength,f,g),p=this.initPTS[i.cc];c.push(s,d,u,l,i,r,o.totalduration,h,m,p)}onAudioTrackSwitching(t,e){const i=this.altAudio;if(!!!e.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const t=this.fragCurrent;t&&(this.log("Switching to main audio track, cancel main fragment load"),t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();const t=this.hls;i&&(t.trigger(R.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),t.trigger(R.AUDIO_TRACK_SWITCHED,e)}}onAudioTrackSwitched(t,e){const i=e.id,r=!!this.hls.audioTracks[i].url;if(r){const t=this.videoBuffer;t&&this.mediaBuffer!==t&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=t)}this.altAudio=r,this.tick()}onBufferCreated(t,e){const i=e.tracks;let r,s,n=!1;for(const t in i){const e=i[t];if("main"===e.id){if(s=t,r=e,"video"===t){const e=i[t];e&&(this.videoBuffer=e.buffer)}}else n=!0}n&&r?(this.log(`Alternate track found, use ${s}.buffered to schedule main fragment loading`),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}onFragBuffered(t,e){const{frag:i,part:r}=e;if(i&&i.type!==_e)return;if(this.fragContextChanged(i))return this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===Ar&&(this.state=pr));const s=r?r.stats:i.stats;this.fragLastKbps=Math.round(8*s.total/(s.buffering.end-s.loading.first)),"initSegment"!==i.sn&&(this.fragPrevious=i),this.fragBufferedComplete(i,r)}onError(t,e){var i;if(e.fatal)this.state=Rr;else switch(e.details){case k.FRAG_GAP:case k.FRAG_PARSING_ERROR:case k.FRAG_DECRYPT_ERROR:case k.FRAG_LOAD_ERROR:case k.FRAG_LOAD_TIMEOUT:case k.KEY_LOAD_ERROR:case k.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(_e,e);break;case k.LEVEL_LOAD_ERROR:case k.LEVEL_LOAD_TIMEOUT:case k.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==kr||(null==(i=e.context)?void 0:i.type)!==Ie||(this.state=pr);break;case k.BUFFER_APPEND_ERROR:case k.BUFFER_FULL_ERROR:if(!e.parent||"main"!==e.parent)return;if(e.details===k.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(e)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case k.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}checkBuffer(){const{media:t,gapController:e}=this;if(t&&e&&t.readyState){if(this.loadedmetadata||!Ji.getBuffered(t).length){const t=this.state!==pr?this.fragCurrent:null;e.poll(this.lastCurrentTime,t)}this.lastCurrentTime=t.currentTime}}onFragLoadEmergencyAborted(){this.state=pr,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==U||this.audioOnly&&!this.altAudio){const t=(e===B?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(t,e,_e),this.tick()}}onLevelsUpdated(t,e){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=e.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:t}=this;if(!t)return;const e=t.currentTime;let i=this.startPosition;if(i>=0&&e<i){if(t.seeking)return void this.log(`could not seek to ${i}, already seeking at ${e}`);const r=Ji.getBuffered(t),s=(r.length?r.start(0):0)-i;s>0&&(s<this.config.maxBufferHole||s<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${s} to match buffer start`),i+=s,this.startPosition=i),this.log(`seek to target start position ${i} from current time ${e}`),t.currentTime=i}}_getAudioCodec(t){let e=this.config.defaultAudioCodec||t.audioCodec;return this.audioCodecSwap&&e&&(this.log("Swapping audio codec"),e=-1!==e.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),e}_loadBitrateTestFrag(t,e){t.bitrateTest=!0,this._doFragLoad(t,e).then((i=>{const{hls:r}=this;if(!i||this.fragContextChanged(t))return;e.fragmentError=0,this.state=pr,this.startFragRequested=!1,this.bitrateTest=!1;const s=t.stats;s.parsing.start=s.parsing.end=s.buffering.start=s.buffering.end=self.performance.now(),r.trigger(R.FRAG_LOADED,i),t.bitrateTest=!1}))}_handleTransmuxComplete(t){var e;const i="main",{hls:r}=this,{remuxResult:s,chunkMeta:n}=t,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:h}=a,{video:d,text:u,id3:c,initSegment:f}=s,{details:g}=h,m=this.altAudio?void 0:s.audio;if(this.fragContextChanged(o))this.fragmentTracker.removeFragment(o);else{if(this.state=Sr,f){if(null!=f&&f.tracks){const t=o.initSegment||o;this._bufferInitSegment(h,f.tracks,t,n),r.trigger(R.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:i,tracks:f.tracks})}const t=f.initPTS,e=f.timescale;S(t)&&(this.initPTS[o.cc]={baseTime:t,timescale:e},r.trigger(R.INIT_PTS_FOUND,{frag:o,id:i,initPTS:t,timescale:e}))}if(d&&g&&"initSegment"!==o.sn){const t=g.fragments[o.sn-1-g.startSN],e=o.sn===g.startSN,i=!t||o.cc>t.cc;if(!1!==s.independent){const{startPTS:t,endPTS:r,startDTS:s,endDTS:a}=d;if(l)l.elementaryStreams[d.type]={startPTS:t,endPTS:r,startDTS:s,endDTS:a};else if(d.firstKeyFrame&&d.independent&&1===n.id&&!i&&(this.couldBacktrack=!0),d.dropped&&d.independent){const s=this.getMainFwdBufferInfo(),n=(s?s.end:this.getLoadPosition())+this.config.maxBufferHole,l=d.firstKeyFramePTS?d.firstKeyFramePTS:t;if(!e&&n<l-this.config.maxBufferHole&&!i)return void this.backtrack(o);i&&(o.gap=!0),o.setElementaryStreamInfo(d.type,o.start,r,o.start,a,!0)}else e&&t>2&&(o.gap=!0);o.setElementaryStreamInfo(d.type,t,r,s,a),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(d,o,l,n,e||i)}else{if(!e&&!i)return void this.backtrack(o);o.gap=!0}}if(m){const{startPTS:t,endPTS:e,startDTS:i,endDTS:r}=m;l&&(l.elementaryStreams[U]={startPTS:t,endPTS:e,startDTS:i,endDTS:r}),o.setElementaryStreamInfo(U,t,e,i,r),this.bufferFragmentData(m,o,l,n)}if(g&&null!=c&&null!=(e=c.samples)&&e.length){const t={id:i,frag:o,details:g,samples:c.samples};r.trigger(R.FRAG_PARSING_METADATA,t)}if(g&&u){const t={id:i,frag:o,details:g,samples:u.samples};r.trigger(R.FRAG_PARSING_USERDATA,t)}}}_bufferInitSegment(t,e,i,r){if(this.state!==Sr)return;this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&delete e.audio;const{audio:s,video:n,audiovideo:a}=e;if(s){let e=t.audioCodec;const i=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){e&&(e=-1!==e.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const t=s.metadata;t&&"channelCount"in t&&1!==(t.channelCount||1)&&-1===i.indexOf("firefox")&&(e="mp4a.40.5")}e&&-1!==e.indexOf("mp4a.40.5")&&-1!==i.indexOf("android")&&"audio/mpeg"!==s.container&&(e="mp4a.40.2",this.log(`Android: force audio codec to ${e}`)),t.audioCodec&&t.audioCodec!==e&&this.log(`Swapping manifest audio codec "${t.audioCodec}" for "${e}"`),s.levelCodec=e,s.id="main",this.log(`Init audio buffer, container:${s.container}, codecs[selected/level/parsed]=[${e||""}/${t.audioCodec||""}/${s.codec}]`)}n&&(n.levelCodec=t.videoCodec,n.id="main",this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${t.videoCodec||""}/${n.codec}]`)),a&&this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${t.codecs}/${a.codec}]`),this.hls.trigger(R.BUFFER_CODECS,e),Object.keys(e).forEach((t=>{const s=e[t].initSegment;null!=s&&s.byteLength&&this.hls.trigger(R.BUFFER_APPENDING,{type:t,data:s,frag:i,part:null,chunkMeta:r,parent:i.type})})),this.tickImmediate()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,_e)}backtrack(t){this.couldBacktrack=!0,this.backtrackFragment=t,this.resetTransmuxer(),this.flushBufferGap(t),this.fragmentTracker.removeFragment(t),this.fragPrevious=null,this.nextLoadPosition=t.start,this.state=pr}checkFragmentChanged(){const t=this.media;let e=null;if(t&&t.readyState>1&&!1===t.seeking){const i=t.currentTime;if(Ji.isBuffered(t,i)?e=this.getAppendedFrag(i):Ji.isBuffered(t,i+.1)&&(e=this.getAppendedFrag(i+.1)),e){this.backtrackFragment=null;const t=this.fragPlaying,i=e.level;t&&e.sn===t.sn&&t.level===i||(this.fragPlaying=e,this.hls.trigger(R.FRAG_CHANGED,{frag:e}),t&&t.level===i||this.hls.trigger(R.LEVEL_SWITCHED,{level:i}))}}}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){const t=this.media;return t?this.fragPlaying||this.getAppendedFrag(t.currentTime):null}get currentProgramDateTime(){const t=this.media;if(t){const e=t.currentTime,i=this.currentFrag;if(i&&S(e)&&S(i.programDateTime)){const t=i.programDateTime+1e3*(e-i.start);return new Date(t)}}return null}get currentLevel(){const t=this.currentFrag;return t?t.level:-1}get nextBufferedFrag(){const t=this.currentFrag;return t?this.followingBufferedFrag(t):null}get forceStartLoad(){return this._forceStartLoad}}class ja{static get version(){return"1.5.14"}static isMSESupported(){return Va()}static isSupported(){return function(){if(!Va())return!1;const t=re();return"function"==typeof(null==t?void 0:t.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some((e=>t.isTypeSupported(oe(e,"video"))))||["mp4a.40.2","fLaC"].some((e=>t.isTypeSupported(oe(e,"audio")))))}()}static getMediaSource(){return re()}static get Events(){return R}static get ErrorTypes(){return b}static get ErrorDetails(){return k}static get DefaultConfig(){return ja.defaultConfig?ja.defaultConfig:Fa}static set DefaultConfig(t){ja.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this.started=!1,this._emitter=new Ms,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,this.triggeringException=void 0,function(t,e){if("object"==typeof console&&!0===t||"object"==typeof t){C(t,"debug","log","info","warn","error");try{w.log(`Debug logs enabled for "${e}" in hls.js version 1.5.14`)}catch(t){w=I}}else w=I}(t.debug||!1,"Hls instance");const e=this.config=function(t,e){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==e.liveMaxLatencyDurationCount&&(void 0===e.liveSyncDurationCount||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==e.liveMaxLatencyDuration&&(void 0===e.liveSyncDuration||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const i=Na(t),r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((t=>{const s=`${"level"===t?"playlist":t}LoadPolicy`,n=void 0===e[s],a=[];r.forEach((r=>{const o=`${t}Loading${r}`,l=e[o];if(void 0!==l&&n){a.push(o);const t=i[s].default;switch(e[s]={default:t},r){case"TimeOut":t.maxLoadTimeMs=l,t.maxTimeToFirstByteMs=l;break;case"MaxRetry":t.errorRetry.maxNumRetry=l,t.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":t.errorRetry.retryDelayMs=l,t.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":t.errorRetry.maxRetryDelayMs=l,t.timeoutRetry.maxRetryDelayMs=l}}})),a.length&&_.warn(`hls.js config: "${a.join('", "')}" setting(s) are deprecated, use "${s}": ${JSON.stringify(e[s])}`)})),v(v({},i),e)}(ja.DefaultConfig,t);this.userConfig=t,e.progressive&&Ua(e);const{abrController:i,bufferController:r,capLevelController:s,errorController:n,fpsController:a}=e,o=new n(this),l=this.abrController=new i(this),h=this.bufferController=new r(this),d=this.capLevelController=new s(this),u=new a(this),c=new Fe(this),f=new Xe(this),g=e.contentSteeringController,m=g?new g(this):null,p=this.levelController=new Ga(this,m),y=new qi(this),E=new Ha(this.config),T=this.streamController=new Wa(this,y,E);d.setStreamController(T),u.setStreamController(T);const S=[c,p,T];m&&S.splice(1,0,m),this.networkControllers=S;const A=[l,h,d,u,f,y];this.audioTrackController=this.createController(e.audioTrackController,S);const L=e.audioStreamController;L&&S.push(new L(this,y,E)),this.subtitleTrackController=this.createController(e.subtitleTrackController,S);const b=e.subtitleStreamController;b&&S.push(new b(this,y,E)),this.createController(e.timelineController,A),E.emeController=this.emeController=this.createController(e.emeController,A),this.cmcdController=this.createController(e.cmcdController,A),this.latencyController=this.createController(ze,A),this.coreComponents=A,S.push(o);const k=o.onErrorOut;"function"==typeof k&&this.on(R.ERROR,k,o)}createController(t,e){if(t){const i=new t(this);return e&&e.push(i),i}return null}on(t,e,i=this){this._emitter.on(t,e,i)}once(t,e,i=this){this._emitter.once(t,e,i)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,e,i=this,r){this._emitter.off(t,e,i,r)}listeners(t){return this._emitter.listeners(t)}emit(t,e,i){return this._emitter.emit(t,e,i)}trigger(t,e){if(this.config.debug)return this.emit(t,t,e);try{return this.emit(t,t,e)}catch(e){if(_.error("An internal error happened while handling event "+t+'. Error message: "'+e.message+'". Here is a stacktrace:',e),!this.triggeringException){this.triggeringException=!0;const i=t===R.ERROR;this.trigger(R.ERROR,{type:b.OTHER_ERROR,details:k.INTERNAL_EXCEPTION,fatal:i,event:t,error:e}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){_.log("destroy"),this.trigger(R.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach((t=>t.destroy())),this.networkControllers.length=0,this.coreComponents.forEach((t=>t.destroy())),this.coreComponents.length=0;const t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){_.log("attachMedia"),this._media=t,this.trigger(R.MEDIA_ATTACHING,{media:t})}detachMedia(){_.log("detachMedia"),this.trigger(R.MEDIA_DETACHING,void 0),this._media=null}loadSource(t){this.stopLoad();const e=this.media,i=this.url,r=this.url=m.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,_.log(`loadSource:${r}`),e&&i&&(i!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(e)),this.trigger(R.MANIFEST_LOADING,{url:t})}startLoad(t=-1){_.log(`startLoad(${t})`),this.started=!0,this.networkControllers.forEach((e=>{e.startLoad(t)}))}stopLoad(){_.log("stopLoad"),this.started=!1,this.networkControllers.forEach((t=>{t.stopLoad()}))}resumeBuffering(){this.started&&this.networkControllers.forEach((t=>{"fragmentLoader"in t&&t.startLoad(-1)}))}pauseBuffering(){this.networkControllers.forEach((t=>{"fragmentLoader"in t&&t.stopLoad()}))}swapAudioCodec(){_.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){_.log("recoverMediaError");const t=this._media;this.detachMedia(),t&&this.attachMedia(t)}removeLevel(t){this.levelController.removeLevel(t)}get levels(){const t=this.levelController.levels;return t||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){_.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){_.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){_.log(`set loadLevel:${t}`),this.levelController.manualLevel=t}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(t){this.levelController.nextLoadLevel=t}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(t){_.log(`set firstLevel:${t}`),this.levelController.firstLevel=t}get startLevel(){const t=this.levelController.startLevel;return-1===t&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t}set startLevel(t){_.log(`set startLevel:${t}`),-1!==t&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(t){const e=!!t;e!==this.config.capLevelToPlayerSize&&(e?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=e)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimate():NaN}set bandwidthEstimate(t){this.abrController.resetEstimator(t)}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(_.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){(function(t){return Qe.indexOf(t)>-1})(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:t,config:{minAutoBitrate:e}}=this;if(!t)return 0;const i=t.length;for(let r=0;r<i;r++)if(t[r].maxBitrate>=e)return r;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:e,maxHdcpLevel:i}=this;let r;if(r=-1===e&&null!=t&&t.length?t.length-1:e,i)for(let e=r;e--;){const r=t[e].attrs["HDCP-LEVEL"];if(r&&r<=i)return e}return r}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(t){this.abrController.nextAutoLevel=t}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}setAudioOption(t){var e;return null==(e=this.audioTrackController)?void 0:e.setAudioOption(t)}setSubtitleOption(t){var e;return null==(e=this.subtitleTrackController)||e.setSubtitleOption(t),null}get allAudioTracks(){const t=this.audioTrackController;return t?t.allAudioTracks:[]}get audioTracks(){const t=this.audioTrackController;return t?t.audioTracks:[]}get audioTrack(){const t=this.audioTrackController;return t?t.audioTrack:-1}set audioTrack(t){const e=this.audioTrackController;e&&(e.audioTrack=t)}get allSubtitleTracks(){const t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}get subtitleTracks(){const t=this.subtitleTrackController;return t?t.subtitleTracks:[]}get subtitleTrack(){const t=this.subtitleTrackController;return t?t.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(t){const e=this.subtitleTrackController;e&&(e.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return!!t&&t.subtitleDisplay}set subtitleDisplay(t){const e=this.subtitleTrackController;e&&(e.subtitleDisplay=t)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(t){this.config.lowLatencyMode=t}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}}ja.defaultConfig=void 0;var qa=i(39473),Xa=i.n(qa),za=function(t,e,i,r,s,n){function a(t){if(void 0!==t&&"function"!=typeof t)throw new TypeError("Function expected");return t}for(var o,l=r.kind,h="getter"===l?"get":"setter"===l?"set":"value",d=!e&&t?r.static?t:t.prototype:null,u=e||(d?Object.getOwnPropertyDescriptor(d,r.name):{}),c=!1,f=i.length-1;f>=0;f--){var g={};for(var m in r)g[m]="access"===m?{}:r[m];for(var m in r.access)g.access[m]=r.access[m];g.addInitializer=function(t){if(c)throw new TypeError("Cannot add initializers after decoration has completed");n.push(a(t||null))};var p=(0,i[f])("accessor"===l?{get:u.get,set:u.set}:u[h],g);if("accessor"===l){if(void 0===p)continue;if(null===p||"object"!=typeof p)throw new TypeError("Object expected");(o=a(p.get))&&(u.get=o),(o=a(p.set))&&(u.set=o),(o=a(p.init))&&s.unshift(o)}else(o=a(p))&&("field"===l?s.unshift(o):u[h]=o)}d&&Object.defineProperty(d,r.name,u),c=!0},Qa=function(t,e,i){for(var r=arguments.length>2,s=0;s<e.length;s++)i=r?e[s].call(t,i):e[s].call(t);return r?i:void 0},Ja=function(t,e,i){return"symbol"==typeof e&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(t,"name",{configurable:!0,value:i?"".concat(i," ",e):e})},Za=function(t,e,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(t,i):s?s.value=i:e.set(t,i),i},to=function(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)};let eo=(()=>{var t,e;let i,l,h=[a.JW],d=[],u=n.F;l=class extends u{get hlsInstance(){return this.hls}constructor(i,r){super(i,r),t.set(this,null),e.set(this,!1),this.dvrSegmentDuration=0,this.dvrWindowRight=0,this.dvrWindowLeft=0,this.dvrTime=-1,this.dvrRightToLiveOffset=0,this.dvrToDateSync=null,this.recoverDecodingErrorDate=-1,this.recoverSwapAudioCodecDate=-1,this.networkRecoveryHandler=null,this.hls=null,this.lastTickerUpdate=-1,this._dvrModeEnabled=!1,this._dvrWindow=0,this._dvrIsLive=!1,this.dvrTime=-1,this.dvrRightToLiveOffset=0,this.dvrToDateSync=null}applyVideoScale(t){this.mediaElement.style.objectFit="COVER"===t?"cover":"contain"}onError(t){var e;"error"===t.type&&t.currentTarget instanceof HTMLMediaElement&&(null===(e=t.currentTarget.error)||void 0===e?void 0:e.code)===MediaError.MEDIA_ERR_DECODE?this.handleHLSMediaError():this.handleError(t)}onSeekEnd(t){super.onSeekEnd(t),this.updateDVRValues()}onDurationChange(t){super.onDurationChange(t),this.dvrWindowRight=this.mediaElement.duration-this.dvrRightToLiveOffset,this.dvrWindowLeft=this.dvrWindowRight-this._dvrWindow}addSource(i){this.resetNetworkErrorHandler(),Za(this,e,!1,"f");const s=Xa().isSupported()&&i.url.indexOf("m3u8")>0;if(this.hls&&(this.hls.destroy(),this.hls=null),s){Za(this,t,i,"f");const s={debug:!1,enableWorker:!0,liveSyncDurationCount:2,capLevelToPlayerSize:!0,startFragPrefetch:!0,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3,manifestLoadingMaxRetry:2,maifestLoadingRetryDelay:500,manifestMaxRetryTimeout:64e3,levelLoadingMaxRetry:3,levelLoadingRetryDelay:500,levelLoadingMaxRetryTimeout:2e3},n=(0,o.$N)(this.pc.getPluginData("plugin-hls"),this.mc.getPluginData("plugin-hls")),a=(0,o.$N)(s,n);this._pendingSeek>0&&(a.startPosition=this._pendingSeek),this.log("HLS.js config:",a),this.hls=new(Xa())(a),this.hls.subtitleDisplay=!1,this.recoverDecodingErrorDate=-1,this.recoverSwapAudioCodecDate=-1,this.hls.attachMedia(this.mediaElement),this.hls.on(Xa().Events.MEDIA_ATTACHED,(()=>{var t;this.player.pixelController&&this.player.pixelController.loadStream(i.url),null===(t=this.hls)||void 0===t||t.loadSource(i.url),this.isPlaying()&&this.mediaElement.play()}));let l=!1;this.hls.on(Xa().Events.ERROR,((t,e)=>{var r,s,n,a,o,h,d,u,c,f,g,m,p;if(e.fatal)switch(e.type){case Xa().ErrorTypes.NETWORK_ERROR:if(this.warn("fatal network error encountered",e.details,e.reason,e.networkDetails,null===(r=navigator.connection)||void 0===r?void 0:r.downlink),"object"==typeof navigator.connection&&(null!==(s=navigator.connection.downlink)&&void 0!==s?s:1)<=0)return this.warn("navigator says offline - add change handler"),this.networkRecoveryHandler=()=>{var t;this.log("network change, try to recover"),l=!0,null===(t=this.hls)||void 0===t||t.startLoad()},void navigator.connection.addEventListener("change",this.networkRecoveryHandler);if(null==this.hls||l){this.error("irrecoverable"),null===(n=this.hls)||void 0===n||n.destroy();const t=e.networkDetails;this.handleError(`${e.details} ${null!==(a=e.reason)&&void 0!==a?a:""} - Status: ${null!==(o=t.status)&&void 0!==o?o:-1} ${null!==(h=t.statusText)&&void 0!==h?h:""} - Response: ${null!==(d=t.response)&&void 0!==d?d:"null"}`)}else l=!0,[k.MANIFEST_LOAD_ERROR,k.MANIFEST_LOAD_TIMEOUT,k.MANIFEST_PARSING_ERROR,k.MANIFEST_INCOMPATIBLE_CODECS_ERROR].includes(e.details)||(null!==(f=null===(c=null===(u=this.hls)||void 0===u?void 0:u.levels)||void 0===c?void 0:c.length)&&void 0!==f?f:0)<1?(this.warn("manifest not loaded, try complete re-set"),null===(g=this.hls)||void 0===g||g.loadSource(i.url),this.mediaElement.play()):(this.log("try to recover"),null===(m=this.hls)||void 0===m||m.startLoad());break;case Xa().ErrorTypes.MEDIA_ERROR:case Xa().ErrorTypes.MUX_ERROR:this.warn("fatal media error encountered, try to recover"),this.handleHLSMediaError();break;default:this.error("fatal error",t,e),null===(p=this.hls)||void 0===p||p.destroy(),this.handleError()}})),this.hls.on(Xa().Events.LEVEL_LOADED,((t,i)=>{var s,n;this._dvrModeEnabled=this.mc.isDvrEnabled&&i.details.live,this.mc.isLive&&!i.details.live&&this.log("config mismatch: MC is live, stream is not!"),this.dvrSegmentDuration=i.details.targetduration,this.dvrRightToLiveOffset=(null!==(n=null===(s=this.hls)||void 0===s?void 0:s.config.liveSyncDurationCount)&&void 0!==n?n:0)*this.dvrSegmentDuration+1,this._dvrWindow=i.details.totalduration-this.dvrRightToLiveOffset,(this.dvrTime<0||isNaN(this.dvrTime))&&(this.dvrTime=this.getDuration()),this.updateDVRValues(),to(this,e,"f")||(this.player.loop.dispatchEvent(r.a.EVENT_STREAM_LOADED,{}),Za(this,e,!0,"f"))})),this.hls.on(Xa().Events.FRAG_LOADED,((t,e)=>{const i=e.frag;if("main"===i.type)if(!i.programDateTime||isNaN(this.dvrWindowLeft)){if(i.sn&&"initSegment"!==i.sn&&i.duration&&!isNaN(this.dvrWindowLeft)){let t=i.duration;const e=i.tagList||[];for(const i of e)if("INF"===i[0]){t=Number(i[1]);break}const r=i.sn*t*1e3,s=new Date(r),n=new Date;if(s.getFullYear()!==n.getFullYear())return;const a=i.start-this.dvrWindowLeft;this.dvrToDateSync={rel:a,real:r,at:Date.now()}}}else{const t=i.start-this.dvrWindowLeft;this.dvrToDateSync={rel:t,real:i.programDateTime,at:Date.now()}}})),this.hls.on(Xa().Events.AUDIO_TRACKS_UPDATED,((t,e)=>{var i,r,s;this.audioTracks=[];const n=null!==(r=null===(i=this.hls)||void 0===i?void 0:i.audioTrack)&&void 0!==r?r:-1;for(const t of e.audioTracks){const e=n<0?t.default:n===this.audioTracks.length,i=(0,o.i5)(t.attrs,"CHANNELS")?parseInt(String(t.attrs.CHANNELS),10):void 0,r=(0,o.i5)(t.attrs,"CHARACTERISTICS")?String(t.attrs.CHARACTERISTICS).includes("public.accessibility.describes-video"):/audio\s*des[ck]ription/i.test(t.name),a={id:String(t.id),default:t.default,label:t.name,language:null!==(s=t.lang)&&void 0!==s?s:"und",isSpeechOptimized:/klare\s*sprache/i.test(t.name),isSimpleLanguage:/einfache\s*sprache/i.test(t.name),enabled:e,channelCount:i,isAudioDescription:r};this.audioTracks.push(a),t.default&&(this.audioTrack=a)}this.onAudioTracksChanged()})),this.hls.on(Xa().Events.AUDIO_TRACK_SWITCHED,((t,e)=>{const i=String(e.id);for(const t of this.audioTracks)i===t.id&&(this.audioTrack=t);this.player.loop.dispatchEvent(r.a.CURRENT_AUDIO_TRACK_CHANGED,{audioTrack:this.audioTrack})}))}else Za(this,t,null,"f"),this.handleError()}handleHLSMediaError(){var t,e,i,r;const s=Date.now();-1===this.recoverDecodingErrorDate||s-this.recoverDecodingErrorDate>3e3?(this.recoverDecodingErrorDate=s,this.log(`try to recover media Error @ ${this.getCurrentTime()}`),null===(t=this.hls)||void 0===t||t.recoverMediaError()):-1===this.recoverSwapAudioCodecDate||s-this.recoverSwapAudioCodecDate>3e3?(this.recoverSwapAudioCodecDate=Date.now(),this.log(`try to swap Audio Codec and recover media Error @ ${this.getCurrentTime()}`),null===(e=this.hls)||void 0===e||e.swapAudioCodec(),null===(i=this.hls)||void 0===i||i.recoverMediaError()):(this.log("cannot recover, last media error recovery failed ..."),null===(r=this.hls)||void 0===r||r.destroy(),this.handleError())}resetNetworkErrorHandler(){var t;this.networkRecoveryHandler&&(null===(t=navigator.connection)||void 0===t||t.removeEventListener("change",this.networkRecoveryHandler))}canSeek(){return!0}getDvrToDateSync(){return this.dvrToDateSync}setCurrentTime(t,e,i,r){void 0===e&&(e=!1),void 0===i&&(i=!1),void 0===r&&(r=!1),this.dvrToDateSync&&t>=this.dvrRelToUnix(0)&&(t=this.dvrUnixToRel(t));let s=Math.min(t,this.getDuration()-.1);if(this.setSeekEventTimestamps(this.getCurrentTime(),t),this._dvrModeEnabled){const e=t/this.getDuration();s=this.dvrWindowLeft+(this.dvrWindowRight-this.dvrWindowLeft)*e,this.dvrTime=t}this.setCurrentTimeRaw(s,e,i,r),this.player.model.time=t}getCurrentTime(){return this._dvrModeEnabled?this.dvrTime:super.getCurrentTime()}getDuration(){return this._dvrModeEnabled?this._dvrWindow:super.getDuration()}seekToLive(){var t,e;this.setCurrentTime(null!==(e=null===(t=this.hls)||void 0===t?void 0:t.liveSyncPosition)&&void 0!==e?e:this.getDuration())}updateTicker(){if(this._dvrModeEnabled){const t=performance.now();-1!==this.lastTickerUpdate&&(this.model.playstate===s.R.PLAYSTATE_PAUSED||this.model.playstate===s.R.PLAYSTATE_PLAYING&&this.playbackStalled?this.dvrTime=Math.max(0,this.dvrTime-(t-this.lastTickerUpdate)/1e3):this.model.playstate===s.R.PLAYSTATE_PLAYING&&(this.dvrTime+=(this.model.playbackRate-1)*((t-this.lastTickerUpdate)/1e3),this.dvrTime>=this.getDuration()&&(this.dvrTime=this.getDuration()))),this.lastTickerUpdate=t}super.updateTicker()}stopTicker(){this.lastTickerUpdate=-1,super.stopTicker()}updateDVRValues(){this.onDVRCallback(this._dvrModeEnabled,this._dvrWindow,this.dvrTime>=this.getDuration())}play(){this.model.playstate===s.R.PLAYSTATE_PAUSED&&this.mc.isLive&&!this.mc.isDvrEnabled&&this.seekToLive(),super.play()}getAudioTracks(){return null===this.hls?[]:this.audioTracks}setAudioTrack(t){if(this.audioTrack=t,null===this.hls)return;const e=parseInt(t.id,10);this.hls.audioTrack!==e&&(this.hls.audioTrack=e)}setAudioTrackById(t){if(null===this.hls)return;const e=parseInt(t,10);this.hls.audioTrack!==e&&(this.hls.audioTrack=e)}getAudioTrack(){return this.audioTrack}setWebVTTSubtitlesEnabled(t){this.hls&&this.hls.subtitleDisplay!==t&&(this.hls.subtitleDisplay=t)}dispose(){this.resetNetworkErrorHandler(),this.hls&&(this.hls.destroy(),this.hls=null),super.dispose()}debugString(){var e,i,r,s;return this.hls?`AutoLevel: ${String(this.hls.autoLevelEnabled)} | Quality ${(null!==(e=this.hls.currentLevel)&&void 0!==e?e:-2)+1} of ${null!==(r=null===(i=this.hls.levels)||void 0===i?void 0:i.length)&&void 0!==r?r:-1}${!0===(null===(s=to(this,t,"f"))||void 0===s?void 0:s.isAdaptiveQualitySelectable)?" (sub-selectable)":""}`:"no instance"}debugQualityLevel(){var t,e,i,r,s;return[null!==(e=null===(t=this.hls)||void 0===t?void 0:t.currentLevel)&&void 0!==e?e:-1,null!==(s=null===(r=null===(i=this.hls)||void 0===i?void 0:i.levels)||void 0===r?void 0:r.length)&&void 0!==s?s:1]}get subQualities(){var t;const e=[{level:-1,label:"Auto",width:-1}];return null===(t=this.hls)||void 0===t||t.levels.forEach(((t,i)=>{var r;e.push({level:i,label:null!==(r=t.name)&&void 0!==r?r:(0,o.a7)(t.width),width:t.width,debug:`${t.codecSet}@${Number.isFinite(t.bitrate)?t.bitrate/1e3+"k":t.bitrate}`}),e[0].width=Math.max(e[0].width,t.width)})),e}selectSubQuality(t){null!==this.hls&&(this.hls.currentLevel=t<0||t>this.hls.levels.length?-1:t)}get currentSubQuality(){return null==this.hls||this.hls.autoLevelEnabled?-1:this.hls.currentLevel}getClassTypeString(){return"HLSCtrl"}};return t=new WeakMap,e=new WeakMap,Ja(l,"HLSCtrl"),(()=>{var t;const e="function"==typeof Symbol&&Symbol.metadata?Object.create(null!==(t=u[Symbol.metadata])&&void 0!==t?t:null):void 0;za(null,i={value:l},h,{kind:"class",name:l.name,metadata:e},null,d),l=i.value,e&&Object.defineProperty(l,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:e}),Qa(l,d)})(),l})();const io={Generator:i(73731).X,Controller:eo}}}]);
|